text:
Q: Django Logging: ValueError: Unable to configure handler 'gunicorn' I configured logging for a new Django project, and here is the code for my settings.py:
LOGGING = {
"version": 1,
# The version number of our log
"disable_existing_loggers": False,
# django uses some of its own loggers for internal operations. In case you want to disable them just replace the False above with true.
# A handler for WARNING. It is basically writing the WARNING messages into a file called WARNING.log
"formatters": {
    "main_formatter": {
        "format": "{asctime}-{levelname}-{module}-{funcName}-{message}",
        "style": "{",
    },
},
"handlers": {
    "warnfile": {
        "level": "WARNING",
        "class": "logging.FileHandler",
        "filename": BASE_DIR / "warning.log",
    },
    "errorfile": {
        "level": "ERROR",
        "class": "logging.FileHandler",
        "filename": BASE_DIR / "error.log",
    },
    "gunicorn": {
        "level": "DEBUG",
        "class": "logging.handlers.RotatingFileHandler",
        "formatter": "verbose",
        "filename": BASE_DIR / "gunicorn.log",
        "maxBytes": 1024 * 1024 * 25,  # 100 mb
    },
},
# A logger for WARNING which has a handler called 'file'. A logger can have multiple handler
"loggers": {
    # notice the blank '', Usually you would put built in loggers like django or root here based on your needs
    "": {
        "handlers": [
            "warnfile",
            "errorfile",
        ],  # notice how file variable is called in handler which has been defined above
        "level": "WARNING",
        "propagate": True,
    },
    "gunicorn.errors": {
        "level": "DEBUG",
        "handlers": ["gunicorn"],
        "propagate": True,
    },
},
}

Let me explain: I want to put 2 kinds of logs: warnings, and errors, in 2 differents files. I also want a third file for gunicorn logs to monitor the server side.
When I run the server, I get the following error:
ValueError: Unable to configure handler 'gunicorn'

I also created all the files just in case the logger does't create them for me, but still no changes.
Here is my full traceback:
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 710, in configure_handler
    formatter = self.config['formatters'][formatter]
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 326, in __getitem__
    value = dict.__getitem__(self, key)
KeyError: 'verbose'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 565, in configure
    handler = self.configure_handler(handlers[name])
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 712, in configure_handler
    raise ValueError('Unable to set formatter '
ValueError: Unable to set formatter 'verbose'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "D:\Data\Dropbox\My Laptop\Tasbiq\V1\v1proj\v1env\lib\site-packages\sentry_sdk\integrations\threading.py", line 69, in run
    reraise(*_capture_exception())
  File "D:\Data\Dropbox\My Laptop\Tasbiq\V1\v1proj\v1env\lib\site-packages\sentry_sdk\_compat.py", line 56, in reraise
    raise value
  File "D:\Data\Dropbox\My Laptop\Tasbiq\V1\v1proj\v1env\lib\site-packages\sentry_sdk\integrations\threading.py", line 67, in run
    return old_run_func(self, *a, **kw)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "D:\Data\Dropbox\My Laptop\Tasbiq\V1\v1proj\v1env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "D:\Data\Dropbox\My Laptop\Tasbiq\V1\v1proj\v1env\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run
    autoreload.raise_last_exception()
  File "D:\Data\Dropbox\My Laptop\Tasbiq\V1\v1proj\v1env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "D:\Data\Dropbox\My Laptop\Tasbiq\V1\v1proj\v1env\lib\site-packages\django\core\management\__init__.py", line 398, in execute
    autoreload.check_errors(django.setup)()
  File "D:\Data\Dropbox\My Laptop\Tasbiq\V1\v1proj\v1env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "D:\Data\Dropbox\My Laptop\Tasbiq\V1\v1proj\v1env\lib\site-packages\django\__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "D:\Data\Dropbox\My Laptop\Tasbiq\V1\v1proj\v1env\lib\site-packages\django\utils\log.py", line 76, in configure_logging
    logging_config_func(logging_settings)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 811, in dictConfig
    dictConfigClass(config).configure()
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 572, in configure
    raise ValueError('Unable to configure handler '
ValueError: Unable to configure handler 'gunicorn'

A: You need to define a Formatter available under the key verbose, for example like this:
"formatters": {
    "verbose": {
        "format": "%(levelname)-8s - %(message)s"
    }
}

It needs to be at the same level as handlers and loggers in your configuration.


text:
Q: How to recover partitions? my partitions are lost and my datas are also lost when I use ntfsfix on my hard drive. For the partition table like this:
sdb        disk
  └─sdb1     unallocated
  └─sdb5     /DATA1
  └─sdb6     /DATA2

Instead of using ntfsfix on /dev/sdb5 or /dev/sdb6, my brain told me to try using it on /dev/sdb, and as a result all my partitions were lost and my data was lost.
Is there a way to restore it?, I've tried using testdisk it doesn't work, or maybe I'm using testdisk wrong.

A: See the good advice in the post
Recovering broken or deleted NTFS partitions.
The first point is to clone the disk, so as not to operate
directly on the damaged disk:
sudo ddrescue /dev/sdb /media/user/External/copy.img /media/user/External/status.log

You may then have luck with testdisk:
testdisk /media/External/copy.img

Follow the step-by-step prompts and you will be able to list the
contents of the partition with the P key,
assuming the disk is almost intact.
If the damage is more serious, you may try using
RecuperaBit,
described as:

A software which attempts to reconstruct file system structures and
recover files. Currently it supports only NTFS.
RecuperaBit attempts reconstruction of the directory structure
regardless of:

*

*missing partition table

*unknown partition boundaries

*partially-overwritten metadata

*quick format

Download the archive from GitHub and extract into a directory, then
create a directory for the output and start the program with:
mkdir /media/user/External/recovered_files
cd [full path of recuperabit]
pypy main.py /media/user/External/copy.img -o /media/user/External/recovered_files -s /media/user/External/savefile.save

This will take some time. To check the list of partitions that can be saved
use the following command:
recoverable

For recovering the partitions or folders, see the description of
RecuperaBit.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a Linux script that can show all hard drive information? I am looking for a Linux script that can be run from the command line, that can show all hard drives' information at the same time, such as name, UUID, mount point, TYPE, free space/available space/total size/use% in MB, etc.
I know the following command:
ls -l /dev/disk/by-uuid
lsblk
df -h
lsblk -o NAME,UUID -f
blkid -o list

But one script would be much easier. I don't know how to make script.

A: First create a file:
touch myscript.sh

Next edit the file (use your preferred editor):
vi myscript.sh

to save the file press esc key, type :wq, press enter key
Add what you want:
#!/bin/sh

ls -l /dev/disk/by-uuid
lsblk
df -h
lsblk -o NAME,UUID -f
blkid -o list

Make the file exactable:
chmod 775 myscript.sh

Run the script:
./myscript.sh
[OR]
sh myscript.sh

To take it one step further, add this line to you .bashrc file and source it:
vi ~/.bashrc

ADD this line at the bottom:

export PATH=$PATH:/absolute/path/of/directory/my/script/is/in

source ~/.bashrc

example:
export PATH=$PATH:/lhome/myuserfolder

Now you can be anywhere on your system and just type: myscript.sh and your script should run.


text:
Q: Add some data from php function into mpdf I have php function, whose create some blocks with data from loop.
finction.php:
    function drawcomplect() {

    for ($i=0;$i<count($new_arr);$i++) {

        if ($i%2==0) {
            echo "
".$j++."
";
            echo "
".$new_arr[$i]."
";
        } else {
            echo "
".$new_arr[$i]."
";
               }
        }
       }

And mPdf file for output:
$html =''.drawcomplect().''

If run this function in php file, it's work. But mPdf not work, print "Page error". How I can add data to pdf?

A:    function drawcomplect() {
      $str = '';

      for ($i=0;$i<count($new_arr);$i++) {

        if ($i%2==0) {
            $str .="
".$j++."

".$new_arr[$i]."
";
        } else {
            $str .="
".$new_arr[$i]."
";
        }
      }
      return $str;
   }

ANd Mpdf:
$html =''.drawcomplect().''


text:
Q: how to skip a module if the module it depends on has no outputs? I have a module depending on another, example terragrunt.hcl in the depending module:
dependency "workspace" {
   config_path = "../workspace"
}

inputs = {
  databricks_resource_id = dependency.workspace.outputs.resource_id
}

During apply there will always be outputs, but during destroy there may not be because I am using --terragrunt-ignore-dependency-errors and may run destroy multiple times.
If the dependency doesn't have any outputs I want the depending module to be skipped with run-all.
Is this possible?


text:
Q: Download Azure Blob using SAS key in .net I am trying to access Azure Blob with SAS token to download the data from the blob, this is what I have tried.
I am very new to this so have no idea how it should work
this is what I have tried so far.
            const string sasToken = "SAS TOKEN";

            var blobUri = new System.Uri("URI");

            var blobUriBuilder = new System.UriBuilder(blobUri)
            {
                Query = sasToken
            };

            var authorizedBlobUri = blobUriBuilder.Uri;
            var blobClient = new BlobClient(authorizedBlobUri);

            Console.WriteLine("blob read successfully: {0} ", blobClient.BlobContainerName);

            // Create a local file in the ./data/ directory for uploading and downloading
            string localPath = "./data/";
            string fileName = "quickstart" + Guid.NewGuid().ToString() + ".txt";
            string localFilePath = Path.Combine(localPath, fileName);

            string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");

            var response = await blobClient.DownloadToAsync(downloadFilePath);
            Console.WriteLine("blob read successfully: {0} {1}", response.Content, response.Status);

Error is

could you suggest if this is the right way to get data from the Blob and how to resolve this error I am getting please

A: Would suggest you to please use this below code share in GITHUB from one of their community members.
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;

namespace AzureBlobStorage
{
    internal static class Program
    {
        private static void Main()
        {
            const string accountName = "account-name";
            const string blobContainerName = "blob-container-name";
            const string downloadLocation = @"C:\data";
            const string sasToken =
                @"<SAS token (just the token, not the URI)>";

            // Create a credential object from the SAS token then use this and the account name to create a cloud storage connection
            var accountSAS = new StorageCredentials(sasToken);
            var storageAccount = new CloudStorageAccount(accountSAS, accountName, null, true);

            // Get the Blob storage container
            var blobClient = storageAccount.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference(blobContainerName);

            // Fail if the container does not exist
            if (!container.Exists())
            {
                Console.Error.WriteLine($"Can't find container '{blobContainerName}'");
                return;
            }

            // Get the list of blobs in the container, just for demo purposes this is ordered by blob name and taking only
            // the first 10 items
            var blobs = container
                .ListBlobs(blobListingDetails: BlobListingDetails.Metadata)
                .OfType<CloudBlob>()
                .OrderBy(blobItem => blobItem.Name)
                .Take(10)
                .ToList();

            // Set the request options to ensure we're performing MD5 validation
            var downloadOptions = new BlobRequestOptions
            {
                DisableContentMD5Validation = false,
                UseTransactionalMD5 = true
            };

            // Download the files
            // The parameters are named for reference only and can safely be removed
            Task.WaitAll(
                blobs.Select(
                    blobItem => blobItem.DownloadToFileAsync(
                        path: Path.Combine(downloadLocation, blobItem.Name),
                        mode: FileMode.Create,
                        accessCondition: null,
                        options: downloadOptions,
                        operationContext: null)).ToArray());
        }
    }
}

Reference: https://gist.github.com/dazfuller/9b5ea145525879fb5114bd78b53e9ee5#file-azureblobdownload-cs


text:
Q: Knuth-Morris-Pratt algorithm confusion I'm trying to implement KMP algorithm. My algorithm works correctly with the following example

*

*Text: 121121

*Pattern: 121

*Result: 1,4

But when Text is 12121 and pattern is the same as above, result just: 1. I don't know if this is the problem of the algorithm or of my implementation?
Other example:

*

*Text: 1111111111

*Pattern: 111

*Result: 1,4,7

My code is:
public class KMP {
    public static void main(String[] args) throws IOException{
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String text = reader.readLine();
        String pattern = reader.readLine();
        search(text,pattern);
    }
    private static void search(String text,String pattern)
    {
        int[] Pi = Pi(pattern);
        for (int i = 0,q=0; i <text.length()&&q<pattern.length() ; i++,q++) {
            while (q>=0 && pattern.charAt(q)!=text.charAt(i))
            {
                q=Pi[q];
            }
            if(q==pattern.length()-1) {
                System.out.println(i-pattern.length()+2);
                q=Pi[q];
            }

        }
    }

    private static int[] Pi(String p) {
        int[] Pi = new int[p.length()];
        Pi[0]=-1;
        int i=0;
        int j=-1;
        while (i<p.length()-1) {
            while (j>=0 && p.charAt(j)!=p.charAt(i))
            {
                j=Pi[j];
            }
            i++;
            j++;
            if(p.charAt(j)==p.charAt(i)) Pi[i]=Pi[j];
            else Pi[i]=j;
        }
        return Pi;
    }

}

A: Hope help you.
public int strStr(String source, String target) {

    if (source == null || target == null){
        return -1;
    }
    if (source.isEmpty() && !target.isEmpty()){
        return -1;
    }
    if (source.isEmpty() && target.isEmpty()){
        return 0;
    }
    if (target.isEmpty()){
        return 0;
    }

    int index = 0;
    int compare_index = 0;
    int compare_start_index = 0;
    int compare_same_length = 0;
    List<Integer> answers = new ArrayList<Integer>();

    while (true){
        if (compare_same_length ==0){
            compare_start_index = compare_index;
        }

        if (source.charAt(compare_index) == target.charAt(index)){
            compare_same_length++;
            index++;
        } else {
            if (compare_same_length >0){
                compare_index--;
            }
            compare_same_length = 0;
            index = 0;
        }

        compare_index++;
        if (compare_same_length == target.length()){
            answers.add(compare_start_index+1);
            compare_same_length=0;
            index=0;
        }

        if (compare_index == source.length()){
            //here are answers
            for (int i = 0; i < answers.size(); i++) {
                int value = answers.get(i);
            }
            return 1;
        }
    }
}


text:
Q: Decoding error,image format unsupported Azure I am running a flask server at the backend. I want to read the image from mobile app and send it to the server to detect faces.
This is the java code(client side) for sending image as bytes -
public class client {
    public static void main(String [] args) throws Exception{

        String url = "http://127.0.0.1:8080/facial";
// 2. create obj for the URL class
        URL obj = new URL(url);
        // 3. open connection on the url
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type","image/jpeg");
        con.setDoInput(true);
        con.setDoOutput(true);

        try {

            System.out.println("Reading image from disk. ");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            baos.flush();
            File file = new File("jpeg.jpg");
            BufferedImage image1 = ImageIO.read(file);

            ImageIO.write(image1, "jpg", baos);
            baos.flush();
            System.out.println(baos.size());
            byte[] bytes = baos.toByteArray();
            baos.close();

            System.out.println("Sending image to server. ");

            OutputStream out = con.getOutputStream();
            DataOutputStream image = new DataOutputStream(out);

            image.writeInt(bytes.length);
            image.write(bytes, 0, bytes.length);

            System.out.println("Image sent to server. ");

            image.close();
            // close the output stream
            out.close();

        }catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
        }

        // define object for the reply from the server
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        //Get response from server
        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);
        // read in the response from the server
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
            System.out.println(inputLine);
        }
        // close the input stream
        in.close();

    }

}

