text:
Q: Removing commited files from older commit that have been deleted locally I've managed to commit some files incidentally in commit A001. Those files are quite big (around 100MB each). After noticing my mistake, In next commit, I've deleted those files with rm command, and commited those changes to commit A002. I've thought that this solved my problem and continued developing. After few commits, let's say commit A005 I've tried to push everything on remote (Large files have been deleted, but they're still commited in commit A001), push fails with following message:
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
...
...

 ! [remote rejected] melodic-dev -> melodic-dev (pre-receive hook declined)

Which is okay, because large files still exist in commit A001.
How can I do following:

*

*Go back to commit A001, unstage those large files and recreate commit A001 without those large files that have been removed, do same to commit A002

*Recreate all following commits A003-A005as they were on tip of the recreated A001_edited-A002_edited commits without those large files

*Push corrected A001-A005 commits to remote branch

I would need something like: Create new branch that has all commits NEW_BRANCH:A001-A005. In that branch, I would like to remove some files from commit A001, therefore i would have NEW_BRANCH: A001_edited commit, and I would like to merge OLD_BRANCH:A001-A002-A003-A004-A005 with NEW_BRANCH: A001_edited-A002_edited so that I have following: OLD_BRANCH: A001_edited-A002_edited-A003-A004-A005
A001_edited = A001 without commiting (revert git add Large files) those large files
A002_edited = A002 without removing (revert git rm Large files) those large files
In two successive commits somewhere in history, I want to remove some staged/unstaged files and keep everything else the same.
I've tried some stuff, but without success.
I hope I've clarified my problem enough, if not let me know :)
Thank you for your time and help.

A: This can be fixed with a powerful and scary approach called rebasing! :) Here's one way:

*

*Run git rebase -i --root. This will open an editor listing all commits all the way from A001 to your latest one.

*In that file, change the word "pick" in front of A001 to "edit". Save the file and close the editor.

*Git will rewind you to the moment after you made A001 (where you added the big files by mistake). Run git rm --cached bigfile1 bigfile2 to remove them from the index, then run git commit --amend to fix commit A001 to not contain them.

*Run git rebase --continue. This will reapply all commits after that on top of the commit you changed. A002 should now only contain the changes you made other than removing the files. No commit should contain the big files anymore.

Hope that works for you, let me know if you encounter any problems!

A: I've managed to use rebase as suggested by blinry but without git rm --cached bigfile1 bigfile2.
I would use git rm --cached bigfile1 bigfile2 if I haven't already done so
with A002 commit.
To clarify, I've added accidentaly some big files to A001 and
removed them in commit A002 which disabled me from pushing on remote branch. I've simply used interactive rebasing and squashed commit A002 into A001:
as follows:
pick A005
pick A004
pick A003
squash A002
pick A001

Squash command "merges" choosen commit with previous one, in this case it "merged" removal of big files with addition of big files and some code changes, which resulted with wanted code changes and without big files, and clean git history (Everything before A001 - A001_without_big_files -A003-A004-A005)
Thank you for your help:)


text:
Q: Activate HDMI output without using as desktop I have an Intel card, and it appears that it is not possible to just stream audio and no video. So is there a way to just activate the port and send a dummy video signal to have audio working? I do not want to extend my desktop on the additional screen.

A: You can set up a second X display for the HDMI output. This will still use up video RAM and display it, but it will be separate from your primary desktop, so your desktop stays on your monitor and doesn't extend to the additional screen. I've set this up on my Intel integrated graphics with an /etc/X11/xorg.conf file that contains
Section "Device"
    Identifier "intel0"
    Driver "intel"
    Option "AccelMethod" "sna"
    Option "ZaphodHeads" "VGA1,HDMI1,DP1"
    Screen 0
EndSection

Section "Device"
    Identifier "intel1"
    Driver "intel"
    Option "AccelMethod" "sna"
    Option "ZaphodHeads" "HDMI3"
    Screen 1
EndSection

You can add Screen sections to specify the resolution if you want.
You'll probably need different output names, look at the output of xrandr to see what outputs your card has. I don't remember why I had to specify the AccelMethod, maybe it was to make it work on my particular chipset. The first screen will have the display name :0, the second on the HDMI port :1 (so you can still tell programs to make use of it if you want to by adding options like -display :1 when you run them).
I'm using two instances of the fvwm window manager for each display; possibly you may need to tell your window manager to only use the first display.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sublime Text 2 Package Control installed but is deleted upon Restart I have copied Package Control.sublime-package in the directory ~/Library/Application\ Support/Sublime\ Text\ 2/Installed\ Packages/
as per instructions in
https://packagecontrol.io/installation#st2
However, after restarting Sublime, the file gets deleted!
None of the answers in Sublime Text 2 - Package Control installed but the list not shown helps to solve this problem.
Any idea what is going on here?


text:
Q: Add if data is new Or Update when data is different angularjs I am trying to Update the data instead of adding (create) a new data when the image is changed (image is in base64)
I had also followed: http://jsfiddle.net/4Zeuk/12/ like what i tried to do below but i had tried my best at it but it update is not working. There are no errors.
Just for your information i am using ngCropper. https://github.com/koorgoo/ngCropper
EDIT: updated controller code
Angular code
      app.controller("ProductAddCtrl", function($scope, $timeout, $resource, Product, Products, $location, Cropper) {
        $scope.product = {item_name: '', price: '', category: ''}
        var file, data;

        $scope.saveImage = function(dataUrl) {
          if (!file || !data) return;
           if ($scope.product.currentImage){
              Cropper.crop(file, data).then(Cropper.encode).then(function(dataUrl) {
                ($scope.preview || ($scope.preview = {})).dataUrl = dataUrl;
                  Product.update({id: $scope.product.id }, {product: { item_name: $scope.product.item_name, category: $scope.product.category, price: $scope.product.price, item_image: dataUrl, filename: file.name}},function(){
            //  $location.path('/');
                console.log($scope.product)
                }, function(error) {
                  console.log(error)
                });
              });
            } else {
              Cropper.crop(file, data).then(Cropper.encode).then(function(dataUrl) {
                ($scope.preview || ($scope.preview = {})).dataUrl = dataUrl;
                  Products.create({ product: { item_name: $scope.product.item_name, price: $scope.product.price, item_image: dataUrl, filename: file.name }}, function(){
                  // $location.path('/');
                  }, function(error){
                    console.log(error)
                  });
              })
            }
          }

          $scope.onChange = function() {
            if ($scope.product.currentImage) {
              $scope.product.item_image = $scope.product.currentImage.item_image;
              $scope.product.filename = $scope.product.currentImage.filename;
            } else {
              $scope.product = {};
            }
          }
  });

Angular Template file

  <input type="file" onchange="angular.element(this).scope().onFile(this.files[0])" ng-class="{'has-error' : productForm.item_image.$invalid}" ng-model="product.currentImage" ng-change="onChange" required>

      <button ng-click="preview()" class="btn btn-success">Show preview</button>
      <button ng-click="zoomin()" class="btn btn-default">Zoom In</button>
      <button ng-click="zoomout()" class="btn btn-default">Zoom Out</button>

      <input type="submit" value="{{ product.currentImage.item_image ? 'Update' : 'Save' }}", class="btn btn-default" ng-click="saveImage()">

      <select name="sellCategory" class="form-control" id="sellCategory" ng-model="product.category" required>
        <option ng-repeat="option in categories.availableCategories" value="{{option.category}}">{{option.name}}</option>
      </select>
      <input type="text" ng-model="product.item_name" class="form-control" placeholder="Item Name" required>
      <input type="text" ng-model="product.price" class="form-control" placeholder="Item Price" required>

A: I grasped the concept wrong.
Let's say i have multiple file upload feature in, instead of configuring angularjs to upload file one by one (via PUT request), i would select each file in base64 format (for preview) and then input the fields (like price, category and name of item) on the client side in angularjs instead of POSTing the PUTting each and every data.
So after everything on client side is set with image preview (i intend to have four) and data, then i would save (POST) it to the backend instead.
Thanks to everyone who looked at my question.


text:
Q: Files not installing for Django/Python web app I'm trying to open a web app locally on my laptop and the files aren't installing. I tried these two methods of installing the files:
    $ pip3 install -r requirements.txt
    $ pipenv install -r ./requirements.txt

But in both ways, I get the following error:
An error occurred while installing scipy==1.1.0
...
ERROR: Couldn't install package: psycopg2
...
 Package installation failed...