This is my server code -
def get_facial(data):
    face_api_url = 'https://southeastasia.api.cognitive.microsoft.com/face/v1.0/detect'

    # Set image_url to the URL of an image that you want to analyze.
    headers = {'Ocp-Apim-Subscription-Key': subscription_key,
    "Content-Type":"application/octet-stream"
    }
    params = {
        'returnFaceId': 'true',
        'returnFaceLandmarks': 'false',
        'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,' +
        'emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
    }
    response = requests.post(face_api_url, params=params, headers=headers, data=data)
    faces = response.json()
    res={}
    import pdb; pdb.set_trace()

    res["status"] = '200'
    res["num"] = str(len(faces))
    return res

@app.route('/facial',methods=['POST'])
def facial():
    import pdb; pdb.set_trace()
    data=bytes(request.get_data())
    res={}
    try:
        res = get_facial(data)
    except:
        res['status'] = '404'
    print(res)
    return json.dumps(res)

After examining - I sent the same image from another python file and checked the size of the data. It was 102564 bytes and it works but
the same image read and sent from java code is 106208 bytes. I don't know where exactly the mistake is.
Any help is appreciated !!:-)

A: I found a quick fix to this problem -
Path path = Paths.get("jpeg.jpg");
byte[] fileContents =  Files.readAllBytes(path);
image.write(fileContents, 0, fileContents.length);

I don't exactly know why reading from imageio fails. My guess is that its also reading the file headers of the jpg file.


text:
Q: php rabbitmq Per-Message TTL Issue I'm using different "Per Message TTL" in RabbitMQ queue, and I expect that messages with different TTL should be processed  by consumer in due time.
To provide this behaviour, I  use RabbitMQ queue with huge "x-message-ttl",  I add messages to this queue with own value of "Per Message TTL"(see code below). For example add to queue messages with TTL 30, 20 and 10 seconds.
The problem  in behaviour, how RabbitMQ process the messages with different "Per MessageTTL" in queue, the messages with largest TTL stop the messages with less TTL. So consumer process all mesages together, when largest TTL expire.
Publish message code:
$channel = new AMQPChannel($this->connection);
$exchange = new AMQPExchange($channel);
$exchange->setName($exchangeName);
$exchange->setType(AMQP_EX_TYPE_DIRECT);
$ttl = $ttl*1000;
$params = array('expiration'=>$ttl);
$message = $exchange->publish($msg, $this->queueNotDelayedName, null, $params);

A: I'm going to be up-front that I don't fully understand your question, because the wording is confusing to me.
Are you referring to this (from the documentation)?

When setting per-message TTL however, expired messages can queue up
  behind non-expired ones until the latter are consumed or expired.
  Hence resources used by such expired messages will not be freed, and
  they will be counted in queue statistics (e.g. the number of messages
  in the queue).

I have not had issues using the per-message TTL feature. The messages expire before they get to the consumer. What the documentation says is that they are not expired in random order out of the queue, but that they are only expired when the message is to be "read" from the queue. Is this the cause of your issue?

A: As correctly noted rmayer06, described functionality  works by design.
From http://www.rabbitmq.com/ttl.html#per-message-ttl :
When setting per-message TTL however, expired messages can queue up
behind non-expired ones until the latter are consumed or expired.

I solved my problem programmatically.
I used the solution which well described here:
http://yuserinterface.com/dev/2013/01/08/how-to-schedule-delay-messages-with-rabbitmq-using-a-dead-letter-exchange/

A: Unfortunately (imho) theMayer is correct. The message will only expire when it hits the head of the queue. We had a similar issue at our company. In the end we had to  implement separate queues as we only had 2 different timeouts so 2 queues. There is a plugin that we are in the middle of investigating that may allow for the operation you seek https://github.com/rabbitmq/rabbitmq-delayed-message-exchange/


text:
Q: iOS Scale UIWindow ,but the statusBar can not scale? As you can see,The first pic is what effect i want.but the i just can make effect like pic 2.the statusBar can not scale with UIWindow.
what can i do? who can give me some tips!

*

*What i want:

*What i made:

A: In iOS, UIStatusBar is not a part of any UIWindow, so you scale an UIWindow take no effect on UIStatusBar.
You can use snapshotViewAfterScreenUpdates: API to take a screenshot image, and show the image in UIImageView, than you can scale the UIImageView rather than the UIWindow.


text:
Q: Quarkus Kafka in cli mode I would like to create a Quarkus app in CLI mode to fetch data from kafka and store it in batch in the DB (as a Poor man's Spark).
Is it possible to somehow inject a Kafka consumer and manually decide (according to offset lag) to fetch the messages ?
Thnx

A: "bare-kafka" usage docs in CR:
https://github.com/quarkusio/quarkus-quickstarts/pull/746/


text:
Q: Solving $x^2+y^2=9$, $\arctan\frac{y+2}{x+2} + \arctan\frac{y-2}{x+4} =2\arctan\frac{y}{x}$ without graphing? The system of equations:

$$\begin{align}
x^2 + y^2 &= 9 \\[6pt]
\operatorname{arctan}\frac{y+2}{x+2} + \operatorname{arctan}\frac{y-2}{x+4} &=2\,\operatorname{arctan} \frac{y}{x}
\end{align}$$

I tried to interpret the second equation by setting $x$ and $y$ as the legs of a right triangle, but I'm still unable to solve this system of of equations geometrically. Any tips?

A: Essentially, the equations say that the origin is at distance $3$ from $(x,y)$ and on the angular bisector of the triangle with vertices $(x,y)$, $(x+2,y+2)$, $(x+4,y-2)$.

A: Hint:
$$\arctan\dfrac{y+2}{x+2}-\arctan\dfrac yx=\arctan\dfrac  yx-\arctan\dfrac{y-2}{x+4}$$
$$\iff\dfrac{2x-2y}{x^2+y^2+2x+2y}=\dfrac{2x+4y}{x^2+y^2-2x+4y}$$
As $x^2+y^2=9$   $$\iff\dfrac{2x-2y}{9+2x+2y}=\dfrac{2x+4y}{9-2x+4y}$$
$$\iff8x^2+16y^2+54y=0\  \ \ \ (1)$$
As $x^2+y^2=9,$ WLOG $x=3\cos t,y=3\sin t$
Put these values in $(1)$ and divide both sides by $\cos^2 t$


text:
Q: How to use Microsoft Bot Framework web chat in Angular5 application I need a way to embed web chat in my angular 5 application. I have tried the non react website way described here: https://github.com/Microsoft/BotFramework-WebChat  and it works.
Is there a way to use the components only rather than loading the entire js file to get the chat window in my Angualar 5 app?

A: If you install the BotFramework-WebChat version greater than 0.10.7, you can directly use the BotFramework-WebChat in ng application.

*

*Install the webchat sdk: npm install botframework-webchat

*fill the style files in .angular-cli.json file:
"styles": [
  "../node_modules/botframework-webchat/botchat.css",
  "../node_modules/botframework-webchat/botchat-fullwindow.css"
],

*Try the sample in component as discussed at https://github.com/Microsoft/BotFramework-WebChat/issues/478:
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {App} from "botframework-webchat";
@Component({
  selector: 'app-root',
  template: `<div id="bot-chat-container" #botWindow></div>`,
})
export class AppComponent implements OnInit {

  @ViewChild("botWindow") botWindowElement: ElementRef;

  ngOnInit(): void {
    App({
      directLine: {secret: 'secret goes here'},
      user: {id: 'user'},
      bot: {id: 'bot'},
    }, this.botWindowElement.nativeElement)
  }
}


text:
Q: Apply a list of attributes to xml element dynamically Say I have a list of attribute tuples:
val list = List(("name", "myname"), ("id", "1"))

How would I then dynamically generate and XML element thus:
<elem name='myname' id='1'/>

A: The standard interface to work with XML in Scala is not very convenient. Attributes are stored in a linked list xml.MetaData (which is not actually a List or any kind of collection whatsoever). So you would have to fold your list to produce this MetaData. After that the easiest way to make an element with it in my opinion is to use % operator. The other way to construct an element is to pass this MetaData to xml.Elem constructor.
val list = List(("name", "myname"), ("id", "1"))
val attributeList = list.foldLeft(xml.Null: xml.MetaData) {
  case (metadata, (key, value)) => xml.Attribute(None, key, xml.Text(value), metadata)
}
val elem = <elem/> % attributeList


text:
Q: Bypassing OPTIONS in REST Is there a way to post from one domain to another without OPTIONS?  I have a POST from domain A to domain B which becomes OPTIONS when I try to run it.  Is there a way around that?  For example, can I write the service on domain B to accept a POST without asking for OPTIONS?

A: I assume you are talking about doing the POST in a browser...
In that case, if using AJAX, and it's cross-domain, you will need the OPTION request, unless you disable web security.
One option would be to create a hidden iframe, add a form with the right action and method=POST and then submit the form using form.submit();
Why not use OPTION though?
Another option would be to reverse proxy the request through your domain. Send the POST to your own web server, which forwards the request to the other domain, and returns its response.


text:
Q: T-SQL : calculate total salary of employees I want to calculate the salary for each employee from in period of time for example from 01-01-2021 to 05/31/2021.
I have these 3 tables:
Teacher

Id
DateOfBirth
Email
PhoneNumber

1
0001-01-01
a@example.com
23423424

2
1984-09-30
b@example.com
9832131

TeacherSalary

Id
Salary
TeacherId
FromDate
ToDate
IsPartTime

1
500000
1
2021-01-01
2021-01-31
1

2
10000000
1
2021-02-01
2021-03-15
0

3
15000000
1
2021-03-16
NULL (mean now)
0

TimeEntry

Id
TeacherId
TeacherSalaryPartTime
Date

1
1
500000
2021-01-05

2
1
450000
2021-01-07

I want to calculate total salary of these employee
For example in this case, this employee have from 01/01/2021 to 01/31/2021 is part-time then sum from time Entry (500000+450000)
and 02/01/2021 to 03/15/2021 is (number days in feb)(10000000/number days in feb) + 15 days of March with salary calculated is 10000000/(day of month March)(day from 03/01/2021 to 03/15/2021)
and 03/16/2021 to 05/31/2021 is calculated with this: (number days from 03/16/2021 to end of month)(15000000/number of days in March) + (number days from 04/01/2021 to 05/31/2021)(15000000/number of days)
Could you please help me calculate this in T-SQL
Thanks

A: There you go
DECLARE @StartDate  DATE = '2021-01-01',
        @EndDate    DATE = '2021-05-31'

SELECT  Teacher.Id                      AS Id,
        Teacher.FullName                AS FullName,
        (
            SELECT  SUM(TimeEntry.TeacherSalaryPartTime)    AS  SalarySum
            FROM    TimeEntry
            WHERE   TimeEntry.EntryDate         BETWEEN @StartDate AND @EndDate
            AND     TimeEntry.TeacherId         =       Teacher.Id
        )
        +
        (
            SELECT  SUM(
                        TeacherSalary.Salary *
                        (DATEDIFF(
                            MONTH,
                            GREATEST(@StartDate, TeacherSalary.FromDate),
                            LEAST(@EndDate, ISNULL(TeacherSalary.ToDate, @EndDate))
                        ) + 1)
                    )                                   AS  SalarySum
            FROM    TeacherSalary
            WHERE   TeacherSalary.IsPartTime    =       0
            AND     TeacherSalary.FromDate      >=      @StartDate
            AND     TeacherSalary.ToDate        <=      @EndDate
            AND     TeacherSalary.TeacherId     =       Teacher.Id
        )

FROM    Teacher

A: Try the following. You might want to check the "now" (where did your 05/31/2021 come from?) and the datediff formula to tune if you have for example half a month, what to do.
select
     t.Id
    ,sum(subquery1.[sum]) as [sum]
from
    Teacher t
    left join TeacherSalary s on s.TeacherId=t.Id
    outer apply
    (
        select
            case
                when s.IsPartTime=0 then s.Salary * (1+datediff(month,s.FromDate,isnull(s.ToDate,'20210531')))
                when s.IsPartTime=1 then
                    (
                        select sum(e.TeacherSalaryPartTime)
                        from
                            [Time Entry] e
                        where
                            e.TeacherId=t.Id
                    )
            end
                as [sum]
    ) as subquery1
    group by t.Id


text:
Q: BB 10 App will terminate ,if It is offline In my App, when ever BB 10 Device is in Offline... I need to show a dialog box with "Ok" Button.pressing "Ok" button Should  Terminate the APP !!!
 SystemDialog *dialog;
dialog = new SystemDialog(tr("OK"), 0);
dialog->setTitle(tr("Alert"));
dialog->setBody(message);
dialog->setDismissAutomatically(true);.
connect(dialog, SIGNAL(finished(bb::system::SystemUiResult::Type)), dialog,
        SLOT(deleteLater()));
dialog->show();

Here deleteLater() is SystemSlot which is only terminating the Alert Dialog box but not the App!!! How to Do this in BB 10 Cascades through C++ Code? IS it possible to Override deleteLater() SystemSlot like this,
// I replaced deleteLater() with SLOT(deleteLaters()) in above code and Added this Slot
 void deleteLaters(){
  bb::Application::exit(0);
  }

Then Its is Saying, No such slot deleteLaters() Found in bb::System !!!
Please Help,
Thankks!!!

A: I guess you are just trying to connect the SystemDialog finished signal to a the same object's deleteLaters slot (which doesn't exist).
Try something like the next code, where myObject might just be this if you declare your slot in your class.
int connectResult = connect(dialog,
                            SIGNAL(finished(bb::system::SystemUiResult::Type)),
                            myObject,
                            SLOT(deleteLaters()));
Q_ASSERT(connectResult);
Q_RESULT(connectResult);

For more information on how to properly declare your new slot in your class, see the signals and slots documentation.
Note: If you really need to close the application (which is not recommended), I believe you should use Application::instance->requestExit() to do it properly. If you don't need to do anything else before closing the application, you might directly connect the signal to the requestExit() slot:
int connectResult = connect(dialog,
                            SIGNAL(finished(bb::system::SystemUiResult::Type)),
                            Application::instance,
                            SLOT(requestExit()));
Q_ASSERT(connectResult);
Q_RESULT(connectResult);


text:
Q: Combinatorical problem of food store
There are four shops selling three types of food each.
There are n people who each buy exactly one food at each shop. For each three people have at least one shop where all three types of the food are bought. Find the maximum value of n that possible

explanation : all the shops selling the same 3 types of food.
Let A,B,C and D are the food stores and x,y and z are the food. And let p is one of x,y and z. I'm not sure to my solution but i got this construction of 7 people is valid.
                 A       B       C       D
                 x       y       z       p
                 x       z       y       p
                 y       x       z       p
                 y       z       x       p
                 z       x       y       p
                 z       y       x       p

with those 6 people we have each three people have at least one shop where all three types of the food are bought. Then I can make some random permutation of food that bought by the seventh people, for example: the seventh people buy type x of food in all shops. Then i can make another valid construction.
                 A       B       C       D
                 x       y       z       y
                 x       z       y       z
                 y       x       z       z
                 y       z       x       y
                 z       x       y       y
                 z       y       x       z
                 x       x       x       x

but i can not make any other permutation of type of food for the 8th people. and that makes me think that 7 is the maximum value of n.
But if someone has any other idea please share because i need combinatorical solution.


text:
Q: Form and Save new record to association model in Rails I have 3 model (3 tables)
Campaign , rel_campaign_site and Site (Campaign,site  have many rel_camp_site)
rel_camp_site table have camp_id and site_id
I want to make a form to create new Campaign but I dont know how to put the site_id in the form (in check box)
and when campaign created , rel_camp_site auto create new record with camp_id is the id of the created campaign,site_id is the chosen checked box in form
please help me.Im newbie in rails :(


text:
Q: Ways to place 3 chess pieces so that none are in the same column or row How many ways can we place $3$ chess pieces so that none are in the same column or row? Chess pieces are distinguishable, so we can imagine them as one pawn, one knight, one rook.
A chess board is a $8\times 8$ grid.
So the correct answer is $8^27^26^2$ because we have $8$ choices for the column and $8$ for the row to place the first piece, and $7$ choices for the second piece, and so on.
However, when I attempted the question, I thought that we could do $(8 C 3)\cdot (8 C 3)$, which first counts the number of  ways to choose $3$ different columns and then $3$ different rows. However that answer seems to undercount. So why is it wrong and why is it undercounting?

A: EDIT:
Adding your method and completing it which works too -

You first choose $3$ rows and $3$ columns so number of ways = $(^8C_3)^2$.
This gives you $9$ squares. Please see one of the cases in the picture. Now you can place the first piece on any of the $9$ squares. That leaves $4$ choices for the next piece. The last one has just one places to go to.
So total number of ways = $(^8C_3)^2 \times 9 \times 4 = 112896$.
May be an easier way to look at it is
Number of ways $ = 8 \times 8 + 7 \times 7 + 6 \times 6$. Explanation -
There are $64$ squares on a chessboard. The first one can be placed anywhere out of $64$ squares - (say, Col1 and Row1). Once that is done, the second one has to avoid squares in col1 and row1. That leaves $64-15 = 49 = 7 \times 7$ squares for the second.
Now think of the third one - $2$ squares to avoid will be common between first and second. So add another $13$ squares to avoid. That leaves $36 = 6 \times 6$ squares.


text:
Q: Unable to open front end and admin When i try to open my site it is not opening, same as my back end as i added the error below.
Adminpanel issue in site.

A: It looks like your magento is unable to read the xml configuration files. Try giving appropriate read permission to all your xml files and try.
cd your/magento_root/
find . -type f -name '*.xml' -exec chmod 644 {} \;

A: The problem is the magento can't read your xml files. Check the file permission, remove the cache.
Make sure your file permissions are set to

Directories : 755 ::: Files : 644

A: Reason 1
Try clearing cache, and check file permissions are correctly set,
Directories : 755
Files : 644
Else another alternative is Reinstall Magento and do following steps:
It may solve the issue, but suggested to have round of research before doing and surely back up database:
Before to import database : - Add query
1) SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