So I then manually installed the files on the command line.
But, when I do $python3 manage.py runserver then I get this error:
ModuleNotFoundError: No module named 'numpy.core._multiarray_umath'
Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x7fbb65b6b790>
Traceback (most recent call last):
  File "/Users/dhanush/.local/share/virtualenvs/sisu-test-release-uLyEUBTr/lib/python3.8/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/Users/dhanush/.local/share/virtualenvs/sisu-test-release-uLyEUBTr/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run
    self.check(display_num_errors=True)
  File "/Users/dhanush/.local/share/virtualenvs/sisu-test-release-uLyEUBTr/lib/python3.8/site-packages/django/core/management/base.py", line 361, in check
    all_issues = self._run_checks(
  File "/Users/dhanush/.local/share/virtualenvs/sisu-test-release-uLyEUBTr/lib/python3.8/site-packages/django/core/management/base.py", line 351, in _run_checks
    return checks.run_checks(**kwargs)
  File "/Users/dhanush/.local/share/virtualenvs/sisu-test-release-uLyEUBTr/lib/python3.8/site-packages/django/core/checks/registry.py", line 73, in run_checks
    new_errors = check(app_configs=app_configs)
...
ImportError: numpy.core.multiarray failed to import

I've spent all day trying to get this web app running. Thanks for your help!


text:
Q: How to access CSV file using OS module How do I access a CSV file on my computer in Jupyter notebook using os module?
I've tried the below code:
    import os
    file =
    (r"C:\Users\...", "r")
    text = file.read()
    file.close

A: You can use it directly without os module:
with open(r"C:\Users\xyz\Desktop\test.csv","r") as f1:
    lines = f1.readlines()

OR
f = open(r"C:\Users\xyz\Desktop\test.csv", "r")

A: You don't need to manually open and close the file, the keyword 'with' does that for you:
import csv

file = r'path\to\your.csv'

with open(file, 'r') as csvfile:
    # do something

For more info please check the official documentation of the CSV module.


text:
Q: AttributeError: 'DataFrame' object has no attribute 'seek' In the DataProcessor class, the raw_file_processing, dataset_csv, classes_csv, and idset_csv functions process the raw datafile and output csv files that can be read by the read_archive function.
My code raised AttributeError: 'DataFrame' object has no attribute 'seek' error.
import pandas as pd
import warnings
import numpy as np
import os
import zipfile
import re
from sklearn.model_selection import train_test_split

class DataProcesser:
    def __init__(self, archive_path, col_id='ID', col_class='class', col_classname='class_name', col_set='set',
                 read_on_init=True, **kwargs):

        self.archive_path = archive_path
        self.archive = zipfile.ZipFile(self.archive_path, 'r')
        self.col_id = col_id
        self.col_class = col_class
        self.col_classname = col_classname
        self.col_set = col_set
        self.dataset = None
        self.dataset_cropped = None
        self.id_set = None
        self.classes = None
        self.train_set = None
        self.validation_set = None
        self.test_set = None
        self.logs = []
        self.stats = None
        self.flag_subset = False
        self.flag_process = False
        self.flag_split = False
        self.measurement_df = None
        if read_on_init:
            self.read_archive(**kwargs)

        def raw_file_processing(self):

            # If the path contains HTAN CODEX data, perform the following processing steps
            if os.path.isdir(archive_path):

                # 'Class' refers to the independent variable
                # The class info is the 3rd column tile_num in the current example
                # The rationale for looking at tile_num is that if we're examining tumor progression, we can observe the relative positions of the tumor growth
                # Tumor progression may be denoted by the corresponding values of tumor progression markers/antibodies such as CEA
                # In the future, we may append all the tumor patient files and normal patient files and then assign patient number as "class"
                self.col_classname = self.archive_path.iloc[2]

                # Dummy-code the classes
                self.col_class = pd.get_dummies(self.col_classname)

                # Create the ID series by concatenating columns 1-3
                self.col_id = self.archive_path.assign(
                    ID=self.archive_path[['cell_id:cell_id', 'region:region', 'tile_num:tile_num']].apply(
                        lambda row: '_'.join([str(each) for each in row]), axis=1))
                self.col_id = self.archive_path.drop(columns=['cell_id:cell_id', 'region:region', 'tile_num:tile_num'])

                # Obtain measurement info
                # Normalize data against blank/empty columns
                # log-transform the data
                for col in self.archive_path[9:]:
                    if re.findall(r"Blank|Empty", col):
                        background = col
                    else:
                        for index, row in col:
                            norm_data = row / background
                            self.measurement_df = np.log2(norm_data)

            return self.archive_path, self.col_id, self.col_class, self.measurement_df

    def dataset_csv(self):

        # If the path contains HTAN CODEX data, perform the following processing steps
        if os.path.isdir(self.archive_path):
            """Col 1: ID
            Col 2: class
            Col 3-n: measurements"""
            id_col = self.col_id

            self.col_class = self.col_class.to_frame()

            frames = [id_col, self.col_class, self.measurement_df]
            self.dataset = pd.concat(frames)
            data_csv = self.dataset.to_csv("../input_data/dataset.csv")

        return data_csv

    def classes_csv(self):

        # If the path contains HTAN CODEX data, perform the following processing steps
        if os.path.isdir(self.archive_path):
            # Remove any duplicate rows with the same col_class and cls_col info
            self.cls_df = pd.DataFrame({'class': [self.col_class], 'class_name': [self.col_classname]})
            self.cls_df.drop_duplicate(keep=False, inplace=True)

            # Save as csv file
            self.cls_df.to_csv('../input_data/classes.csv')

        return self.cls_df

    def idset_csv(self):

        # If the path contains HTAN CODEX data, perform the following processing steps
        if os.path.isdir(self.archive_path):
            # Get the ids
            ids = self.archive_path[0]

            # Train-test-validation split
            ids.sample(frac=1)
            train, test = train_test_split(ids, test_size=0.2, random_state=1)
            train, val = train_test_split(train, test_size=0.25, random_state=1)

            # Assuming train, val, test are dataframes
            # A string is assigned to the "set" column.
            train.loc[:, 'set'] = 'train'
            val.loc[:, 'set'] = 'val'
            test.loc[:, 'set'] = 'test'

            # Save as csv file
            id_set = pd.concat([train, val, test], axis=0)
            id_set_csv = id_set.to_csv('../input_data/id_set.csv', index=False)

        return id_set_csv

    def zip_files(self):

        # Create a ZipFile object for dataset.csv, classes.csv, and id_set.csv
        zip = ZipFile("data.zip", "w")
        zip.write("dataset.csv")
        zip.write("classes.csv")
        zip.write("id_set.csv")
        zip.close()
        return zip

    def read_archive(self, datatable=True, **kwargs):
        """
        Read a zip archive, without extraction, than contains:
        * data as .csv, observations in rows, measurements in columns. Names of columns must have the format:
         A_1, A_2, A_3,..., C_1, C_2,... where A and C are groups (sensors) and 1,2,3... measurement time
        * IDs of training/validation/test as .csv
        * Explicit name of classes as .csv
        :return: 2 pandas, one with raw data, one with IDs
        """
        if datatable:
            try:
                from datatable import fread
                self.dataset = fread(self.archive.open('dataset.csv'), **kwargs).to_pandas()
                self.id_set = fread(self.archive.open('id_set.csv'), **kwargs).to_pandas()
                self.classes = fread(self.archive.open('classes.csv'), **kwargs).to_pandas()
            except ModuleNotFoundError:
                warnings.warn('datatable module not found, using pandas instead. To prevent this message from appearing'
                              ' use "datatable = False" when reading the archive.')
                self.dataset = pd.read_csv(self.archive.open('dataset.csv'))
                self.id_set = pd.read_csv(self.archive.open('id_set.csv'))
                self.classes = pd.read_csv(self.archive.open('classes.csv'))
        else:
            self.dataset = pd.read_csv(self.archive.open('dataset.csv'))
            self.id_set = pd.read_csv(self.archive.open('id_set.csv'))
            self.classes = pd.read_csv(self.archive.open('classes.csv'))
        self.check_datasets()
        self.logs.append('Read archive: {0}'.format(self.archive_path))
        return None

input_path = "//wsl$/Ubuntu-20.04/home/melissachua/CODEX/input_data"
# Open all the subfolders within path
for root, dirs, files in os.walk(input_path):
    for file in files:
        with open(os.path.join(root, file), "r") as data:
            data_file = pd.read_csv(data)
            data = DataProcesser(data_file, datatable=False)

meas_var = None
start_time = None
end_time = None

# Open all the subfolders within path
for root, dirs, files in os.walk(input_path):
    for file in files:
        with open(os.path.join(root, file), "r") as data:
            data_file = pd.read_csv(data)

            # The data object is used to automatically derive some parameters (e.g. number of classes)
            data = DataProcesser(data_file, datatable=False)

Traceback
> Traceback (most recent call last):   File
> "C:/Users/User/PycharmProjects/CODEX/main.py", line 171, in <module>
>     data = DataProcesser(data_file, datatable=False)   File "C:/Users/User/PycharmProjects/CODEX/main.py", line 16, in __init__
>     self.archive = zipfile.ZipFile(self.archive_path, 'r')   File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\zipfile.py",
> line 1269, in __init__
>     self._RealGetContents()   File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\zipfile.py",
> line 1332, in _RealGetContents
>     endrec = _EndRecData(fp)   File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\zipfile.py",
> line 264, in _EndRecData
>     fpin.seek(0, 2)   File "C:\Users\User\PycharmProjects\CODEX\venv\lib\site-packages\pandas\core\generic.py",
> line 5487, in __getattr__
>     return object.__getattribute__(self, name) AttributeError: 'DataFrame' object has no attribute 'seek'
>
> Process finished with exit code 1

A: The error you are getting is from the zipfile.ZipFile call. You should pass (the path to) a .zip file to your constructor, not a pandas DataFrame.

A: In your code you have the following lines:

data_file = pd.read_csv(data)
data = DataProcesser(data_file, datatable=False)

With the first line you are reading a csv file into a DataFrame and storing this DataFrame in a variable data_file.
The second line uses this DataFrame as input for your DataProcesser constructor. The constructor, however, is defined as follows:
def __init__(self, archive_path, col_id='ID', col_class='class', col_classname='class_name', col_set='set',
                 read_on_init=True, **kwargs):

You are passing your DataFrame as archive_path, which is not what  your constructor is expecting. The constructor is expecting a str as file name (also a file would be appropriate) for example for the zipfile constructor or the os functions. See Zipfile documnetation for example.
Therefore, store your DataFrame in another variable and use the archive_path for the file path.  Unfortunately, you have mixed up the DataFrame instance and the archive_path multiple times in your code. Here are a few examples.

# Constrcutor
self.archive = zipfile.ZipFile(self.archive_path, 'r')

...

# First method
if os.path.isdir(archive_path):

...

self.col_classname = self.archive_path.iloc[2]

...
for col in self.archive_path[9:]:


text:
Q: chai-http write after end I have a server-app that receives an audio stream from the client. I am trying to test the app using chai/chai-http, but it gives me this error:

[Error: write after end]

What's the problem?
Code:
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../server-app');
var should = chai.should();
var fs = require('fs');

chai.use(chaiHttp);

describe('server', function() {
  it('should work..', function (done){
    var req = chai.request(server).post('/speech');
    fs.createReadStream('./test.wav').pipe(req);
    req.end(function (err,res){
        console.log(err);//outputs: [Error: write after end]
        done();
    });
  });
});

A: You're calling req.end before the stream finishes pushing data to the request.
I would do the following:
var readstream = fs.createReadStream('./test.wav');
readstream.pipe(req);

readstream.on('close', someFunction);
readstream.on('end', someFunction);

and call req.end in the close or end events for the stream. You're calling req.end before either of those events are emitted.

A: Basically JavaScript is asynchronus and stream or socket connection is synchronus ,Once you created a stream you have to wait for the stream to close to make another request
In your case the req.end getting executed once you opened the stream
Three options available to make it to be work

*

*Try with chai agent

*Put your code in the stream close because both chai.end and stream end seems to be same for your scenario

*put req.end inside setTimeOut (Did not tried may be for worst case)

A: When piping, by default, end() is called on the destination when the source stream emits 'end' event. So you don't have to call end() by youself.
Suscribe to the 'finish' and 'error' event of the destination stream to control when the work it is done or when a error happens:
 fs.createReadStream('./test.wav').pipe(req);
 req.on('error', (err) => {console.log(err);});
 req.on('finish',() => {done();});

If you want to keep the writer (req) open you can set end option to false when piping:
fs.createReadStream('./test.wav').pipe(req, options = {end = false}); but keep in mind that 'finish' event wont be fired up by the pipe.


text:
Q: How long should a SAML Token be valid has anybody an advice, how long a SAML Token should be valid (in a SOA infrastructure)?
I thought of several (6-12) hours.
many thanks
Markus

A: It is generally a bad idea to have such a high lifetime for your tokens, because they can theoretically be "stolen" and reused. Token issuance should not be an especially timely affair, so I would recommend that you reauthenticate your users with the STS quite often, and only let your token "live" for a few minutes.


text:
Q: Add values in second array depending upon the values in first array Here's the situation:
Suppose I have first Array as:
Array(
    [0] => Person1
    [1] => Person1
    [2] => Person2
)

And second array as:
Array(
    [0] => 100.00
    [1] => 150.25
    [2] => 157.15
)

How do I add values (100.00 + 150.25) of second Array and merge them (250.25) so that they belong to Person1 in the first array.
Desired Output:
Array(
    [0] => 250.25 // for Person1 in the first Array after adding
    [1] => 157.15 // for Person2 in the first Array
)

Any help is highly appreciated. Thank You.
P.S.: All the values are coming from the database.
EDIT 1:
Here's what I have tried, but this outputs the second array as it is:
$sums = array();
$sums = array_fill_keys(array_keys($affiCode + $affiCommAmount), 0);
array_walk($sums, function (&$value, $key, $arrs) {
    $value = @($arrs[0][$key] + $arrs[1][$key]);
    }, array($affiCode, $affiCommAmount)
);

A: The arrays are the same size, so you can use a for loop to process them simultaneously:
for($i = 0; $i<count($personArray); $i++)

Within the loop, construct a new array keyed to the values from the first array. If the key does not yet exist, initialize it:
if (!isset($newArray[$personArray[$i]])) {
    $newArray[$personArray[$i]] = 0.0;
}

then add the new value to the selected array key:
$newArray[$personArray[$i]] += $valueArray[$i]

When the loop ends, $newArray will look like:
Array(
    ['Person1'] => 250.25
    ['Person2'] => 157.15
)

If you want to replace the 'Person1' and 'Person2' keys with numerical indexes, use array_values():
$numericallyIndexedArray = array_values($newArray);

The final code looks like:
$newArray = [];
for($i = 0; $i<count($personArray); $i++) {
    if (!isset($newArray[$personArray[$i]])) {
        $newArray[$personArray[$i]] = 0;
    }

    $newArray[$personArray[$i]] += $valueArray[$i];
}

// Optionally return the new array with numerical indexes:
$numericallyIndexedArray = array_values($newArray);

A: Get the person from first array by index and add the money:
for($i=0;$i<count(arrayPerson);$i++){
  $arrayPerson[$i]->addMoney($arrayMoney[$i])
  //Or  $arrayPerson[$i]->Money += $arrayMoney[$i]
} //$i defines your index in the array.

sql
Better though to make a join in the SQL and sum the money and group by PersonID.
for example:
SELECT person.* COUNT(Money) FROM Person
LEFT JOIN Money
ON person.ID = Money.PersonID
GROUP BY person.ID

A: Simple foreach loop:
$people = array('Person1', 'Person1', 'Person2');
$values = array(100.00, 150.25, 157.15);

$output = array();
foreach ($people as $key => $person) {

    if (! isset($output[$person])) {
        $output[$person] = 0;
    }

    if (! empty($values[$key])) {
        $output[$person] += $values[$key];
    }
}

// $output = array(2) { ["Person1"]=> float(250.25) ["Person2"]=> float(157.15) }

If you want to do away with the keys in $output, you can use array_values($output)
Here's an example


text:
Q: Iterate over nested sublists and remove specific items I am a beginner in Python. Can someone help me figure out what is the problem in my code below in python 2.7:
I am trying to iterate through list and sublists recursively and delete AND, OR, NOT, IFF, IMPLIES in list.
My method :
def setOfSets(prop):
    if isinstance(prop, str):
        answer = prop
    else:
        for item in prop:
            if isinstance(item, str):
                if (item == IFF):
                    answer = prop.remove(item)
                if (item == IMPLIES):
                    answer = prop.remove(item)
                if (item == AND):
                    answer = prop.remove(item)
                if (item == OR):
                    answer = prop.remove(item)
                if (item == NOT):
                    answer = prop.remove(item)
            else:
                answer = setOfSets(item)

    return answer

prop0 = setOfSets(inputList)
print "Set of Sets:"
print prop0

Results :
Input : ['or', 'R', ['not', 'B'], 'W']
Expected output : ['R',['B'],'W']
Current output : None

I think I am making some silly mistake or using something wrong in python.

A: It's simpler to build a new list than to copy the old nested list and remove items from it.
Here's a slightly improved version, with more test cases:
#!/usr/bin/env python

OPNAMES = set(('IFF', 'IMPLIES', 'AND', 'OR', 'NOT'))

def setOfSets(prop):
    answer = []
    for item in prop:
        if isinstance(item, str):
            if item.upper() not in OPNAMES:
                answer.append(item)
        else:
            answer.append(setOfSets(item))

    return answer

def test(prop):
    print prop
    print setOfSets(prop)
    print

props = [
    ['A', 'B', 'C'],
    ['or', 'R', ['not', 'B'], 'W'],
    ['or', 'R', ['not', 'B'], [['IMPLIES', 'Q'], 'W'], 'Z'],
    [['A', 'AND', ['B', 'OR', ['NOT', 'C']], 'IFF', 'D'],'IMPLIES', 'Z'],
]

for prop in props:
    test(prop)

output
['A', 'B', 'C']
['A', 'B', 'C']

['or', 'R', ['not', 'B'], 'W']
['R', ['B'], 'W']

['or', 'R', ['not', 'B'], [['IMPLIES', 'Q'], 'W'], 'Z']
['R', ['B'], [['Q'], 'W'], 'Z']

[['A', 'AND', ['B', 'OR', ['NOT', 'C']], 'IFF', 'D'], 'IMPLIES', 'Z']
[['A', ['B', ['C']], 'D'], 'Z']


text:
Q: Icons not showing in createBottomTabNavigator in react native Icons not showing in createBottomTabNavigator in react native. I guess icons are not rendering. I tried the following code. Getting the following result after executing the code. Try to use the https://oblador.github.io/react-native-vector-icons icons in the code but none of the icons is set properly.

import React from 'react';
import { Text, View } from 'react-native';
import { createBottomTabNavigator, createAppContainer } from 'react-navigation';
import Icon from 'react-native-vector-icons/Ionicons';

class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Home!</Text>
      </View>
    );
  }
}