OR
at beginning of sql import script
After import / installation : - Execute following query
2) UPDATE `core_store` SET `store_id` = 0 WHERE `code` like 'admin';
   UPDATE `core_website` SET `website_id` = 0 WHERE `code` like 'admin';
   UPDATE `customer_group` SET `customer_group_id` = 0 WHERE `customer_group_code` like 'NOT LOGGED IN';

Reason 2
The problem is the magento can't read your xml files. So check file permission again for xml files and check your xml files under app/etc folder and every custom modules under app/code/local/ may be some xml files are corrupted (miss formed).
clear cache
Note:- not given proper permission also occurs this error.

A: open your terminal or connect your website via ssh access and fire below command one by one for file/directory permission
chmod -R 644 ./*
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
chmod 550 ./mage

A: The problem is the Magento can't read your XML files. So check file permission again for xml files and check your xml files under app/etc folder and every custom modules under app/code/local/ may be some XML files are corrupted (miss formed).
just run an rsync -p on with your production site
Can Use cleanup Script  for your localhost
cleanup script


text:
Q: Release Management 2015 Deploy zip file to a Linux server and run a SH file on the Linux server I'm investigating if I can deploy a zip file and then run the SH file on the Linux server using Microsoft Release Manager 2015.
I've followed the link from http://blogs.msdn.com/cfs-filesystemfile.ashx/__key/communityserver-components-postattachments/00-10-52-77-91/DSC-deployment-in-RM.pdf but I don't want to run an agent on the Linux box.
The following article works but its outside RM. http://blogs.technet.com/b/privatecloud/archive/2014/05/19/powershell-dsc-for-linux-step-by-step.aspx#pi169501=2
Any help would be appreciated.

A: The only out-of-the-box supported mechanism is to use Chef.
DSC for Linux didn't work in RM 2013. I don't know if RM 2015 changed the story or not, but I would expect that it did not. Note: DSC for Windows worked fine.
The only option I've ever seen that works for Linux is to use an agent-based deployment. The architecture is like this:

*

*Choose a Windows machine to act as a "springboard" that will actually execute the deployment

*Create a custom tool for PuTTY (specifically, PLink/PSFTP)

*Use the custom tool to invoke the appropriate SSH tools to copy the deployment artifacts (binaries/scripts) to the Linux machine and execute the scripts

The new RM Service in VSTS (and in on-premise TFS 2015 later this year) will make for a much smoother experience, as it has better support for non-Windows environments.


text:
Q: How to make heatmap clickable? I have attached my code below which I have been using to try and generate a clickable heatmap. The actual heatmap is generated but I cannot produce a click event.
Here is my code:
const centerLocation = new google.maps.LatLng(
  Number(28.555040),
  Number(77.241920)
);
const mapProp = {
  center: centerLocation,
  zoom: 12,
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  clickableIcons: true
};
this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
const location = new google.maps.LatLng(
  Number(28.555040),
  Number(77.241920)
);

for (let i = 0; i < userData.length; i++) {
  this.marker = new google.maps.Marker({
    position: new google.maps.LatLng(+userData[i][1], +userData[i][2]),
    map: this.map,
    icon: this.userimage,
    title: userData[i][0]
  });
  // tslint:disable-next-line:no-shadowed-variable
  google.maps.event.addListener(this.marker, 'click', (function (marker, i) {
    return function () {
      infowindow.setContent('' + userData[i][0] + '');
      infowindow.open(this.map, this);
    };
  })(this.marker, i));

}
const infowindow = new google.maps.InfoWindow();
for (let i = 0; i < eventData.length; i++) {
  this.marker = new google.maps.Marker({
    position: new google.maps.LatLng(+eventData[i][1], +eventData[i][2]),
    map: this.map,
    icon: this.image,
    title: eventData[i][0]
  });

  // tslint:disable-next-line:no-shadowed-variable
  google.maps.event.addListener(this.marker, 'click', (function (marker, i) {
    return function () {
      infowindow.setContent('' + eventData[i][0] + '');
      infowindow.open(this.map, this);
    };
  })(this.marker, i));
}

// console.warn(location);

this.marker.setPosition(location);
this.heatmap = new google.maps.visualization.HeatmapLayer({
  data: heatmapData,
  dissipating: true,
  radius: 50
});

this.heatmap.setMap(this.map);

// For heatmap color
const gradient = [
  'rgba(0, 255, 255, 0)',
  'rgba(0, 255, 255, 1)',
  'rgba(0, 191, 255, 1)',
  'rgba(0, 127, 255, 1)',
  'rgba(0, 63, 255, 1)',
  'rgba(0, 0, 255, 1)',
  'rgba(0, 0, 223, 1)',
  'rgba(0, 0, 191, 1)',
  'rgba(0, 0, 159, 1)',
  'rgba(0, 0, 127, 1)',
  'rgba(63, 0, 91, 1)',
  'rgba(127, 0, 63, 1)',
  'rgba(191, 0, 31, 1)',
  'rgba(255, 0, 0, 1)'
];
this.heatmap.set('gradient', gradient);
// For heatmap color

this.heatmap.set('opacity', 0.6);

A: If by 'clickable' you mean interactive you may want to look at complexheatmaps which offer that specific utility. The supporting documentation can be found here. An example of what level of interactivity is possible can be found on this page.
Use one of the following to download the package...
Most Recent (you must use force = TRUE):
library(devtools)
install_github("jokergoo/ComplexHeatmap", force = TRUE)
library(ComplexHeatmap)

Stable:
if (!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")
BiocManager::install("ComplexHeatmap", version = "3.8")

Alternatively, you may want to look at using iheatmapr, though I know very little about it. As it is designed with interactivity as a forethough it may be of use to you. Here is how it was described in the Journal of Open Source Software.

There are great tools in R for creating simple interactive heatmaps
  (Galili 2016, Cheng and Galili (2016)) or creating static complex
  heatmaps (Gu, Eils, and Schlesner 2016). However, there are no tools
  facilitating the creation of complex, interactive heatmaps.
  Theiheatmapr package fills this gap, enabling the creation of highly
  customizable, interactive, complex heatmaps using the plot library
  (Sievert et al. 2016). The resulting interactive visualizations can
  easily be incorporated into reproducible R Markdown reports for sharing
  with collaborators


text:
Q: Error on custom javascript button Below code should update the Leadership_Notification_check__c when the Suite, RedLightReview are not empty, TOV >= 5000000000 and check field is 0.
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}

var Suite= document.getElementById('00Nq00000017vbe_ileinner').innerHTML;
var TOV= document.getElementById('00Nq000000181Wp_ileinner').innerHTML;
var RedLightReview= document.getElementById('00Nq00000017qTB_ileinner').innerHTML;
var ce = new sforce.SObject("Contract_Extract__C");
ce.id = "{!Contract_Extract__c.Id}";
var check = {!Contract_Extract__c.Leadership_Notification_check__c}
if ((TOV >= 5000000000 ||  (Suite != ' ' || Suite != ' ' ) || (RedLightReview!= ' ' || RedLightReview != ' ') ) && check === 0) {
       ce.Leadership_Notification_check__c = 1;
       result = sforce.connection.update([ce]);

}

Thanks in advance...


text:
Q: Make set of pointers to use comparison criteria of underlying injects, C++ I want std::set if shared_ptr's to compare the pointee's, not pointers.
I have this example:
std::shared_ptr<std::string> s(new std::string("abc"));
std::shared_ptr<std::string> p(new std::string("abc"));
std::set<std::shared_ptr<std::string>> S;
S.insert(s);
S.insert(p);
std::cout << S.size();

As you can see I am putting the same element in the set but this outputs 2.
How can I make set's insert to use the comparison criteria of underlying strings?  And what if its not a string but more complex object?

A: The second template parameter of std::set is the type of the comparator to be used (default is std::less<Key>):
#include <iostream>
#include <memory>
#include <set>
#include <string>

struct deref_less {
  bool operator()(const auto& a, const auto& b) const { return (*a) < (*b); }
  using is_transparent = void;
};

int main() {
  std::shared_ptr<std::string> s(new std::string("abc"));
  std::shared_ptr<std::string> p(new std::string("abc"));
  std::set<std::shared_ptr<std::string>, deref_less> S;
  S.insert(s);
  S.insert(p);
  std::cout << S.size();
}

Output:
1

auto parameters for convenience with C++20, before the comparator is a bit more verbose. using is_transparent = void; to enable eg the set::find overload that accepts a std::unique_ptr<std::string> (see godbolt example).


text:
Q: How to traverse a table in Oracle SQL I have a table in Oracle (12c) which I need to retrieve data.
The table is called ACCOUNT_ANALYSIS_FY16.  This table holds a 3 level hierarchy of businesses.  The position in this hierarchy is designated by the column DUNS_LEVEL, whose value is DUNS (meaning the lowest level of a business), IMMEDIATE (meaning a level 2, aka Parent of DUNS level) or ULTIMATE, (meaning level 3, or Parent of IMMEDIATE).
Applicable columns are:
NN_NAME - Account Name
DUNS_LEVEL
DUNS
ULTIMATE_PARENT_DUNS
IMMEDIATE_PARENT_DUNS

The requirement... for a given account name (and there may be multiple occurrences for the same account name due to different locations), I need to see everything about that account (aka SELECT *), AS WELL AS everything about the Immediate Parent and the Ultimate Parent of the given account.
I have written this in SQL, but it involves 5 SELECT statements.  I know there has to be a more elegant and simple way to do this.  Note that the end result is to place this in an anonymous PL/SQL block, so it is acceptable to write a PL/SQL block if that is a better solution.
Here is the straight SQL that I have which works...
Select *from ACCOUNT_ANALYSIS_FY16 where NN_NAME = 'XYZ GROUP'
union
Select * from ACCOUNT_ANALYSIS_FY16 where DUNS in (Select IMMEDIATE_PARENT_DUNS from ACCOUNT_ANALYSIS_FY16 where NN_NAME = 'XYZ GROUP')
union
Select * from ACCOUNT_ANALYSIS_FY16 where DUNS in (Select ULTIMATE_PARENT_DUNS from ACCOUNT_ANALYSIS_FY16 where NN_NAME = 'XYZ GROUP')

Thanks

A: Try:
SELECT *
FROM ACCOUNT_ANALYSIS_FY16 t
WHERE NN_NAME = 'XYZ GROUP'
  OR EXISTS (
     SELECT NULL
     from ACCOUNT_ANALYSIS_FY16 t1
     WHERE t.DUNS IN ( t1.ULTIMATE_PARENT_DUNS, t1.IMMEDIATE_PARENT_DUNS )
       AND t1.NN_NAME = 'XYZ GROUP'
  )


text:
Q: Для чего нужны escape последовательности в адресах URL? Часто встречаю ссылки записанные в escape последовательности с символом процента в качестве отделителя для закодированного символа. Для чего применяется эта технология?

A: Они применяются для того чтобы передавать специальные символы. например
Нужно передать параметр значение которого R&D, если просто дописать его в url
url?param=R&D

То можно заметить, что значение параметра будет на самом деле R, так как & служит для разделения параметров.
При использования escape же получим строку
url?param=R%26D

которая отлично передается.


text:
Q: word processing in prolog How can I write a program in prolog that breaks a word into syllables using predicate: First syllable is vowel-consonant-vowel .. or Second syllable: vowel-consonant-consonant-vowel. For example; abandon = aba-ndon ..

A: This program will basically apply the rules you mention, but I don't think it will make a good tool for word processing.
vowel(a).
vowel(e).
vowel(i).
vowel(o).
vowel(u).
consonant(L):- not(vowel(L)).

syllable(W, S, RW):- atom_chars(W, [V1, C, V2|Tail]), vowel(V1), consonant(C), vowel(V2), !, atomic_list_concat([V1, C, V2], S), atomic_list_concat(Tail, RW).
syllable(W, S, RW):- atom_chars(W, [V1, C, C2, V2|Tail]), vowel(V1), consonant(C), consonant(C2),vowel(V2), !, atomic_list_concat([V1, C, C2, V2], S), atomic_list_concat(Tail, RW).
syllable(W, W, _).

break(W, B):- syllable(W, B, ''), !.
break(W, B):- syllable(W, S, RW), break(RW, B2), atomic_list_concat([S, '-', B2], B).

The program defines what a vowel is and what it is not. Also a syllable according to your rules, and how to break a word. Using the predicate ´break/2´ you can test it:
?- break(abaebbi, B).
B = 'aba-ebbi'

What makes me doubt about your rules, besides my poor English, is that testing with each word of my answer, returns the entire word always :)
?-break('syllable', B).
B = syllable

A: There's a publically available list of words split into "syllables" (not sure exactly what the criteria is) here. Each line is a word, so you could read the words in one at time, split them into syllables, and store them in some dynamic predicate. Suppose the file is called mhypth.txt, as it is at the link above:
go :-
        %% I don't know why 65533 is the code for the separator, but it is.
        string_codes(Sep, [65533]),
        setup_call_cleanup(
                           open(<Path to mhyph.txt>>, read, St),
                           read_sylls(St, Sep),
                           close(St)
                          ).

:- dynamic word_sylls/2.

read_sylls(Stream, Sep) :-
        read_line_to_string(Stream, S),
        (S == end_of_file -> true
        ;
         split_string(S, Sep, Sep, Parts),
         atomics_to_string(Parts, Word),
         asserta(word_sylls(Word, Parts)),
         read_sylls(Stream, Sep)
        ).

If you load this into your SWI Prolog interpreter, you can then do something like this:
?- go.
true.

?- word_sylls(A,B).
A = "Zurich",
B = ["Zu", "rich"] ;
A = "Zollner",
B = ["Zoll", "ner"] ;
A = "zymurgy",
B = ["zy", "mur", "gy"] ;
A = "zymosis",
B = ["zy", "mo", "sis"] ;
A = "zymoplastic",
B = ["zy", "mo", "plas", "tic"] ;
A = "zymolytic",
B = ["zy", "mo", "lyt", "ic"] ;
A = "zymologic",
B = ["zy", "mo", "log", "ic"]

?- word_sylls("abandon", Sylls).
Sylls = ["a", "ban", "don"].

?-


text:
Q: Rails, Omniauth and Facebook - "Email can't be blank" issue in production but not development Very simple question.
I have run into the "Email can't be blank" issue with my rails app/omniauth/facebook login. There are many questions on this, and among the answers is that some users give their telephone number and not their email addresses. However in my case, I have a facebook account open, with an email address that works fine with omniauth in development, but when I use it production it comes back email can't be blank. My credentials are correct.
Can anyone explain how you could have this combination of events?
edit: here is my controller code (keep in mind my devise model is "Member" and there is an associated profile model "User"
def provider
     auth = request.env["omniauth.auth"]
     member_email_check = Member.find_by_email(auth.info.email)
     if member_email_check.present? && User.find_by_member_id(member_email_check.id)
     sign_in_and_redirect member_email_check
     return false
    else
       member = Member.where(provider: auth.provider, uid: auth.uid).first_or_create do |member|
      member.provider = auth.provider
      member.uid = auth.uid
      member.email = auth.info.email
     end
   end

  if auth.provider == "facebook"
    if member.save
       unless User.find_by_member_id(member.id)
           User.create(:member_id => member.id,
                  :full_name => auth.info.first_name + " " + auth.info.last_name,
                  :first_name => auth.info.first_name,
                  :last_name => auth.info.last_name,
                  :email => auth.info.email,
                  :picture => auth.info.image)
           end
         sign_in_and_redirect member
       else
         session["devise.member_attributes"] = member.attributes
         redirect_to new_member_registration_url
       end
     end
   end

   alias_method :facebook, :provider

 end

SOLVED!
        config.omniauth :facebook, "<YOUR API KEY>", "<YOUR SECRET KEY>", scope: 'email', info_fields: 'email,name,first_name,last_name,gender'

just added the email scope and info_fields.


text:
Q: mv multiple files same dir without specifying same path or each If we have a dir/file setup like the following
var
  |-->usr
  |    |-FileA
  |    |-FileB
  |    |-FileC
  |    |-FileD

How can I move FileA and FileD without specifying the path twice like in the following cmd?
mv /var/usr/FileA /var/usr/FileB /home

A: Try doing this :
mv /var/usr/{FileA,FileB} /home

or :
( cd /var/usr/ && mv FileA FileB /home )

The later one use a subshell to return to the previous PATH.
Check brace expansion

A: You could just do:
mv /va[r]/usr/File[AB] /home

And possibly even...
mv /va[r]/usr/File[AB] /home


text:
Q: Insert array items into another array eventy nth elements Here's the problem.
I have 2 arrays
Arrays :
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
var arr2 = ['up', 'down', 'left', 'right'];

I want to insert the arr2 elemments inside the arr1 every n step for example :
/*
If the step is 2 the result would be :
*/
[1,2,'up',3,4,'down',5,6,'left',7,8,'right',9, 10, 11, 12, 13, 14, 15, 16];

I have this function as a start point but I can't figure out how to solve my problem from : How to add item in array every x items?

/**
     * Add an item to an array at a certain frequency starting at a given index
     * @param array arr - the starting array
     * @param mixed item - the item to be inserted into the array
     * @param integer starting = the index at which to begin inserting
     * @param integer frequency - The frequency at which to add the item
     */
    function addItemEvery(arr, item, starting, frequency) {
      for (var i = 0, a = []; i < arr.length; i++) {
        a.push(arr[i]);
        if ((i + 1 + starting) % frequency === 0) {
          a.push(item);
          i++;
          if(arr[i]) a.push(arr[i]);
        }
      }
      return a;
    }

    var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
    arr = addItemEvery(arr, "item", 0, 3);
    console.log(arr);

Thank you so much for helping

A: This should get you on the right track. Note that this modifies the original arrays:

let arr1 = [1,2,3,4,5,6,7,8,9];
let arr2 = ['up', 'down', 'left', 'right'];
let nth = 2;
let result = arr1.reduce((carry, current_value, index, original)=>{
    // insert current element of arr1
    carry.push(current_value);
    // insert from arr2 if on multiple of nth index and there's any left
    if((index+1) % nth === 0 && arr2.length!=0){
        carry.push(arr2.shift())
    }
    return carry;
}, []);
console.log('result', result);

A: This is relatively simple to adapt:
1) set a counter to keep track of which items from the second array have been added
2) instead of simply adding "item" to the main array at the nth step, instead add the item from arr2 at the current count. Then increase the counter.
3) Change the if condition to ensure that it doesn't try to add more items than exist in arr2
Demo:

/**
     * Add an item to an array at a certain frequency starting at a given index
     * @param array arr - the starting array
     * @param array arr2 - the list of items to be inserted into the array
     * @param integer starting = the index at which to begin inserting
     * @param integer frequency - The frequency at which to add the item
     */
    function addItemEvery(arr, arr2, starting, frequency) {
      var arr2count = 0;
      for (var i = 0, a = []; i < arr.length; i++) {
        a.push(arr[i]);
        if ((i + 1 + starting) % frequency === 0 && arr2count < arr2.length) {
          a.push(arr2[arr2count++]);
          i++;
          if(arr[i]) a.push(arr[i]);
        }
      }
      return a;
    }

    var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
    var arr2 = ['up', 'down', 'left', 'right'];
    arr = addItemEvery(arr, arr2, 0, 2);
    console.log(arr);

A: try this:

var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
var arr2 = ['up', 'down', 'left', 'right'];
var step=2;
var j=0;
 for (var i = 0,result= []; i < arr1.length; i++) {
         result.push(arr1[i]);
           if ((i + 1) % step === 0 && arr2.length>j)  {
            result.push(arr2[j]);
            j++;
          }
    }
           console.log(result);

A: I solved it that way

var arr2 = ['up', 'down', 'left', 'right'];

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];

var new_array = [];
var temp = 2;
var aggEl = () => {
    for(let i = 0, k=0; i<arr.length; i++){
        if(i== temp && k<arr2.length){
            new_array.push(arr2[k]);// I put the element of second array in new array
            k++;// I increase 'k' of one
            temp= i+3;   //new temp increase 'i' of 3 for find the new position where I will put other element of second array
        }
        else{
            new_array.push(arr[i]);
        }
    }
    alert(new_array);
}