const TabNavigator = createBottomTabNavigator({
  Home: {
    screen:HomeScreen,
    navigationOptions: {
      tabBarIcon: ({ focused, tintColor })=> <Icon name="ios-mail" color={tintColor} size={14}/>
    },
  },
  tabBarOptions: {
    showLabel: false,
    activeTintColor: '#0a0a0a',
    style: {
      backgroundColor: '#f7f7f7',
      height: 30,
      borderTopWidth: 1,
      borderTopColor: 'red'
    }
  }
});

export default createAppContainer(TabNavigator);

A: run this command again yarn react-native run-android
This works fine with my project

A: Open your_react_native_project->android -> app -> build.gradle file and put below code of at the end of the file.
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
And put the below code inside the dependency block.
implementation project(':react-native-vector-icons')

This works fine with my project.


text:
Q: Fatal signal 11 when using SIFT detector from opencv4android I try to use the SIFT Feature detector from Opencv4Android
My code is the following
       public void onManagerConnected(int status) {
        switch (status) {
        case LoaderCallbackInterface.SUCCESS:
            {

   fileimage = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Pictures/263.jpg");

 image=Highgui.imread(fileimage.getAbsolutePath(),Highgui.CV_LOAD_IMAGE_COLOR);

    FeatureDetector fd = null ;

    fd= FeatureDetector.create(FeatureDetector.SIFT);

    MatOfKeyPoint keypoints= new MatOfKeyPoint();

    fd.detect(image, keypoints);

My log file is the following
       -24 09:40:19.636: A/libc(12695): Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0  in tid 12695 (mples.tutorial2)


text:
Q: Studies with small sample sizes I'm asking myself the question of why studies with small sample sizes are not as convincing as those with larger sample sizes, and when this becomes a statistical issue. A complaint I've heard a lot with studies is while they show a certain "desired" result (e.g. the treatment group had lower cholesterol than the placebo group), the sample size was small.
Statistically, if you have the sample size to detect an effect, then the sample size was large enough in that sense. So at that point, on what grounds could you claim a higher sample size would be better? To get more exact confidence intervals if they are asymptotic?
Personally I would feel more convinced with a sample of 1000 rather than 500, but I can't identify technically where this makes a difference aside from precision.

A: Let's use reductio ad absurdum to see how the "if you have the sample size to detect an effect, then the sample size was large enough in that sense" logic doesn't hold. Imagine that you had a sample of size $N=1$. In such a sample, you can either observe a result that confirms or disagrees with your hypothesis. Unless you can make a strong hypothesis like "it should never happen" (but then, you don't need statistics, just logical reasoning), there will always be some chance to observe either of the results, even if unlikely. In such a case, your single sample does not "prove" anything, as it could be pure luck. However, if you repeated the experiment many times and saw the same result repeated, it gets less likely that it was luck.

A: In frequentist statistics this is a matter of $\alpha$ (significance level) and $1-\beta$ (power) of a hypothesis test. Usually you would fix $\beta$ (for ex. $80 \%$) and then determine the number of samples required to obtain such power for a desired $\alpha$ (for ex. $0.05$).
A specific example: power analysis for a simple t-test given $d = 1$, $1-\beta=0.8$, and $\alpha=0.05$ returns a required sample size of $n \approx 17$. Increasing $1-\beta=0.9$ yields $n \approx 22$. The significance level has stayed the same in both cases, i.e. the CI obtained from such tests will cover the true values with the same proportions, what has changed is the power, the second test has more power than the first (and narrower CI's).

A: A comment made by "Josh" under this Andrew Gelman's blog post:
https://statmodeling.stat.columbia.edu/2022/01/24/how-large-a-sample-size-does-he-actually-need-he-got-statistical-significance-twice-isnt-that-enough/
helped me (finally!) understand this issue. I copied the comment here, hope that's OK:
"Let's say we take 100 samples under the null distribution and 100 samples under the alternative distribution. We expect ~5 samples under the null to be significant. If we have power of 80 percent, we'd expect ~80 significant results under the alternative. Here only 5/85 of our results are false positives.
However, what if we have statistical power of only 10 percent. Then we expect ~10 samples under the alternative to be significant. Here 5/15 of our significant results would be false positives.
Decreasing power increases the likelihood that we are in situation one (significant result with the null) rather than in situation two (significant result with the alternative)."


text:
Q: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $ AND Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $ I was doing every post method of my app using this method:
1-This is the interface where I do my get and post methods:
@POST("feedback/challenge/newRating")
Call<IncreasedChallengeFeedback> challengeFeedbackIncreaseRating(@Body IncreasedChallengeFeedback increasedFeedbackChallenge);

2- the method to do the call
public void increaseRatingCFb(IncreasedChallengeFeedback increasedChallengeFeedback) {

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://10.0.2.2:3000/")
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    api = retrofit.create(INodeJS.class);

    Call<IncreasedChallengeFeedback> call = api.challengeFeedbackIncreaseRating(increasedChallengeFeedback);
    call.enqueue(new Callback<IncreasedChallengeFeedback>() {
        @Override
        public void onResponse(Call<IncreasedChallengeFeedback> call, Response<IncreasedChallengeFeedback> response) {
            if (!response.isSuccessful()) {
                System.out.println("!= Successful" + response.code());
                return;
            }
        }

        @Override
        public void onFailure(Call<IncreasedChallengeFeedback> call, Throwable t) {
            System.out.println("OnFailure: " + t.getMessage());
        }
    });
}

3- Here I just create an object of the class to use with the method
holder.likeButton.setOnLikeListener(new OnLikeListener() {
        @Override
        public void liked(LikeButton likeButton) {

         IncreasedChallengeFeedback icfb = new IncreasedChallengeFeedback("8","2");
         increaseRatingCFb(icfb);

        }

4- And finally here its the class
public class IncreasedChallengeFeedback {

private String cFeedbackRating;
private String cFeedbackID;

public IncreasedChallengeFeedback(String cFeedbackRating, String cFeedbackID) {
    this.cFeedbackRating = cFeedbackRating;
    this.cFeedbackID = cFeedbackID;
}

}
And with this I am getting this errors:

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

So I added this:
Gson gson = new GsonBuilder()
            .setLenient()
            .create();

And then the error changes to this:

Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

The thing is that  I did all my other posts and get methods using that method and then suddenly I'm stuck with this errors.

A: Your JSON object is most likely malformed. Print the JSON object you receive to see if it's malformed in any way. The same question was asked here, so check for more info: https://stackoverflow.com/a/28418787/13709773


text:
Q: Несколько spl_autoload_register(); Вообщем у меня несколько
spl_autoload_register();

Беда в том, что оба они не работают, в чем может быть загвоздка?
Один подгружает классы из ядра, второй загружает классы шаблонизатора.
Но всегда срабатывает тот который находится первым. Как лечить?
A:
Но всегда срабатывает тот который находится первым.

Всегда срабатывает весь стек загрузчиков по порядку, переход к следующему осуществляется до тех пор, пока класс не найден и не загружен (а что, могли быть варианты?)

Как лечить?

Каждый автозагрузчик должен уметь не нервничать и спокйно реагировать на отсутствие файла, в котором может быть класс. В этом случае управление просто перейдет к следующему загрузчику, ответственность текущего кончается, и за остальное он беспокоиться не должен. Впрочем, использование PSR-0/PSR-4 настолько же спокойно унифицирует загрузчик и позволяет иметь всего один загрузчик в системе, а если предоставить эту задачу composer, то можно решить проблемы с автозагрузкой даже для пакетов, которые ничего не знают про PSR.


text:
Q: Как в C# из внутреннего класса ссылаться на нестатические поля внешнего class Outer {
    int x = 1;

    class Inner {
        void Method() {
            Console.WriteLine(x);
            }
    }

}

Если проводить аналогию с Java, то в Java это возможно. Пример из Java
class Outer {
    int x = 1;

    class Inner {
        void Method() {
            System.out.println(Outer.this.x);
            }
    }

}


text:
Q: Не компилируется фрагментный шейдер Есть два вот таких шейдера:

 // Vertex shader program
 var VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' +
  'attribute vec4 a_Color;\n' +
  'varying vec4 v_Color;\n' + // varying variable
  'void main() {\n' +
  '  gl_Position = a_Position;\n' +
  '  gl_PointSize = 10.0;\n' +
  '  v_Color = a_Color;\n' +  // Pass the data to the fragment shader
  '}\n';

// Fragment shader program
var FSHADER_SOURCE =
  '#ifdef GL_ES\n' +
  'precision mediump float;\n' + // Precision qualifier (See Chapter 6)
  '#endif GL_ES\n' +
  'varying vec4 v_Color;\n' +    // Receive the data from the vertex shader
  'void main() {\n' +
  '  gl_FragColor = v_Color;\n' +
  '}\n';

Компилируются функцией: gl.getShaderParameter(shader, gl.COMPILE_STATUS);
Вершинный шейдер собирается без проблем, а фрагментный нет. В консоль падает вот это: Failed to compile shader: ERROR: 0:3: 'GL_ES' : unexpected token after conditional expression
Код чужой и мне не понятны вот эти строки:

'#ifdef GL_ES\n' +
'precision mediump float;\n' +
'#endif GL_ES\n' +

Сначала я грешил на видеокарту но она ни причем. Этот код взят из исходников книги и в сети никто не отзывался плохо об нем.
Помогите найти причину ошибки.

A: Попробуйте изменить строки на:
'#ifdef GL_ES\n' +
'precision mediump float;\n' +
'#endif\n' +

Эти строки переключают точность вычислений на среднюю для WebGL, так как, похоже, не все устройства поддерживают высокую точность аппаратно, а те, что поддерживают, всё равно работают медленнее.


text:
Q: ngx-slick-carousel with clickable image doesn't consistently allow click event I am facing a problem using ngx-slick-carousel. I am using a slick carousel with href link.
<ngx-slick-carousel class="carousel"
    #slickModal="slick-carousel"
    [config]="slideConfig" >

     <div ngxSlickItem *ngFor="let slide of slides | async" class="slide shadow centerImage">
          <a (click)="launchpopup()" href="javascript:void(0);">

          <img src="<<Some link>>">

           </a>
       </div>

</ngx-slick-carousel>

*

*It loads well.

*When the carousel starts lets say image 1 on the left slides and
goes to left which is outside the max slides and so it hides, when
image 1 comes back on the right side, the click doesn't work  at
all..only when image 1 goes to its original position it starts to
work. Same for other images.

Has anyone faced this problem?
Note:- The same problem appears with owl-carousel


text:
Q: How to stop angular-material components overlapping my sticky navbar? I have created a navbar using normal CSS3. But some of the components like input fields and buttons are created using angular material.
Here my navbar is sticky. But components created using angular material are overlapping my navbar.
navbar css is:
position: sticky;
top: 0;

A: Set the z-index of your navbar to a greater value in your css.
Example: z-index: 10


text:
Q: How to get worksheet and cell that the current VBA function is returning to? Is there a variable anywhere that gives the worksheet and cell that will recieve the result of a custom VBA function?
For example, if in A!B1 the formula is =MyCustomFunc() in my code:
public function MyCustomFunc()
    'what can I call here to get the values "A" and "B1"?
end function

A: Is this what you are trying?
Option Explicit

Public Function MyCustomFunc()
    '~~> Judicious use of 'Volatile' is advised.
    '~~> This will be called everytime the sheet is recalculated
    Application.Volatile

    MsgBox Application.Caller.Parent.Name & ", " & Application.Caller.Address
End Function

A: You want Application.ThisCell.
This returns the cell which is currently being calculated.

A: ActiveSheet.Name will give you sheet name. ActiveCell.Row will give you row number and ActiveCell.Column will give you column letter. Then you can combine them to get cell address.


text:
Q: setting style after getting highest column and Row Is it possible to set style of each row dynamically after getting the highest column and highest Row ?
I tried
$highCol = $objPHPExcel->setActiveSheetIndex()->getHighestDataColumn();
$highRow = $objPHPExcel->setActiveSheetIndex()->getHighestDataRow();
$val ="'A6:" . $highCol .$highRow . "'";
$objPHPExcel->getActiveSheet()->getStyle($val)->applyFromArray($styleArray);

My PHP CGI crashes.

A: A major problem is the spurious quotes in your $val variable
Try changing
$val ="'A6:" . $highCol .$highRow . "'";

to
$val ="A6:" . $highCol .$highRow;


text:
Q: Wordpress query returning posts with very old date when querying for future events I'm doing a wordpress query for future events based on the date code stored in a meta value. I'm getting the future events as expected but some very old events from the 1990s are being returned in the query after the future events. Is there any way around this?
$today = time();

$futureloop = new WP_Query( array(
'post_type' => 'exhibitions',
'post_status' => 'publish',
'posts_per_page' => '100',
'meta_query' => array(
 array(
  'key' => 'exhibition_date',
  'compare' => '>=',
  'value' => $today,
 )
),
'meta_key' => 'exhibition_date',
'orderby' => 'meta_value',
'order' => 'ASC'
) );
while ( $futureloop->have_posts() ) : $futureloop->the_post();

For example I have one event that occurred in April 1990 that is showing up.
When I echo $today and the date of the event this is the result:
639273600 $exhibiton_date
1559283337 $today

A: It seems exhibition_date is DATETIME type. So you should try meta_query as below.
$today= date('Y-m-d H:i:s');

'meta_query' => array(
 array(
  'key' => 'exhibition_date',
  'value' => $today,
  'compare' => '<=',
  'type'      => 'DATETIME',
 )
),

Hope it will work for you.
Class Reference/WP Meta Query


text:
Q: Java - Compress large string In my Java application I get from some calculations a really long string (from really long string I mean of around 600000 characters or so).
But I need to send this string to a client to process it, and for this reason I need the compressed string to be of maximum 1000 characters.
I have tried using GZIPOutputStream and Inflater and Deflater classes, and in the best case I got an output string of 300000 characters, which is great compression, but in my case it's not enough.
I have also tried compressing the string n times, but the ouput was larger than the previous one, so only one-time compressing was successful.
So, what do you suggest me to try?
Thank you.

A: I agree with @Peter Lawrey that, strictly with those requirements, it might be impossible to deliver such a big message to the client.
Anyway, I still suggest three possible solutions, depending on how flexible your requirements are:

*

*If all of your input strings have a restricted vocabulary (it does not allow a free, random combination of letters, symbols and numbers, but it is restricted to a certain set of business words, identifiers and values), and also a simple grammar, you can try to design your own compress algorithm. Example:

    input symbol          compressed symbol
    ------------          -----------------
    client                1
    bill                  2
    date                  3
    amount                4
    value                 5
    price                 6
    tax                   7

If the grammar is simple but the vocabulary is not that restricted, you could perform an initial custom compression to compress the document's structure as much as you can, and then a second GZIP compression to compress the data.
And don't forget that you'll have to bundle the client application with the corresponding uncompressor.
Anyway, it's not an easy task, I admit it.

*Deliver the response to the client application in streaming. If the protocol is HTTP, you could use Chunked Transfer Coding.

*If everything else fails, you'll have to page the results and serve them to the client by pages on demand: The client makes a query, the server executes it and delivers just the first page of results. Then, the client may chose to read the next page.


text:
Q: How to detect running app from JWrapper bundle and pass commandline arguments to it We have recently decided to move our application deployment over to JWrapper and have started dealing with the smaller changes required to implement all the features for our tool. In particular, we have a custom protocol that we handle using the protocol registration in JWrapper. We do this in a separate (non-user runnable) virtual app. When it gets the arguments it must decide either to hand them off to a currently running instance of our main virtual app or spawn a new instance of the main app with the command line arguments set (we achieve this using JWSystem.forkVirtualApp(...)).
We see mentioned on the URL Handling FAQ page from JWrapper here that only MacOS is able to register an event handler to respond to URL openings and that there is a suggestion for windows...

On Windows this isn't possible directly since Windows doesn't support it however a dedicated URL-handling virtual app which then communicated the URLs to your main app would achieve the same result.

My question is; how exactly do we get a hold of our running main virtual app and how do we pass it some arguments? Is there a particular approach that we should use?

A: You might be able to do some of this with JWrapper's IPC (Inter-Process Communication) capabilities. Here is an old article talking about some of this: http://www.jwrapper.com/blog/aes-encrypted-multiplexed-inter-process-communication-for-java
Here is is a javadoc for the class that covers IPC in JWrapper: http://simple-help.com/media/static/jwrapper/jwutils/JWSockIPC.html
You could also coordinate by watching a particular file as a means of communicating between your virtual apps.


text:
Q: QtQuick drawing shapes and colors but not text I've just tried running my qtquick2 application, my application opens successfully but no text is drawn.

A: Fonts are probably missing on your target.
You can add them to your layer by appending IMAGE_INSTALL_append with  ttf-dejavu-sans, ttf-ubuntu-mono, ttf-ubuntu-sans or any other font.


text:
Q: Running 2 threads and Displaying Best Result I'm working on a Travelling Salesman Solver, I'm trying to make it execute in two threads and return the path drawing(Jframe) and the path distance/output of the best search.
My Code is below:
  Executer myRunnable = new Executer();
    Thread t = new Thread(myRunnable);
    t.start();
    t.join();
    int tdist=(Executer.returnPathValue());
    int []comparet = returnSearchedPath();

    Thread t1 = new Thread(myRunnable);
    t1.start();
    t1.join();

    int t1dist=(Executer.returnPathValue());
    int []comparet2 = returnSearchedPath();

    if(tdist<t1dist){
        printPath(comparet);
        System.out.println(tdist);
    }
    else{
        printPath(comparet2);
        System.out.println(t1dist);
    }

The output from this is
SEARCH COMMENCING:
32 10 51 13 12 26 24 23 47 45 15 49 19 29 28 46 25 27 11 50 3 43 22 20 41 1 6 16 2 17 30 21 0 48 31 44 18 40 7 8 9 14 5 4 37 36 33 34 35 38 39 42 32->dist 8904

My only problem NOW is accomplishing the same result without using .join() and let the threads run at the same time. Any ideas?

A: Basically, you are needing an ArrayList of your threads and a variable to hold the current best path. In the thread class, you need two Synchronized methods. Synchronized methods are ones that are thread-safe. This means that if you have multiple threads running you can change data in another thread safely. If you want to read more about how that works you can go to this link here. You will need one method to update the current best route if the route the thread found is less than the current best and you will need one function to remove itself from the ArrayList in the main thread when it is finished. This means you would have a blocking while loop in the main thread that looks something like this:
//Where threads is the ArrayList of all of your threads
while(!threads.isempty()){
    //Wait here
}

Then after that while ends you can check the current best path variable and that should be the best one. Now you do not have to wait for it to break out of the while loop to update the JFrame. You can change the JFrame when the current best does not match what the current JFrame is showing inside the while loop but once you get out you should double check that the correct one is being shown. Exiting means all threads are done so the final answer would be whatever is left in the current best path.

A:
Do I HAVE to wait for both of them to complete basically I want to accomplish the same result I have without using .join

I think I understand.  There are techniques where you can get output from a thread without waiting on it specifically.  The basic technique is a producer-consumer pattern.
https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem
Here's a simple way to do this in Java.  First, make a global thread-safe queue.
public class Global {

  public static final ConcurrentLinkedQueue outputQueue = new ConcurrentLinkedQueue();

}

Then pass this queue in to any thread you want.  Use this queue to save output from that thread.
public class MyTask implements Runnable {

  private final Queue output;

  /** 'q' must be thread safe */
  public MyTask( Queue q ) {
    output = q;
  }

  @Override
  public void run() {

    // do stuff

    int [] path = ...
    output.add( path );
  }

}

Now you can just read the queue to get output, or decide not to read it.  You can also dedicate one thread to output and let the main thread do other things.  (This is what is typically done in a producer-consumer problem.)  You can also produce output but not finish, and continue producing results and add them to the queue as you are able to calculate them.  This works well for progressive type problems.
This code wasn't tested, and sorry for using raw types, it's just a quick example.


text:
Q: Pandas - Counting quantity of commas in character field I have a pandas dataframe with a column filled with strings as is shown below:
   string_column
0  t,d,t,d,v,d
1  s,v,y,d
2  d,u,f

I would like to create a new column with the count of commas in the string column. My intended outcome is below:
   string_column  comma_count
0  t,d,t,d,v,d    5
1  s,v,y,d        3
2  d,u,f          2

Is there a string reading method to pandas that will accomplish this task?
Thanks

A: use str.count
df.assign(comma_count=df.string_column.str.count(','))

  string_column  comma_count
0   t,d,t,d,v,d            5
1       s,v,y,d            3
2         d,u,f            2

A: Use str.count:
df['comma_count'] = df.string_column.str.count(',')
print (df)
  string_column  comma_count
0   t,d,t,d,v,d            5
1       s,v,y,d            3
2         d,u,f            2


text:
Q: How to correctly unit test yargs in typescript There are 2 points that I need to be explained
- How to reset yargs without using deprecated .reset() method; (.global() method instead, but how ??)
- how do I pass in the command line to yargs as typed in by the user
Given the following test:
import * as yargs from 'yargs';
describe.only('how to write a unit test for yargs with typescript', () => {
  beforeEach(() => {
    yargs.reset(); // No, but how do we get a new yargs instance?
  });
  it('yargs', () => {
    const usernameOption = {
      alias: 'username',
      describe: 'website username'
    };
    // (['login', '-u', 'jimmy']) => where does this go, without causing a build error
    // TS2349: This expression is not callable
    //
    yargs.command('login', 'login to website', (y: yargs.Argv): yargs.Argv => {
      return y.option('u', usernameOption);
    });
    console.log(`>>> ${JSON.stringify(yargs.argv)}`);

    // the above outputs:
    // >>> result: {"_":[],"$0":"/Users/Plastikfan/dev/github/js/aergia-cli-ts/node_modules/.bin/mocha"}
    //
    // how to reset yargs without using deprecated .reset() method?
    // => .global() ?
    //
  });
});

if I try to pass in the command line into yargs:
    yargs(['login', '-u', 'jimmy']).command('login', 'login to website', (y: yargs.Argv): yargs.Argv => {
      return y.option('u', usernameOption);
    });

I see the following error 'TS2349: This expression is not callable':

ERROR in
  /Users/Plastikfan/dev/github/js/aergia-cli-ts/tests/yargs/yargs-builder.impl.spec.ts
  ./tests/yargs/yargs-builder.impl.spec.ts [tsl] ERROR in
  /Users/Plastikfan/dev/github/js/aergia-cli-ts/tests/yargs/yargs-builder.impl.spec.ts(89,5)
        TS2349: This expression is not callable.   Type '{ default: Argv<{}>; alias(shortName: K1,
  longName: K2 | readonly K2[]): Argv<{ [key in K2]: {}[K1]; }>;
  alias(shortName: K2, longName: K1
  | readonly K1[]): Argv<...>; alias(shortName: string | readonly
  string[], longName: string | readonly st...' has no call signatures.

I've been scanning around for other yargs unit tests and I found these tests in yargs: yargs completion tests
in particular:
yargs(['./completion', '--get-yargs-completions', 'apple'])

ie yargs is invoked (), but this is where I get the error when I try it in a typescript test. Note that the example quoted is a javascript test, and it also uses the deprecated .reset() function inside beforeEach.
I originally had "esModuleInterop": true, in tsconfig, but setting this to false made no difference.


text:
Q: Replacing specific character to lowercase using xsl Hi i have an xml as below.
<setField identifier="2">
      <fieldValues>
       <fieldValue>
        <field>event</field>
        <value>
         <boundVariable>$event1</boundVariable>
        </value>
        <type>java.lang.String</type>
       </fieldValue>
      </fieldValues>
      <variable>append</variable>
     </setField>

I need to convert to the following format.
<freeForm><text>append.setEvent($event1);</freeForm></text>

I am trying the following approach.
   <xsl:template match="setField" name="setFieldTemplate">
   <xsl:element name="freeForm">
   <xsl:element name="text">
   <xsl:value-of select="variable" />
   <xsl:text>.set</xsl:text>
   <xsl:value-of select="concat(translate(substring(field, 1, 1)"/>
   <xsl:text>(</xsl:text>
   <xsl:value-of select="boundVariable"/>
   <xsl:text>);</xsl:text>
   </xsl:element>
   </xsl:element>
   </xsl:template>

Here my requirment is based on the field name i need to generate corresponding statement as below.For that i need to change the first character of the field name to upper while generating to the following format.
append.setEvent($event1);
Here the field name is "event" and i need to generate setEvent(for which i am concatinating with the string "set").But i need to change the fieldname's first letter to upper one(Event from event).when i try with the above template with translate function i am facing some invalid xpath expression.
Please provide me some pointers to do the same.

A: You want:
            <xsl:value-of select="concat(
                translate(substring(//field, 1, 1),
                'abcdefghijklmnstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ'),
                substring(//field, 2))"/>

Also you might prefer:
<xsl:template match="setField">
    <freeForm>
        <text>
            <xsl:value-of select="variable" />
            <xsl:text>.set</xsl:text>
            <xsl:value-of select="concat(
                translate(
                 substring(fieldValues/fieldValue/field, 1, 1),
                 'abcdefghijklmnstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ'),
                substring(fieldValues/fieldValue/field, 2),
                '(',fieldValues/fieldValue/value/boundVariable,');')"/>
        </text>
    </freeForm>
</xsl:template>

A: <xsl:value-of select="concat(
                variable,
                '.set',
                translate(substring(//field, 1, 1), 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'),
                substring(//field, 2),
                '(',
                //boundVariable,
                ');'
                )"/>


text:
Q: How can i join pairs of records in a single table sorted chronologically (using MySQL) I would like to know if there is an easy way to join pairs of records in a single table to form one table. For example:
ID, TYPE, TIME
1, A, 01:00:00
2, B, 02:00:00
3, A, 03:00:00
4, B, 04:00:00
5, A, 05:00:00
what i would like to retreive is a single table listing the pairs (A/B) like so.
ID, TYPE, TIME, ID, TYPE, TIME
1, A, 01:00:00, 2, B, 02:00:00
3, A, 03:00:00, 4, B, 04:00:00
5, A, 05:00:00,NULL,NULL,NULL
The B record should be the next one after A, and if there is no B then just return NULL. The table shall be sorted chronigically.
TIA

A: funny question, hope this work for you
select tbl_a.*, tbl_b.*
from
  your_table as tbl_a
left join
  your_table as tbl_b
on
  tbl_a.ID=tbl_b.ID-1
where tbl_a.ID%2=1       <-- get ID mod 2=1
order by tbl_a.ID;

A: Thanks ajreal, it helped me find the answer:
SELECT T.ID,T.Type,T.Time,T2.ID,T2.Type,T2.Time FROM Table T LEFT JOIN Table T2
ON (T.Type = 'A' AND T2.Type = 'B' AND T.Time < T2.Time)
WHERE T2.ID IS NOT NULL
GROUP BY T.ID


text:
Q: Does $\ln$ belong to the field of Hahn series or not? Consider the field of Hahn series (see e.g. https://en.wikipedia.org/wiki/Hahn_series )$$K[[T^{\mathbb{Q}}]]=\left\{\sum_{q\in\Bbb{Q}} a_q T^q: a_q\in K,\text{supp}(a_q)\text{ is well ordered} \right\}$$
($\text{supp}(a_q)=\{q\in\Bbb{Q}:a_q\ne0\}$)with usual addition and multiplication:
$$\sum_{q\in\Bbb{Q}}a_q T^q+\sum_{q\in\Bbb{Q}} b_q T^q=\sum_{q\in\Bbb{Q}} (a_q+b_q) T^n$$
and $$\left(\sum_{q\in\Bbb{Q}} a_q T^q \right)\left(\sum_{q\in\Bbb{Q}} a_q T^q\right)=\sum_{q\in\Bbb{Q}} \sum_{q_1+q_2=q} a_{q_1}b_{q_2} T^q$$
and with the norm
$$\left\|\sum_{q} a_q T^q \right\|=\rho^{\min\{q\;:\;a_q\ne 0\}}$$
where $0<\rho<1$.
I conclude that the series $$\ln(T)=\sum_{n=1}^\infty \frac{(-1)^{n+1}}{n}(T-1)^n$$
does not belong to $K[[T^{\mathbb{Q}}]]$, because, while the sequence
$$x_n=\sum_{m=1}^n \frac{(-1)^{m+1}}{m}(T-1)^m$$
is a sequence in $K[[T^{\Bbb{Q}}]]$, but it is not Cauchy sequence, therefore from this strategy, we can't conclude that $\ln$ belongs to $K[[T^{\Bbb{Q}}]]$ or not.
And I stack here.
Please help me to figure out if $\ln$ belongs to $K[[T^{\Bbb{Q}]]$ or not.
Thanks.


text:
Q: Command executed differently from terminal or in bash script I'm trying to automate a backup script with attic, but I'm stuck on this issue: the actual attic command performs differently when executed from the script and when executed directly in the terminal.
The script builds and executes the command:
/usr/bin/attic create --stats --verbose --exclude '/home/.cache' /media/attic-backup/paolo.attic::2016-08-27 /home

the command outputs the files backuped up from attic:
/home
/home/.attic
/home/.attic/keys
/home/.cache
/home/git
/home/git/.bash_history
etc etc

The /home/.cache directory should have been skipped...
However, if I execute the same command from the terminal I get:
$ /usr/bin/attic create --stats --verbose --exclude '/home/.cache' /media/attic-backup/paolo.attic::2016-08-27 /home
/home
/home/.attic
/home/.attic/keys
/home/git
/home/git/.bash_history
etc etc

Now the /home/.cache directory has been skipped.
It's not a matter of sudo.
Why the command in the script behaves differently?

A: When you say the script "builds" the command, do you mean it stores it in a string (variable), and then tries to execute the string as a command? If so, putting quotes inside the string ('/home/.cache') won't do what you expect, because the quotes are treated as data and passed to the command as part of the argument, rather than being parsed and removed before it's passed as an argument. Essentially, this means that rsync was being told to exclude '/home/.cache' rather than just /home/.cache. See BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail! for more info.
If you're trying to build the command piece-by-piece, usually the best way to do it is with an array. Something like this:
atticcmd=(/usr/bin/attic create --stats --verbose --exclude '/home/.cache' /media/attic-backup/paolo.attic::2016-08-27 /home)
"${atticcmd[@]}"

Or you can build only a part of it in an array:
atticopts=(--stats --verbose)
for e in "${excludes[@]}"; do
    atticopts+=(--exclude "$e")
done
/usr/bin/attic create "${atticopts[@]}" /media/attic-backup/paolo.attic::2016-08-27 /home


text:
Q: Removing the timestamp from a datetime in pandas dataframe Scenario: I have a dataframe with multiple columns retrieved from excel worksheets. Some of these columns are dates where some values are dates (yyyy:mm:dd) and some are datetimes (yyyy:mm:dd 00.00.000000).
Question: How can I remove the time stamp from the dates when they are not the index of my dataframe?
What I already tried: From other posts here in SO (working with dates in pandas - remove unseen characters in datetime and convert to string and How to strip a pandas datetime of date, hours and seconds) I found:
pd.DatetimeIndex(dfST['timestamp']).date

and
strfitme (df['timestamp'].apply(lambda x: x.strftime('%Y-%m-%d'))

But I can't seem to find a way to use those directly on the wanted column when it is not the index of my dataframe.

A: You can do the following:
dfST['timestamp'] = pd.to_datetime(dfST['timestamp'])

to_datetime() will infer the formatting of the date column. You can also pass errors='coerce' if the column contains non-date values.
After completing the above, you'll be able to create a new column containing only date values:
dfST['new_date_column'] = dfST['timestamp'].dt.date

A: You can also use dt.normalize() to convert times to midnight (null times don't render) or dt.floor to floor the frequency to daily:
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['timestamp'] = df['timestamp'].dt.normalize()

df['timestamp'] = df['timestamp'].dt.floor('D')

Note that this keeps the dtype of the column datetime64[ns] because each element is still of type pd.Timestamp, whereas dt.date suggested in Andrew L's post converts it to object because each element becomes type datetime.date.

Also, it's worth noting that dt.normalize and dt.floor('D') are both significantly faster (approx. 10 times faster for longer dataframes) than dt.date:

Code used to produce the timings plot:
from perfplot import plot
plot(
    setup=lambda n: pd.Series([pd.Timestamp('now')]*n),
    kernels=[lambda s: s.dt.date, lambda s: s.dt.normalize(), lambda s: s.dt.floor('D')],
    labels= ["col.dt.date", "col.dt.normalize()", "col.dt.floor('D')"],
    n_range=[2**k for k in range(21)],
    xlabel='Length of column',
    title='Removing Time From Datetime',
    equality_check=lambda x,y: all(x.eq(y)));


text:
Q: PHP: Search MYSQL database between datetime but use the date only? I have a column in MYSQL that stores the datetime like so:
2017-08-18 08:59:53
2017-08-18 07:59:00

I can search the database and return the results between the datetime column like so:
$from = date("Y-m-d H:i:s", strtotime($_GET['from']));
$to = date("Y-m-d H:i:s", strtotime($_GET['to']));

$sql1="SELECT * FROM `Table` WHERE mydate>='$to' and mydate<='$from'";

This works fine as long as I search like this:
2017-08-18 08:59:53

But what I need to be able to do is to search like this:
2017-08-18

and still get the same result when I search.
I don't want to use the time in my search string/query.

A: Try mysql date() function like:
$sql1="SELECT * FROM `Table` WHERE date(mydate)>='$to' and date(mydate)<='$from'";

mysql date() function returns only date part from datetime column in default Y-m-d format.

A: You are very close. If you want to search a DATETIME or other datestamp column for matches to a particular day, do this:
WHERE mydate >= DATE(whatever_first_day)
  AND mydate  < DATE(whatever_last_day) + INTERVAL 1 DAY

This searches for everything on the date mentioned in whatever_first_day, starting with midnight on that date, and everything up to, but not including (<), midnight on the day after whatever_last_day.
This way of searching is sargable: it can use an index on the mydate column.
You could also use
 WHERE DATE(mydate) >= DATE(whatever_first_day)
   AND DATE(mydate) <= DATE(whatever_last_day)

but that is not sargable.

A: "SELECT * FROM `Table` WHERE date_format(mydate,"%Y-%m-%d")>='$to' and date_format(mydate,"%Y-%m-%d")<='$from'";


text:
Q: Time Scale Calculus/Dynamic Equations on Time Scales Studying the mathematics of dynamic phenomena seems to branch out in an overwhelming number of directions.  There are univariate and multivariate varieties, continuous and discrete varieties, deterministic and stochastic varieties, and perhaps more distinctions, from which each combination seems to lead to its own field of theory.  As someone self studying math who has the experience of a first course in ODEs, is most of the way through what would be a first course in PDEs, and has occasionally glanced into the field of difference equations, with an eye toward stochastic and financial applications, I am wondering if my further studies might benefit from learning some Time Scale Calculus or Dynamic Equations on Time Scales.
The most basic ideas of the subject don't seem too hard to grasp, but a lot of literature seems orientated toward a "purer" proof-ridden sort of math, borderline graduate-level or researcher-grade material.  My interest is more in the camp of computation/conceptual understanding.  Is it reasonable to study dynamic phenomena as Dynamic Equations on Time Scales in order to eliminate the need to learn continuous and discrete subjects individually, or is it important to understand the underlying math continuously and discretely before generalizing it?  If I learn a few key topics in Time Scale Calculus, can I use the subject to understand what solution methods for continuous problems will port over to discrete problems and vice-versa, i.e., can I solve problems as a "function of time scale" and then plug in whatever time scale I need at the end to arrive at correct results?

A: *

*Is it reasonable to study dynamic phenomena as Dynamic Equations on Time Scales in order to eliminate the need to learn continuous and discrete subjects individually, or is it important to understand the underlying math continuously and discretely before generalizing it?
It is essential to understand calculus in continuous cases. Time scale is a generalization, but you cannot understand it unless you learn continuous calculus.
2.If I learn a few key topics in Time Scale Calculus, can I use the subject to understand what solution methods for continuous problems will port over to discrete problems and vice-versa, i.e., can I solve problems as a "function of time scale" and then plug in whatever time scale I need at the end to arrive at correct results?
The answer depends on a problem sometimes; it may become complicated; for example, consider the definition of an exponential function. For $T=\mathbb{R}$, if you try to calculate exponential in the time scale set up, it will be complicated.


text:
Q: Adjusting the rise and fall time of a gate driver I have a hard time understanding the specifications of the UCC27511A-Q1 gate driver.

I understand that for a period of 0.5 μs (2 MHz) it can supply a source current of 4 A and a sink current of 8 A.
The internal resistance specified is:

In my particular project I need Vgs = 12 V to activate the FET and I want to adjust the rise and fall time of the switching, and there is the problem that I do not understand.

In the datasheet, does the CLoad emulate the parasitic capacitance that is usually found in FET datasheets as Q gate charge?
If so, if my understanding is correct for 0.5 μs I have 4 A that results in 2 μC.
I calculated the power needed for Cload as specified in the datasheet, but I have a hard time understanding how to adjust my resistances for custom rise and fall times.

I would really appreciate an example.

A: Most gate drivers including the one you are asking about should be considered as a voltage source rather than a current source. If you look at the output stage of the driver you can see that the output to the gate is either connected to GND or VDD using transistors inside the driver IC:

This particular driver is a bit special because it has two pull-up transistors. The NFET is just briefly turned on during the switching time to decrease the pull-up resistance to approximately 1 Ohm. The rest of the high period the PFET is kept on and the NFET is turned off. For rise time calculation you can consider the driver as a simple 1 Ohm pull-up resistor. But you will have to limit the current to the specified 4 A. Otherwise the driver might get damaged, have a look at the absolute maximum ratings.
So to calculate or simulate rise time you could simplify the driver like this:

You need to estimate the series inductance which includes PCB layout as well as the input capacitance of the MOSFET. You end up with an RLC series circuit for which you can increase the resistance to increase rise time. The series inductance is probably in the order of some nH to tens of nH given reasonable PCB layout.

A:
In the datasheet, does the CLoad emulate the parasitic capacitance that is usually found in FET datasheet as Q gate charge?

It doesn't "emulate" it, it is the gate capacitance for a "typical" application.
So, one way to prolong the rise- and fall-time is to add capacitance in parallel with the gate - but this will waste energy proportional to the added capacitance, and thus is not desirable.
Instead, using a series current limiter will keep the energy loss fixed independently of the rise/fall time.
I haven't tried it on the breadboard, but I'd start with current sources in series with the gate driver. Something like the below may be a starting point. R1 and R3 adjust the rise- and fall-time: the larger the resistance, the slower the corresponding slew rate.
Rs1, D5, D6 and Cg1 are a reference circuit used to compare the performance of the current sources to a short circuit.
Rs1 and Rs2 model the source impedance of the gate driver.

simulate this circuit – Schematic created using CircuitLab
D1 and D2 steer the high and low levels to separate current sources. This makes both transition times individually adjustable.
Q2+Q22 and Q4+Q44 are the current limiters and steer base current away from the pass elements Q1/Q3. D3 and D4 are anti-saturation diodes, and may not be needed in the physical circuit.
The voltage across the reference gate capacitor Cg1, and the slew-rate-limited gate capacitor Cg2, is shown on the plot below.

It is also possible to have just one current source inside a rectifier bridge - that way both the rising and falling edge would be controlled exactly the same:

simulate this circuit
The rising- and falling edge are now controlled by the same current source and are symmetric:

At this point we may as well make our own gate driver :)
The input is driven from a 3.3V logic level source V1. Q3-Q4 are a push-pull driver stage that generates the 12V-level control voltage. Q1-Q2 are the common-base stage that controls Q3-Q4. 1V6 is a 1.6V reference level that biases the common-base input stage. D1 and D2 are Baker clamps that prevent Q3 and Q4 from saturating.
Q5-Q7-Q9 and Q6-Q8-Q10 are a pair of voltage-controlled current sources that can drive current into the gate capacitance Cg, or out of it. Vc1 is the voltage that controls the current.
D3 and D4 prevent the current source outputs from saturating by robbing the drive current when the output voltage gets close to the rails.
The rise- and fall-times are controlled by the 50Ω potentiometers Rr and Rf, respectively.

simulate this circuit
The input, high-level control, and gate voltage waveforms are shown below.

Tweaking the coupling networks a bit, we get:

simulate this circuit
Simulation at 1ns time step looks quite reasonable. I've tried it out on the breadboard and soldered point-to-point on a copper-clad laminate acting as a ground plane, and the simulated performance is representative of what's possible with careful construction and tweaking to match the parasitics.

If the digital PWM source doesn't have a "high drive" option in the GPIO configuration, a buffer is necessary, e.g. several paralleled 74HC04, etc.


text:
Q: Angular - How to fix "ERROR TS2322: Type 'ModuleWithProviders' is not assignable to type 'any[] | Type'" I'm trying to create a webapp using Angular, but at the time of compilation I get this error which I can't solve:

ERROR in src/app/app.module.ts(22,5): error TS2322: Type
  'ModuleWithProviders' is not assignable to type 'any[] |
  Type'.   Type 'ModuleWithProviders' is missing the following
  properties from type 'Type': apply, call, bind, prototype, and 5
  more.

That's my app.module.ts:
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ToastrModule } from 'ngx-toastr';
import { AppRoutingModule } from './app-routing.module';
import { ComponentsModule } from './components/components.module';
import { AppComponent } from './app.component';
import { AdminLayoutComponent } from './layouts/admin-layout/admin-layout.component';

@NgModule({
  declarations: [
    BrowserAnimationsModule,
    FormsModule,
    HttpClientModule,
    ComponentsModule,
    RouterModule,
    AppRoutingModule,
    NgbModule,
    ToastrModule.forRoot()
  ],
  imports: [
    AppComponent,
    AdminLayoutComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

The error is reported on the line: ToastrModule.forRoot()
And that's my package.json:
{
  "name": "pum-pum-pum",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~7.2.0",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/forms": "~7.2.0",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "core-js": "^2.5.4",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.13.0",
    "@angular/cli": "~7.3.7",
    "@angular/compiler-cli": "~7.2.0",
    "@angular/language-service": "~7.2.0",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.2.2"
  }
}

Please someone help me.

A: *

*declarations is save components,pipes or directives.

*imports is save modules.

@NgModule({
  // right
  imports: [
    BrowserAnimationsModule,
    FormsModule,
    HttpClientModule,
    ComponentsModule,
    RouterModule,
    AppRoutingModule,
    NgbModule,
    ToastrModule.forRoot()
  ],
  // right
  declarations: [
    AppComponent,
    AdminLayoutComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

A: As i see, you have added Modules under declarations and components under imports, you should add Modules under imports and components under declarations.

A: Add all this in import not in @NgModule({declarations:
FormsModule,
HttpClientModule,
ComponentsModule,
RouterModule,
AppRoutingModule,
NgbModule,
ToastrModule.forRoot()
any module or importation is not added in declarations.
this will be like -
imports: [
BrowserAnimationsModule,
FormsModule,
HttpClientModule,
ComponentsModule,
RouterModule,
AppRoutingModule,
NgbModule,
ToastrModule.forRoot()
],


text:
Q: Google chrome on Windows 8 does not understand time format in javascript cookie expiration time I would like to set a cookie from Javascript for short period of time (some hours). I use the following time format:
document.cookie="MYCOOKIE=TEST; expires=Saturday, 28-Jun-14 21:01:33 GMT";

This works fine from many browsers, but it seems to be a problem with Google Chrome on Windows.
For example in Google Chrome on Windows 8, after setting the Cookie above, I go to Settings->Privacy->Content Settings->Cookies and site data it shows: (I am in CEST time zone, so I am 2 hours ahead of GMT)
Expires:    Saturday, June 28, 2014 10:01:33 PM

Note that expiration time is 10:01:33 CEST whereas the correct should be 11:01:33 CEST.
(This works fine with Chromium browser on Ubuntu 12.04 and Firefox on Windows 8)
See also Chrome does not allow cookies with expirations less than 4 hours.

A: How about trying a cookie library like this: https://github.com/ScottHamper/Cookies.
If you scroll down the page to the examples, there are three different ways to set a cookie's date, and it says it's cross browser, so there is a chance that it has accounted for this strange difference in how Chrome acts on Windows 8.  And, according to the site, it is a tiny 1kb file so it shouldn't noticably slow your page.


text:
Q: Laurent expansion of different function I have two problems of expanding function to Laurent series:
1)find the Laurent expansion in the ${[z:R<|z|<\infty] }$ domain of the function $f(z)=\frac{1}{z^2+1}$, for $R$ bigger enough,what is the minimal R?
2)find the Laurent expansion of the function $f(z)=\frac{A}{z^2}+\frac{B}{z}+\frac{C}{z-1}$ in the domain $\Omega=\Bbb C/D_2(0) $, what are $A,B,C$ so $f$ would be holomorphic on $\Omega$?


text:
Q: How to use env .bashrc variables on crontab? I need to send a personal env variable $FTP111_PASSWD defined at my personal .bashrc  to crontab execution. How to set an environment variable on crontab?
My original shell script, named cron4_etc.sh, created for crontab execution was:
#!/bin/bash

cd /myFolder/
ftp -n -i <<EOF
open 101.111.111.111
user myUser "$FTP111_PASSWD"
mget check_*.log
bye
EOF

If I execute the script via terminal ./cron4_etc.sh it is executing fine, but if I have start it using the following crontab line
  */20 *     *   *   *     /home/myUser/cron4_etc.sh > /tmp/cron4.log 2>&1

crontab says

Password: Login incorrect.\nLogin failed.

I tried to improve my script using this suggestion, but the error persists:
#!/usr/bin/env bash

# set environment
source /home/myUser/.bashrc

cd /tmp/pg_io/PGW
ftp -n -i <<EOF
open 101.111.111.111
user myUser "$FTP111_PASSWD"
mget check_*.log
bye
EOF

PS: I am using Ubuntu 18 LTS, but the question is for generic crontab.

A: My favorite solution comes from Augusto Destrero, who provided the following answer to a very similar question:

Setting vars in /etc/environment also worked for me in Ubuntu. As of 12.04, variables in /etc/environment are loaded for cron.

Some people suggest to do a simple env >> /etc/environment to append all your environment variables, but I would be careful with that and rather review /etc/environment manually.


text:
Q: How i can add permission in a field collection, only for one field I want add permission only on one field in a field collection, for a special user. Thx for help.

A: Minimal reply for minimal question: use hook_form_alter and set #access to the form field when the current  user (via gloabl $user) uid matches the uid you want.
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#access
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7

A: If you don't want to do it programmatically you can find this functionality with the Field Permissions module : https://www.drupal.org/project/field_permissions


text:
Q: Small questions for AJAX onreadystatechange xmlhttp.onreadystatechange=function() {

So this says onreadystatechange, invoke function(). Can I put parameters in function()? Second question, what does it mean when someone writes, xmlhttp.onreadystatechange=statechanged? Does that mean it will always be true or something?

A: *

*You can't use a parameter since onreadystatechange has no parameters to give you. What parameter are you expecting? It is simply a hook for handling the response. What you do have available is the xmlhttp.readyState which tells you if the response is ready or not, xmlhttp.status - the http status code (i.e. 200), and xmlhttp.responseText - the response itself.

*No - that means you are assigning a variable reference (a function) to onreadystatechange.
I would strongly suggest using a JS framework (such as jQuery) to do AJAX calls - it will abstract away the low-level details you are asking about. If you must use native JS AJAX calls - read this tutorial.

A: You can pass parameters with a wrapper function:
var func = function(p1, p2) {/*...*/};
xmlhttp.onreadystatechange = function() {
  func(foo, bar);
};


text:
Q: Managed to unmanaged code, DWORD value to LPVOID I have a manged process which passes an address value as a DWORD.  I wish to use this DWORD value in a thread function which requires the param be passed as an LPVOID, how can I pass the value without it becoming garbled?  This is not the real code but as much of it as I can remember!
void incoming(DWORD addr)
{
    CreateThread(...threadfunc, addr...);
}

DWORD WINAPI threadfunc(LPVOID param)
{
  DWORD _addr = param
}

The problem is the receiving threadfunc the addr value is garbled so when I use ReadProcessMemory() for example it is now rubbish!
Thanks.

A: You need the managed process to pass the pointer to incoming as System.IntPtr.  This is the standard way to pass pointer values to unmanaged APIs.

The IntPtr type can be used by
  languages that support pointers, and
  as a common means of referring to data
  between languages that do and do not
  support pointers.

As noted this will fail on Win64 - you really need to change the incoming parameter to be of type INT_PTR.


text:
Q: async/await inside arrow functions (Array#map/filter) I'm getting compile time error in this code:
const someFunction = async (myArray) => {
    return myArray.map(myValue => {
        return {
            id: "my_id",
            myValue: await service.getByValue(myValue);
        }
    });
};

Error message is:

await is a reserved word

Why can't I use it like this?

A: If you want to run map with an asynchronous mapping function you can use the following code:
const resultArray = await Promise.all(inputArray.map(async (i) => someAsyncFunction(i)));

How it works:

*

*inputArray.map(async ...) returns an array of promises - one for each value in inputArray.

*Putting Promise.all() around the array of promises converts it into a single promise.

*The single promise from Promise.all() returns an array of values - the individual promises each resolve to one value.

*We put await in front of Promise.all() so that we wait for the combined promise to resolve and store the array of resolved sub-promises into the variable resultArray.

In the end we get one output value in resultArray for each item in inputArray, mapped through the function someAsyncFunction.  We have to wait for all async functions to resolve before the result is available.

A: it will be 2 instructions, but just shift "await" with the extra instruction
let results = array.map((e) => fetch('....'))
results  = await Promise.all(results)

A: I tried all these answers but no one works for my case because all answers return a promise object not the result of the promise like this:
{
  [[Prototype]]: Promise
  [[PromiseState]]: "fulfilled"
  [[PromiseResult]]: Array(3)
  0: ...an object data here...
  1: ...an object data here...
  2: ...an object data here...
  length: 3
  [[Prototype]]: Array(0)
}

Then I found this answer https://stackoverflow.com/a/64978715/8339172 that states if map function is not async or promise aware.
So instead of using await inside map function, I use for loop and await the individual item because he said that for loop is async aware and will pause the loop.

A: You can't do this as you imagine, because you can't use await if it is not directly inside an async function.
The sensible thing to do here would be to make the function passed to map asynchronous. This means that map would return an array of promises. We can then use Promise.all to get the result when all the promises return. As Promise.all itself returns a promise, the outer function does not need to be async.
const someFunction = (myArray) => {
    const promises = myArray.map(async (myValue) => {
        return {
            id: "my_id",
            myValue: await service.getByValue(myValue)
        }
    });
    return Promise.all(promises);
}

A: That's because the function in map isn't async, so you can't have await in it's return statement. It compiles with this modification:
const someFunction = async (myArray) => {
    return myArray.map(async (myValue) => { // <-- note the `async` on this line
        return {
            id: "my_id",
            myValue: await service.getByValue(myValue)
        }
    });
};

Try it out in Babel REPL
So… it's not possible to give recommendation without seeing the rest of your app, but depending on what are you trying to do, either make the inner function asynchronous or try to come up with some different architecture for this block.
Update: we might get top-level await one day: https://github.com/MylesBorins/proposal-top-level-await

A: When you want each remapped value resolved before moving on to the next, you can process the array as an asynchronous iterable.
Below, we use library iter-ops, to remap each value into promise, and then produce an object with resolved value, because map itself shouldn't be handling any promises internally.
import {pipe, map, wait, toAsync} from 'iter-ops';

const i = pipe(
    toAsync(myArray), // make asynchronous
    map(myValue => {
        return service.getByValue(myValue).then(a => ({id: 'my_id', myValue: a}))
    }),
    wait() // wait for each promise
);

(async function() {
    for await (const a of i) {
        console.log(a); // print resulting objects
    }
})

After each value, we use wait to resolve each remapped value as it is generated, to keep resolution requirement consistent with the original question.


text:
Q: nuget package-update performance i am using nuget-packages to separate my asp.net-mvc web-application into modules (each area is a separate package).
i needed to do this because its a multi-tenant system where each customer can have his own implementation of the modules.
But when i change something in my modules i need to rebuild them => create the nuget-package and then update the package in my main-application.
My problem is, that updating these packages takes painfully long. My test-module has only about 50kB (3 Views to copy located in the content folder of the package) and it still takes about 3 minutes to update.
The package-source is just a local folder, so it shouldnt be a network-related issue.
Any ideas on how to improve the performance or what i'm doing wrong?


text:
Q: Theory behind patterns formed on Chladni plates? In this video of vibrating Chladni plates we can see small sand particles align themselves into different interesting patterns (also shown in the image below) which correspond to some particular vibrations.
What is the theory behind this fact? Are the patterns created related to the Laplace eigenfunctions of the shape? If yes, how are they related, and what importance has the source point of the vibration?

A: The Ritz paper is pretty in depth but the simple take away is this formula for integers m and n plotted where it implicitly equals 0.

A: What you are seeing on the square plate are the resonant modes of the structure.  Each of these modes has a particular frequency associated with it, and is rung up when the plate is driven at that frequency.  These resonant modes act like standing waves on a string: where some parts of the plate are moving a lot while other parts are standing still. The sand is bounced away from the parts which are moving a lot (the nodes) and is left in the places where the plate is not moving at all (the anti-nodes).
I'll address your specific questions in more detail in reverse order.

what importance has the source point of the vibration?

Almost none (with a few caveats).  If you drive the plate at one of its nodes (a point where it will be moving a lot), then you will excite the resonant mode more than if you drive it at a point which is near an anti-node.  This will only effect the amplitude though, not the shape of the mode.
One caveat is that if the structure has a lot of internal friction (damping), then the mode structure will change slightly and the height of the nodes will die out as you get far from the source point.

Are the patterns created related to the Laplace eigenfunctions of the shape?

I'm not sure what you mean by Laplace eigenfunctions.  As described in the section below, the solutions are eigenfunctions of the two dimensional wave equation.  The starting point for the solution begins with what may be called the Fourier eigenfunctions, but the boundary conditions (which are complicated in the case of a sheet which is free to move at the ends) change these solutions into something completely different.

What is the theory behind this fact?

This journal article has a systematic derivation of exactly the situation you are asking about.  This note has a more easily parsed derivation of the similar situation of a stretched rectangular membrane.  I can walk through the basics of the membrane case here, and point out where it is different from your case where necessary.
If you consider an elastic material and write down the forces on an infinitesimal piece of the material as a function of its height, you find that the equation describing the height of any piece is the two dimensional wave equation;
$$
\frac{\partial^2 u(x,y,t)}{\partial t^2}=\frac{T}{\rho}\left(\frac{\partial^2 u(x,y,t)}{\partial x^2} + \frac{\partial^2 u(x,y,t)}{\partial y^2}\right),
$$
where $T$ is the tension of the surface (units of force per length) and $\rho$ is the mass density (units of mass per area).  A more simplified way of writing this equation which lends itself better to a solution by separation of variables is
$$
c^2\nabla^2 u=\frac{\partial^2}{\partial t^2}u
$$
where $c^2=\frac{T}{\rho}$.  In the case of a rigid material such as your situation this coefficient is given by $c^2=\frac{m\omega^2}{D}$ where $D$ is the cylindrical stiffness of the material, $\omega$ is the resonant frequency, and $m$ is the mass.
Using separation of variables we can separate this equation into three independent one dimensional differential equations;
$$
\begin{align}
\frac{d^2}{dt^2}G(t)+(c\nu)^2G(t)&=0\\
\frac{d^2}{dx^2}H(x)+k^2H(x)&=0\\
\frac{d^2}{dy^2}Q(y)+p^2Q(y)&=0\\
p^2+k^2&=\nu^2,
\end{align}
$$
where $u(x,y,t)=G(t)H(x)Q(y)$.  The solutions to these equation may be thought of as the Fourier eigenfunctions; i.e. $\sin$, $\cos$, $\sinh$, and $\cosh$.
As with all physical problems, we need to specify the boundary conditions in order to get physically meaningful solutions.  As an example, a rubber sheet which is clamped at the edges has the boundary conditions,
$$
u(\pm a, y)=0\qquad\&\qquad u(x,\pm b)=0
$$
where $2a$ and $2b$ are the $x$ and $y$ dimensions of the sheet respectively.  These conditions say that the sheet can't move up and down at the edges where it is clamped.  This situation is rather straightforward to solve and is worked out in the note mentioned above.
You're situation is a bit more difficult because the edges are completely free to move.  In this case you have to incorporate into the boundary conditions the fact that the plate is a rigid object which doesn't need to be under tension to be supported.  Taking them from the article mentioned above, they are
$$
\begin{align}
\frac{\partial^2u}{\partial x^2}+\nu_p\frac{\partial^2 u}{\partial y^2}&=\frac{\partial^3u}{\partial x^3}+(2-\nu_p)\frac{\partial^3u}{\partial x\partial y^2}=0\qquad @ x=\pm a\\
\frac{\partial^2u}{\partial y^2}+\nu_p\frac{\partial^2 u}{\partial x^2}&=\frac{\partial^3u}{\partial y^3}+(2-\nu_p)\frac{\partial^3u}{\partial x^2\partial y}=0\qquad @ y=\pm b,
\end{align}
$$
where $\nu_p$ is a material parameter known as Poisson's ratio which describes how much a material expands in one direction when compressed in the other.
The nice thing about solution of the wave equation by separation of variables is that the solutions you find form a complete set of eigenfunctions for the problem.  Furthermore, their eigenvalues tell you the resonant frequency of each particular mode.  The image below shows the second, third, and fourth order solutions to your equation (taken from the referenced journal article).  When you excite these modes with the sand on the plate, the sand is bounced away from the high points and stays at the un-moving points which are called nodal lines.  These nodal lines are the places where the solution is still zero in the diagram below.

A: The theory of vibrating plates is a bit more complicated than that used for the vibration of membranes, as commented from a previous answer. And yet, this is assuming a thin plate (shear is neglected just as in the Euler Bernouilli beam theory). The theory was developped by Sophie Germain, Poisson, and ultimately by Kirchhoff. So Kirchhoff plate theory should be what you're looking for. Notice in particular the applicable boundary condition at a free edge derived by Kirchhoff (given in a previous answer):  it is not very intuititive! As a matter of fact, analytical solutions are only known for some given geometries and prescribed boundary conditions. I would recommend the following reference: Leissa, A. W. (1969). Vibration of plates. Ohio State Univ Columbus. Another general reference for the theory: Graff, K. F. (1975). WAVE MOTION IN ELASTIC SOLIDS. Publication of: Oxford University Press.