text:
Q: How do I match a UTF-8 encoded hashtag with embedded punctuation characters? I want to extract #hashtags from a string, also those that have special characters such as #1+1.
Currently I'm using:
@hashtags ||= string.scan(/#\w+/)

But it doesn't work with those special characters. Also, I want it to be UTF-8 compatible.
How do I do this?
EDIT:
If the last character is a special character it should be removed, such as #hashtag, #hashtag. #hashtag! #hashtag? etc...
Also, the hash sign at the beginning should be removed.

A: The Solution
You probably want something like:
'#hash+tag'.encode('UTF-8').scan /\b(?<=#)[^#[:punct:]]+\b/
=> ["hash+tag"]

Note that the zero-width assertion at the beginning is required to avoid capturing the pound sign as part of the match.
References

*

*String#encode

*Ruby's POSIX Character Classes

A: How about this:
@hashtags ||=string.match(/(#[[:alpha:]]+)|#[\d\+-]+\d+/).to_s[1..-1]

Takes cares of #alphabets or #2323+2323 #2323-2323 #2323+65656-67676
Also removes # at beginning
Or if you want it in array form:
 @hashtags ||=string.scan(/#[[:alpha:]]+|#[\d\+-]+\d+/).collect{|x| x[1..-1]}

Wow, this took so long but I still don't understand why scan(/#[[:alpha:]]+|#[\d\+-]+\d+/) works but not scan(/(#[[:alpha:]]+)|#[\d\+-]+\d+/) in my computer. The difference being the () on the 2nd scan statement. This has no effect as it should be when I use with match method.

A: This should work:
@hashtags = str.scan(/#([[:graph:]]*[[:alnum:]])/).flatten

Or if you don't want your hashtag to start with a special character:
@hashtags = str.scan(/#((?:[[:alnum:]][[:graph:]]*)?[[:alnum:]])/).flatten


text:
Q: The state information is invalid for this page and might be corrupted in internet explorer I have used jquery for mbscrollable it working fine but when i run application in Internet Explorer it gives error on button which redirects to next page.
Error is:
The state information is invalid for this page and might be corrupted.
Server Error in '/maxnetecommerce' Application.
The state information is invalid for this page and might be corrupted.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: The state information is invalid for this page and might be corrupted.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[FormatException: Invalid character in a Base-64 string.]
   System.Convert.FromBase64String(String s) +0
   System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +102
   System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) +59
   System.Web.UI.HiddenFieldPageStatePersister.Load() +124
[ViewStateException: Invalid viewstate.
    Client IP: 182.72.17.210
    Port: 54486
    User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.1; .NET4.0C)
    ViewState: /wEPDwULLTEwMjY3ODM1MjEPFgIeB2VuZERhdGUFAjMwFgJmD2QWAgIDD2QWBgIFD2QWAmYPFgIeBFRleHQF+CE8ZGl2IGlkPSdtZW51Jz48dWwgY2xhc3M9J21lbnUnPjxsaSBpZD0nMCcgb25DbGljaz0nc2V0Q29va2llKDApJz48YSBocmVmPSdEZWZhdWx0LmFzcHgnIGNsYXNzPSdwYXJlbnQnPjxzcGFuPkhvbWU8L3NwYW4+PC9hPjwvbGk+PGxpIGlkPScxJyBvbkNsaWNrPSdzZXRDb29raWUoMSknPjxhIGhyZWY9J1JlZ2lzdGVyLmFzcHgnIGNsYXNzPSdwYXJlbnQnPjxzcGFuPlJlZ2lzdGVyPC9zcGFuPjwvYT48L2xpPjxsaSAgaWQ9JzInIG9uQ2xpY2s9J3NldENvb2tpZSgyKSc+PGEgaHJlZj0nTG9naW5QYWdlLmFzcHgnIGNsYXNzPSdwYXJlbnQnPjxzcGFuPkxvZ2luPC9zcGFuPjwvYT48L2xpPjxsaSBpZD0zIG9uQ2xpY2s9J3NldENvb2tpZSgzKScgPjxhIGhyZWY9JyMnIGNsYXNzPSdwYXJlbnQnPjxzcGFuPkJpa2VzPC9zcGFuPjwvYT48ZGl2Pjx1bD4gPGxpIGlkPTMgb25DbGljaz0nc2V0Q29va2llKDMpJyA+PGEgaHJlZj0nQ2F0ZWdvcnlGZWF0dXJlZFByb2R1Y3RzLmFzcHg/UGFyZW50Q2F0aWQ9MzUmU3ViQ2...]
[HttpException (0x80004005): The state information is invalid for this page and might be corrupted.]
   System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +148
   System.Web.UI.HiddenFieldPageStatePersister.Load() +10956310
   System.Web.UI.Page.LoadPageStateFromPersistenceMedium() +11040040
   System.Web.UI.Page.LoadAllState() +46
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +11035559
   System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +11035098
   System.Web.UI.Page.ProcessRequest() +91
   System.Web.UI.Page.ProcessRequest(HttpContext context) +240
   ASP.default_aspx.ProcessRequest(HttpContext context) +52
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +599
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171
But it works fine in Mozilla Firefox,
when i remove mbscrollable from page no error comes,
can anybody please tell me solution for this.
Thanks.

A: My guess is that you have a big view state, because the mb.scrollable keep all data on the same page, and usually this data are saved on viewstate.
To test that just check the source code of your rendered html to see if viewstate are real huge.
Then if it is just change the viewstate options on web.config. You can cut it in parts automatically on web.config. You can also find code on web that compress the viewstate. You can also disable the viewstate for your control and check if you do not have other problems and you do not needed.
Hope this help.

A: Most of the time we modify pages, which causes the shadow, copied files in the Temporary ASP.NET files folder to be regenerated. A user has a copy of the page that was requested before this change, and the user posts the page after the files in that folder were regenerated.
For more detail visit  http://support.microsoft.com/kb/323744


text:
Q: Autolauncher misselected in Windows 7 You know that popup that shows up if you connect a USB device that has files on it? I once accidently selected WIndoes Media pLayer for my galaxy III and know everytime i charge it up that thing opens up...how can i change the setting to do nothing?

A: You can change the settings through AutoPlay.  Open the Control Panel and type autoplay in the search box in the upper right corner.  Open the AutoPlay applet and select the default action you want.


text:
Q: ListView - Selected Item in the middle I'm building a Windows Store app using XAML. I have a scrollable ListView that has its SelectedItem set on start.
Now, I have two requirements:

*

*I would like the selected item to be always visible

*In addition it
should be displayed in the middle of the list when possible (it's
not possible for the first element).

The first requirement I can partially fulfill by using list's LayoutUpdated event and list.ScrollIntoView(item) method, but this doesn't allow me to scroll down the list manually until the item is unselected.
For the 2nd requirement I have no ideas.

A: Ok, found out how to achieve that: http://fczaja.blogspot.com/2013/05/xaml-listview-scroll-selecteditem-to.html


text:
Q: CXF Http Conduit - timeout being ignored (JAVA) I am creating a HTTPConduit in JAVA programatically and I would like to change the conduit name to *.http_conduit
How can I set that?
Source Code:
Client client = ClientProxy.getClient(port);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(600000);
httpClientPolicy.setAllowChunking(false);
http.setClient(httpClientPolicy);


text:
Q: Windows Service Not Starting After Installing Well, I have created a new windows service and the install from Visual Studio.
When I am done installing, how can I start the service ?
I need something that will allow me to start the process, or an exe.. something?
The Installer is : Visual Studio Installer - Setup Project.
Any help?
My question in order:

*

*Why the service don't start?

*How can i control what happen after intall ? Where is the code for it?
Thanks!

A: to start your service you can either execute the command:
net start YourServiceName

or go to Control Panel -> Admin tools ->  Services and select your service and click start.
full path above depends also on your actual windows version.
even if you did not use any logging, in general service failures are recorded in the Windows Event Log so open Event Viewer and see latest events.

A: even you Set the startup type to Automatic it will not start your service automatically until the machine restart. what you can do is create event handler for AfterInstall  event of your service installer class and start the service using ServiceController Start method as below
public serviceInstaller()
{
    this.AfterInstall += new InstallEventHandler(serviceInstaller_AfterInstall);
}

void serviceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
    ServiceController sc = new ServiceController(serviceInstaller.ServiceName);
    sc.Start();
}

you can create event using the visual studio event window as well.

A: Set the startup type to Automatic in the ServiceInstaller class properties (you can do it in the Designer file).

A: A windows service needs to be installed ( it should tell you what to do if you try debugging it ), then started in the server manager. Then you can attach to it.
They are a bit of a pain to debug, TBH.

A: What does the service do? is it opening SQL connections?
looking for a file?
check in your event viewer where the service is installed for errors after you try to start it, it will give us a better understanding.

A: It is impossible to understand your question unless you take interest in making it understandable.
However from my assumption,
Goto Visual studio Tools => Visual Studio command prompt
use command net start <>
If fails starting the servicce, Check event log (eventvwr.msc in run dialog) to see if there any relevant errors logged.

A: Your Windows service working in some systems.
If you face some system getting error Windows Service not starting after installing if manually/automatically.
if the service starts and stops like that, it means your code is throwing an unhandled exception. This is pretty difficult to debug, but there are a few options.

*

*Consult the Windows Event Viewer.

Event Viewer - eventvwr.msc
Normally you can get to this by going to the computer/server manager, then clicking Event Viewer -> Windows Logs -> Application. You can see what threw the exception here, which may help, but you don't get the stack trace.
Event Viewer Log Image

*Add try/catch block in your service start method.

*Let you check whether you are using any hot code(For Ex: "D:\"). That drive is not available in installed system.
This will helps a lot!


text:
Q: Why are Data Projections relevant? Why is it useful to store data in unusual projections and datums?
I understand the value of projections as output constructs, because of distortion, etc: that much is justifiable.
However, I don't understand why, for instance, states use state plane projections in data. We have decimal accuracy: why not just store precise values in EPSG:4326? Is this entirely a remnant of pre-auto-reprojection days, or is there a value proposition I'm missing?
I'll restrict the scope of this question to vector data only to make it more concrete.

A: I'm a little uneasy relying on project- and/or calculate-on-the-fly when it comes to analysis. There's a lot of pressure to get things done and show them to the user quickly, and this leads to shortcuts. I can't count how many days I've lost tracking down problems with data alignment across layers that come from different processes only to discover that at some point a program(mer) decided that for expediency "we'll just ignore everything past the 6th decimal".
Unless one has the code, and the knowledge to understand it, the calculations behind on-the-fly transitions are invisible, it's hard to test their veracity, and impossible to tweak. For example, to use a raster geoprocessing analogy (I know your question is about vectors but it illustrates the concept clearly), when I project "manually" I can choose among nearest-neighbor, bilinear, cubic, spline, etc. depending on the nature of my data and the purpose the result is destined for. On-the-fly generally drops or hides things like this.
In the fullness of time I expect on-the-fly processing will be honed and tested enough to be reliable. I don't think we're they're yet, I could be wrong, but I remain to be convinced.

A: Different projections offer different balances of distortions in shape, area, and distance/scale. Such distortions are unavoidable when projecting a 3 dimensional object, the earth, to a 2D medium, a paper map or computer screen. Even Google Earth, 3D Analyst, and other "3D" tools don't really display 3 dimensions. So the mapmaker must choose an appropriate projection that best balances the distortions based on the purpose of the map.
Often local/state governments have mandated a projection or by law. This usually happened long before modern advances in GIS. The chosen projection, or group of projections, usually best balance all three distortions based on the locality. Governments will then require developers to tie surveys to the locally mandated projection. This will make it easier to compare developers' maps with official maps for public review, hearings, etc. It also makes all official maps look similar.

A: Legacy. Back in the Day (and now too) it was/is (much) easier to write a system that works in cartesian space instead of spherical coordinates relative on a spheroid. (What's the distance between A and B on a plane? over the surface of a sphere? of a spheroid? do you feel the degree of difficulty increasing?) And since most counties/states/cities exist in limited geographical areas that are amenable to fitting into map projections, it made sense to store and work with their data in cartesian coordinates in a local map projection.


text:
Q: Sensitive information in the document root Let's say you have a config.php that holds sensitive information like a DB user password. It is not recommended to store that file in the document root, right?
Why is that so and is it a safer approach to store sensitive information in the index.php of the document root?

A: For me, the first scenario that comes to mind is a misconfiguration that lets users download or view .php files, rather than parse them and present them as text/html. Say you perform an upgrade, something goes wrong, and Apache is no longer parsing your scripts. Somebody notices that Apache is sending your PHP files as plain text, and is able to open config.php and see the source code (and all the sensitive database configuration parameters inside).

A: To take this idea just a little bit further.  Ideally you wouldn't store much more than a simple script that accesses your codebase, and your static files like images and css in the web root.
eg:

webroot/index.php
webroot/images/img1.jpg
webroot/images/img2.jpg
webroot/css/base.css

lib/myclass1.php
lib/myclass2.php

And your index.php would look something like this:
<?php
$CODEBASE = '/usr/home/wwwuser/wherever/it/is';

include $CODEBASE."/lib/myclass1.php";

$code = new MyClass1();
$code->doStuff();

?>

A: It's not a safer approach to store configuration data in index.php than config.php; they are both equally prone to being displayed if PHP somehow fails to parse their contents. The advantage to using a separate file for configuration data is that you may limit access to it, effectively preventing anyone from reading it over the HTTP protocol and keeping your data safe(r) even if PHP isn't parsing it.


text:
Q: Vertically center text together with an image in a button It's pretty simple, I have a button, I want an icon to the left of it. The problem is that the button text is pushed downwards a little, so the icon and the text don't line up neatly. I'm not really sure what causes this, I tried vertical-align and setting the line-height.
http://codepen.io/anon/pen/EKlFb
HTML
<button>
  OBS
</button>

CSS
button {
  font-weight: bold;
  height: 27px;
  line-height: 27px;
  vertical-align: middle;
}

A: Working Fiddle
Try following:
<button>

   OBS
</button>

CSS:
button img,
button span {
  vertical-align: middle;
}

Editted:
Fiddle

A: Just float your image to the left and it should be fixed:
HTML:
<button>

  OBS
</button>

CSS:
button {
  font-weight: bold;
  height: 27px;
}

button > .icon
{
  float: left;
}

CodePen


text:
Q: XBRL R package reads adds another link to input link. Resulting in a link that cannot be opened I'm using XBRL package to import XBRL data from the SEC EDGAR website, and whenever I use xbrlDoAll function, it is unable to read the url, even though I provided the valid one. For example, to replicate this error, use the following:
library(XBRL)

inst <- "https://www.sec.gov/Archives/edgar/data/320193/000032019318000145/aapl-20180929.xml"
xbrl.vars <- xbrlDoAll(inst)

This is the error I get:
Error in fileFromCache(file) : Error in download.file(file, cached.file, quiet = !verbose) : cannot open URL 'https://www.sec.gov/Archives/edgar/data/320193/000032019318000145/https://xbrl.sec.gov/dei/2018/dei-2018-01-31.xsd'

As you can see, the URL cannot be opened because for some reason it adds another https:// in the middle of the link to get the file.

https://www.sec.gov/Archives/edgar/data/320193/000032019318000145/https://xbrl.sec.gov/dei/2018/dei-2018-01-31.xsd

Which makes it an invalid url. I tried to manually download the file to the cache folder but the issue still persists. How can I edit it so it can properly read and download the content from the links? Thank you.

A: This looks like a bug.
Just as a wild guess I would try to use a slightly modified url: http://www.sec.gov/Archives/edgar/data/320193/000032019318000145/aapl-20180929.xml.
Using http instead of https.

A: This is a bug as the package has not been maintained very well.  What you need to do is go straight to this website:  https://xbrl.sec.gov/dei/2018/dei-2018-01-31.xsd  and then save it directly into your xbrl.Cache folder (or whichever folder is serving as your cache).


text:
Q: Experimenting with objects in JavaScript I started learning JavaScript on Codecademy a few days ago, and took Lost Decade's Simple Canvas Game as a base, and I was wondering: how could I add multiple enemies? I know that it's possible, but I've had great difficulty getting it to work.
Here's my code before I broke everything.
EDIT: I've added movement to the one monster, but not sure about creating another monster object and having my functions play nice with them.

A: At the moment you have a singleton object, monster, and all your function calls are directly manipulating the properties of that one object. monster is declared in the same scope (the global scope) as all of your functions so they can access it with no problems.
To create > 1 monster at the very least you'll need to rewrite all your functions to accept a monster object, then you can manipulate the properties of each one by passing THAT monster in as an argument e.g.
var changeMonsterDirections = function(theMonster) {
    for (var i = 0; i < 2; i++) {
            theMonster.directions[i] = directions[Math.floor(Math.random() * directions.length)];
    }
    // If both directions are the same, null out one of them so that
    // the monster doesn't move twice as fast
    if (theMonster.directions[0] == theMonster.directions[1]) {
            theMonster.directions[1] = null;
    }

}
Then if you have
var monster1 = {
    speed: 200,
    directions: [null, null]
};
var monster2 = {
    speed: 200,
    directions: [null, null]
};

you can pass them around to your functions, like so
changeMonsterDirections(monster1);
changeMonsterDirections(monster2);

The above will work with your program as written but isn't object-oriented or good programming practice. A discussion of how to make your game work with proper OOP is beyond the scope of SO - try
http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/
or similar, Google around for others. Good luck.


text:
Q: How to model execution time of algorithms? Which models of algorithm running time exist?
We all expect mergesort to be faster than bublesort, and note that mergesort makes O(n log n) comparisons vs. O(n2) for bubblesort.
For other algorithms, you count other operations (than compares and swaps), such as pointer dereference, array lookup, arithmetic on fixed-size integers, etc.
What other ways to model execution time are there?
One I know of myself is counting the number of block read from and written to disk; see my answer to When does Big-O notation fail? for a lengthy description.
Another is counting the number of cache misses.  This expands on the I/O model by looking at all levels of the memory hierarchy.
A third, for distributed algorithms (such as in secure multiparty computation) is to count the amount of data transmitted across the network (commonly measured in rounds of communication or number of messages).
Which other interesting things are there to count (and not count!) in order to predict the performance of an algorithm?
Also, how good are these models?  As far as I've heard, cache oblivious algorithms are competitive with I/O-efficient algorithms for data on disk, but not for in-memory algorithms.
In particular: in which specific instances do these models mispredict relative performance?  According to my own experiments, Fibonacci heaps don't speed up Dijstra's shortest path (versus binary heaps) when the data is small enough to fit in memory.

A: You have to define a computational model, give an estimation of the cost of each operation and then analyse your algorithm in term of those costs; of course, the costs are determined by the particular environment and the characteristics of the underlying machine where you want to deploy your algorithm, so the question is really too generic.
In an algorithm course, we just assume that each operation costs 1, so we just count how many times we loop; in algorithms that works with main memory, we assume that each operations, apart read/write from I/O, costs 0 (and read/write 1), and so on.
Are those models tight with the reality? It depends on the reality: your environment and your machine.
Your calculation with cache misses could be correct on a core duo, but wrong with a cell processor, where you have to transfer manually the contents of the memory of SPEs, for example.

A: I think that whatever your basis for modelling execution time/space using O(n...) notations, you are assuming a normalized environment. I would think that whatever model you specify, and no matter how many variables you measure to determine it ... it only applies in a normalized environment. So when disk I/O is low in competition terms O(n...) may not be required to factor in those overheads ... if you see my point.
So O(n) models typical performance in a normalized environment on the input n.
By extension you can say disk reads are in the order O(n) or that memory allocations are order O(n) and so on. External events that add pressure (such as scheduling) shouldn't play a part in the model of typical time/space/occurrence of anything.
Or maybe I am missing your point (Which I suspect I might be).

A: For the realtime platforms I work on, lately I find that copying largeish amounts of data (eg: in the KB range, not the MB range) is actually way quicker than I've been trained to expect. Probably this has to do with the large caches in use today, or perhaps just the blazing fast processor speed. But the effect is that one really shouldn't bother to pervert one's code too badly anymore just to avoid data copies.
Instead, the things I really have to look out for are device accesses and context switches. The fewer of those, the better.
The days when "zero buffer" device drivers were synonomous with speed are over.


text:
Q: Verify kurento media server using wss How to verify kurento media server is using wss or not?
As mention this documentation I'd uncommented the
"secure": {
  "port": 8433,
  "certificate": "defaultCertificate.pem",
  "password": ""
},
and provided the certificate and password pem files, but when i'm passing KMS_URI = "wss://localhost:8433/kurento" I'm unable to get icecandidates also. But by using KMS_URI = "ws://localhost:8888/kurento" I can able to get icecandidates from the KMS but unable to reach ICECANDIDATES STATE as "CONNECTED". (Using nodeJS as Signaling Server)

*

*Is there any command or way to check whether KMS using wss protocol or not?

*If I'm using all these thing why I'm unable to reach Icecandidatestate as "CONNECTED"?

Edit 1

*

*I build my application by following kurento documentation (one-to-many nodeJS example). And I had hosted my app on Amazon ec2 machine. Both servers are on same machine i.e. nodeJS server and KMS.

*google STUN server address is configured in my application.

*Using KMS version 6.0 & kurento-client-js version 6.6.0

*Libnice is also updated with version 0.1.13

My application was running fine but suddenly I don't know why its because of chrome update or what application is unable to reach connected state even it is return icecandidates to clients but unable to reach icecandidates connected state. Lastly due to chrome update version 52, I had stuck with the same problem but by using SSL certificate on KMS it starts working fine.
By using command
sudo netstat -putan | grep kurento

KMS is listening both 8443 and 8888 ports
But the thing is that when I'm using KMS_URI = "ws://localhost:8888/kurento" in my node server.js file to create Pipeline it is returning icecandidates to clients and pipeline get created. But when I'm passing KMS_URI = "wss://localhost:8443/kurento" it is returning a log message reconnect to server . So, what exactly is the problem does KMS not using certificate file or anything else.
Rest about the certificate so there should be no issue with certificate because I'm using same certificate for nodeJS application and both the servers are on same machine so I'd used that same certificate for KMS also. For nodeJS application certificate is working fine.

A: You can check which ports an app is listening with the following command
sudo netstat -putan | grep kurento

As to why you don't complete the negotiation, it might not be related to that. There are a number of things very important about which you are not saying anything

*

*What type of app are you running? What's the setup?

*Are you running your KMS behind a NAT? Spoiler alert: this is 99% of the times the case

*Did you configure STUN and/or TURN in your KMS?

*Are you using different clients?

*What version of KMS are you using?

UPDATE 1
You are trying to connect your node.js server app to the incorrect port 8443. Per your configuration, your KMS is listening on 8433 (note the last two digits are 3s). Apart from that, if you are going to place your server app and your KMS in the same server, as you are doing right now, there is no point in using WSS.

A: My problem is resolved finally by using "74.125.200.127:19302" stun server address in place of "173.194.66.127:19302". I had verified both stun server addresses by using this webrtc trickle-ice link.


text:
Q: NoMethodError: undefined method `to_sym' for {:factory=>:user}:Hash I get an error when I call create on the character factory
    factory :user do |f|
        f.sequence(:email) { |n| "foo#{n}@example.com" }
        f.password "password"
  end

    factory :character do |f|
        f.name "testcharone"
        f.race "human"
    after(:create) { |character| character.init("fighter")}
    association factory: :user
  end

Error:
NoMethodError:
       undefined method `to_sym' for {:factory=>:user}:Hash

Can anyone see what's wrong?
This test took 16 minutes to complete, while the others, which are similiar took between 5-10 minutes
describe Character do
    let(:character) { FactoryGirl.create :character}

  describe "#add_units" do
        context "when unit doesnt exist beforehand" do
        it "it create a new member" do
            expect(character.owns.count).to eq(0)
            character.add_units("character", "Archer" => 1)
            expect(character.owns.count).to eq(1)
            expect(character.owns.first.amount).to eq(1)
        end
    end

A: In factory :character,
Replace
 association factory: :user

With
 association :user

You have to pass only the factory name i.e., :user in this case and not a hash factory: :user

A: You facotry should be as  like below
Hope you should ahave a factory for user as well
factory :character do |f|
   f.name "testcharone"
   f.race "human"
   f.association :author, factory: :user
   after(:create) { |character| character.init("fighter")}
end

or
 factory :character do
   name "testcharone"
   race "human"
   association :user
   after(:create) { |character| character.init("fighter")}
end


text:
Q: A quotient ring of a polynomial ring over $F$ with infinitely many variables is isomorphic to a polynomial ring in one variable over $F$. The Problem: Let $F[x, y_1, y_2,\dots]$ be the polynomial ring in the infinite set of variables $x, y_1, y_2, \dots$ over the field $F$, and let $I$ be the ideal $(x-y_1^2, y_1-y_2^2,\dots, y_i-y_{i+1}^2,\dots)$ in this ring. Define $R=F[x, y_1, y_2,\dots]/I$. Denote the image of $y_i$ in $R$ as $x^{1/2^i}$. Let $R_n$ be the subring of $R$ generated by $F$ and $x^{1/2^n}$. Prove that $R_n$ is isomorphic to a polynomial ring in one variable over $F$.
Hint: First show that the ring $S_n=F[x, y_1,\dots, y_n]/(x-y_1^2, y_1-y_2^2,\dots, y_{n-1}-y_n^2)$ is isomorphic to the polynomial ring $F[y_n]$. Then show any polynomial relation $y_n$ satisfies in $R_n$ gives a corresponding relation in $S_N$ for some $N\geq n$.
Source: Abstract Algebra, $\mathit{3^{rd}}$ edition by Dummit and Foote.
I failed to make use of the first half of the hint, and did not even understand the second half. I failed to come up with an explicit isomorphism from $S_n$ to $F[y_n]$, or a homomorphism from $F[x, y_1,\dots, y_n]$ to $F[y_n]$ with kernel $(x-y_1^2, y_1-y_2^2,\dots, y_{n-1}-y_n^2)$. Any help would be greatly appreciated.


text:
Q: Display passed data from one Ionic 3 vpage to another So, I have data displaying on one page with a (click) event that passes data to another page, except I can only get the data to print in the console and not the page itself.  I've been at it for hours and am at my breaking point :)
I am only going to show the relevant code below to keep the post shortened (well, what I think is relevant)
list2page.html
...
<button class="list-item" tappable ion-item (click)="goToFeed(item)" *ngFor="let item of list2.items">
  ...
</button>
...

list2page.ts
...
goToFeed(item) {
  this.nav.push(ProfilePage, {item: item});
}
...

profile.ts - it will print the entire item to console - see screenshot
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

import 'rxjs/Rx';

@Component({
  selector: 'profile-page',
  templateUrl: 'profile.html'
})
export class ProfilePage {

  constructor(
    public nav: NavController,
    public navParams: NavParams,
  ) {
  }

  ionViewDidLoad() {
    let veteran_first = (this.navParams.get('item.veteran_first'));
    console.log(this.navParams.get('item'));
  }

}

A: You should define veteran_first as a class variable, not a local variable:
  export class ProfilePage {
  veteran_first; //------------------------> define it here
  constructor(public nav: NavController, public navParams: NavParams) {}

  ionViewDidLoad() {
    // Assign to this.veteran_first
    this.veteran_first = this.navParams.get("item.veteran_first");
    console.log(this.navParams.get("item"));
  }
}

Then in profile.html:
<div>
    veteran_first = {{veteran_first}}
</div>

A: Delcare a parameter on your model:
public data: any;

Then instantiate like so:
this.data = this.navParams.data;

or this should also work
this.data = this.navParams.get('item');

then after you have it, you should be able to drill into it
this.data.item.veteran_first

or something to that effect. I have used both ways to fetch data passed thru the navCtrl.


text: Q: 3-way measure of association, nominal variables Cramer's V does a great job of capturing the degree of association between two nominal variables. What measure is best suited for capturing a similar association between three nominal variables?


text:
Q: How to get object property from each object in an array? Assuming I have an array of objects in PHP, something like:
Array (
    [0] => stdClass Object (
            [id] => 1
            [name] => Title One
        )
    [1] => stdClass Object (
            [id] => 2
            [name] => Title Two
        )

    [2] => stdClass Object (
            [id] => 7
            [name] => Title Seven
        )
)

What is the best way (i.e. fastest) to get an array of the IDs? i.e. array(1,2,7) I can loop manually but I feel there must be a better method.
Just saw this in the similar questions but there's a little debate over whether the accepted answer is really the best way, plus it's from 2 years ago. I'm on PHP 5.3.

A: You can use array_map to get the IDs from each element.
function getID($a){
   return $a->id;
}
$IDs = array_map('getID', $array);

Demo: http://ideone.com/nf3ug

A: Since PHP 7.0 you may use the builtin function array_column for that, which takes an input array and the name of the property you want to pluck:
$ids = array_column($input, 'id');
// array(0 => 1, 1 => 2, 2 => 7)

As a third parameter, you may optionally supply an index-key as well:
$ids = array_column($input, 'name', 'id');
// array(1 => 'Title One', 2 => 'Title Two', 7 => 'Title Seven')

Please note that, although it's already available in PHP 5.5.0, support for an array of objects was first introduced in PHP 7.0.

A: The fastest way is simply looping (foreach, for, while). Using callback functions will incur unnecessary overhead.
I would look to see if there's a way to create the list via the code that is building the initial array of objects.

A: I'm using RedBean and for some reason passing in "getID" didn't work for me, so here is how I done it:
$ids = array_map(function($val){return $val->id;}, $objects);

A: You can do it easily with ouzo goodies
$result = array_map(Functions::extract()->id, $objects);

or with Arrays (from ouzo goodies)
$result = Arrays::map($objects, Functions::extract()->id);

Check out: http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract
See also functional programming with ouzo (I cannot post a link).

A: Did you try the array_keys function?
EDIT:
<?php
   $ids = array();
   for($c=0; $c<count($the_array); $c++) $ids[$c] = $the_array[$c]->id;
?>

A: You can also use extract_property() which is a well tested library designed specifically for this job (disclaimer: I am the author).


text:
Q: How to send email from jenkins using port number 25 How to send email from jenkins using port number 25.
Jenkins release version 2.235.3 SMTP port field for Extended E-mail Notification keeps getting reverted back to port no. 25  even after adding either 465 or 587 port number in that field and clicking "Apply and Save" buttons.
i have used telnet to verify whether smtp.gmail.com is accessible/open on ports 25,465 & 587.
smtp.gmail.com is accessible and open on 465 and 587, but not on port 25 & telnet gives me below message.
"telnet: Unable to connect to remote host: Network is unreachable"
how can we use port number 25 of smtp to send mails  using jenkins or general.
Is it even advisable to use port no. 25 of gmail to send emails from third party vendors.

A: You can follow status of this issue from link here https://issues.jenkins.io/browse/JENKINS-63367
On 08/14/2020 they will be releasing a fix for it but if you do not want to wait for it you can downgrade email-ext-plugin to 2.71 and you will be able to change SMTP port number. This is an issue everyone is facing for version 2.73 and 2.74. Hope it will be fixed with 2.74 version.
If you just setup your Jenkins, you will not have an option to downgrade, instead:

*

*uninstall plugin and then navigate to https://updates.jenkins.io/download/plugins/email-ext/ and download version 2.71

*Go to Jenkins > Manage Jenkins> Manage Plugins > Advanced > Upload Plugin  and choose downloaded verion and click on upload.

Let it finish installing and after that, restart your Jenkins. Now you should be able to change SMTP port without any issue!


text:
Q: Can't access the `rawBytes` public member in the `BarCode`class To use the content of a BarCode, I want to access to it's raw value. If I use the rawValue member, the compilation ends successfully, but when I try with the rawBytes member, the compiler stops with an error indicating it can't find the rawBytessymbol...
As both members are declared public, according to the Android documentation, I don't understand why I can use one and not the other.
Any explanation?
How I import the BarCodeclass : import com.google.android.gms.vision.barcode.Barcode;
How I access both members :
Barcode b=new Barcode();
String s=b.rawValue;
byte [] tab=b.rawBytes;

The rawBytes word is displayed in red in the editor.


text:
Q: Combining string with variable in SQL Server I am very new to SQL Server. I want to combine 01-JUL- and a variable with a year to get a date and am doing this:
select
   *,
   '01-Jan-1900' as from_date_x,
   '01-JUL-' + from_finyr as to_date_x
into
   bbt_item_6_a
from
   bbt_item_5_finyrs

and am getting the following error:

Conversion failed when converting the varchar value '01-JUL-' to data type int.

I have tried searching for the answer but cannot get it.
Thanks

A: It sounds like the from_finyr field has int data type.  Instead, you need:
    select *,
        '01-Jan-1900' as from_date_x,
        '01-JUL-' + CAST(from_finyr AS varchar(4)) as to_date_x
    into bbt_item_6_a
    from bbt_item_5_finyrs

A: Following SQL is an example, on how you can combine "01-JUL-" and a variable with a year to get a date: SELECT CAST('01-JUL-' + @varaible AS DATE) AS to_date_x