perspective() problems fixed with perspective?

Question: I have a flip animation were I use perspective, I have a simple card that flips when hovered. From my understanding the perspective property and the transform property perspective() are the same except perspective is applied to the parent and is rendered on its children and the perspective() is applied directly to an element you want to have perspective, is this correct? I used the perspective property at first then realized I could simplify my code slightly by using perspective() so I changed it. With perspective() if you hover over the card the animation works but if you move the mouse off and back on before the animation finishes at the very beginning of the animation you get some weird results, the back of the card will show through the front and the card will stretch across the screen, all this weird behavior stops when I give the card a parent with a perspective property and delete the perspective(), so is this a browser error or am I not understanding the differences correctly or is there some other property I need to use with perspective() that I'm not aware off?
two versions of css with results
perspective: 1000px;
https://fiddle.jshell.net/rqzwoguw/28/
transform: perspective(1000px);
https://fiddle.jshell.net/rqzwoguw/29/ // move mouse on and off at the beginning or the middle point of the transition.
Answer: Keep the pespective constant, don't change it on hover.
Just add to .card:  (no rotation, but the same pespective that you are setting on hover)
transform: perspective(1000px) rotateY(0deg);

.front,
.back,
.card {
  width: 100px;
  height: 170px;
  border-radius: 10px;
  text-align: center;
}

.card {
  position: relative;
  transition: transform 1s ease-in-out 0s;
  transform-style: preserve-3d;
  transform-origin: right;
  transform: perspective(1000px) rotateY(0deg);
}

.card:hover {
  transform: perspective(1000px) rotateY(180deg);
}

.front {
  background-color: red;
}

.back {
  background-color: blue;
  transform: rotateY(180deg);
  position: absolute;
  top: 0px;
  z-index: -1;
}

    FRONT

    BACK


Rem used for responsive design looks different on mobile device

Question: I followed advice for a responsive design where I heard that setting up this:
html {
  font-size: 62.5%
}

on the root of your css will make it very easy to work with units (because 1rem = 10px).
And everything worked fine, I checked final work on different screen sizes, adjusted media queries breakpoints and deployed the website. On my computer and all looks good, tablet - also good... but on my iPhone everything looks wrong. I started to look up what can be the cause and one article said that font-size: 62.5% on mobile device doesn't work. Do you have any experience with that? Please share if you have some articles or knowledge about it.
Comment: 1 rem will not equal 10 pixels. 1 rem in your case would equal a font size of 62.5%.
Comment: @Rahim Browser default size is usually 16 pixels. So 16 times 62.5% = 10. However if you dont set a font size and allow the browser to set the size, 1 rem would equal 16px
Answer: 1 rem in your case would equal a font size of 10px based on what is below. Personally there is no reason to set a font size, and allow the browser to set the size
62.5% usually refers to the browser default size of 16px. 16 multiplied by .625 = 10. 1 rem would equal 10px, again based on the browser default font size. When you set 62.5%, you are setting it as 62.5% of the default size. Most browsers default font size = 16px
In CSS rem stands for "root em", a unit of measurement that represents the font size of the root element. This means that 1rem equals the font size of the html element, which for most browsers has a default value of 16px. Using rem can help ensure consistency of font size and spacing throughout your UI.
https://www.sitepoint.com/understanding-and-using-rem-units-in-css/


Fix 404 error when adding conditional action to Rule?

Question: Subsequent to what I saw in the question 'Don't calculate shipping for specific item', I tried to create a rule with a conditional action (screen capture below), but it causes 404 error:

The export for the rule looks like so:
{ "rules_test_please_delete_" : {
  "LABEL" : "Test (please delete)",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules_conditional", "rules" ],
  "ON" : { "node_delete--page" : { "bundle" : "page" } },
  "DO" : [ { "CONDITIONAL" : [] } ]
}
}

How can I fix the 404 error?
Related resources:

Conditional Rules bug report
Rules feature request
Answer: Not sure (yet) what is causing your 404 error, but at this point I'm not convinced it is a bug ...
I imported your exported rule in my own site to experiment with it, this is what happened:

The import worked fine (of course), so I started from the very same Rule as your exported rule.
I then used the Rules UI to also add such "If", and then just show a Bingo-message on the site.
If I would want to add another "if", the URL that would be used for that would have relative path "/admin/config/workflow/rules/reaction/manage/rules_attempt_to_recreate_a_404_error/add/3/if".

Here is the proof of my experiment (an exported Rule, which includes some additional logic within that Conditional Rules Action, and for which I changed the label and machine name also, though only after I imported the rule):
{ "rules_attempt_to_recreate_a_404_error" : {
    "LABEL" : "Attempt to recreate a 404 error",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_delete--page" : { "bundle" : "page" } },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "node:promote" ], "value" : "1" } },
            "DO" : [
              { "drupal_message" : { "message" : "Bingo, this one seems to work ... using \u0022Conditional Rules\u0022 ..." } }
            ]
          }
        ]
      }
    ]
  }
}

The scenario described above was completed in a Drupal 7.5x site, using these versions of related modules:

Rules: 7.x-2.9
Conditional Rules: 7.x-1.0-beta2

I suggest you try to import "my" rule here in your site, and see if you get any other messages while trying to perform that import.
To further pinpoint your issue, have a look at the typical Drupal logging information, you may find there some other indication about what's happening in your site around the time the 404 error occurs.
Notes:

I'm not sure if it could be an explanation for your issue (what it is that causes it), but I noticed that your scenario uses https://, while my scenario was performed using  http:// ... Debugging is the art of taking away all possible causes for an issue, so you may want to try in a site using http:// instead of https:// ... FYI: I tried a similar scenario using  https://, and did not encounter any problem or 404 error.
As an alternative to using the Conditional Rules module, you can also create corresponding Rules Components, with similar Rules Actions to be performed. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".
Comment: What versions of Drupal, Rules, and Conditional Rules are you using?
Comment: I double checked my Drupal logs, and it shows only the 'page not found' at the time when I was seeing the 404 page. What does your URL bar show when you click 'add if'?
Comment: @BrylieChristopherOxley check my updated answer to address your prior comments. And for sure also my note "1." ... (you never know ...). BTW: did you notice all comments below my answer to the linked question got removed ... Good for you that you did accept my advice to create a new question ...
Comment: do you have clean URLs enabled?


Get unique results from observable

Question: I have a component that fetches data from a service and pushes data to an array upon button click. If that data already exists in the array, I don't want it to be pushed again.
import { ImportResults } from '../shared/mass.interface';
import { Component, Input, OnChanges, OnInit } from '@angular/core';
import { MassEmpService } from '../shared/mass.service';

@Component({
    selector: 'app-employee-selection',
    templateUrl: './employee-selection.component.html',
    styleUrls: ['./employee-selection.component.css']
})

export class EmployeeSelectionComponent implements OnInit {

    // Define our search results
    public searchResults: ImportResults[] = [];

    constructor(
        private _massEmpService: MassEmpService
    ) {
    }

    ngOnInit() {

        // Push our results to the array if they don't already exist
        this._massEmpService.importedResults.subscribe(
            data => (this.searchResults.indexOf(data) === -1 ? this.searchResults.push(...data) : '')
        );

    }
}

Is there any quick way to test if an identical object already exists in an array without having to look for a specific key or value?
Scenario
I enter a username into a search field and press "search". It provides me the results, I push them to an array and then use *ngFor to loop over them and display them. However, if I then searched by supervisor, I don't want anyone thats already in the results to appear again, only new data that has not yet been seen.
I know this is more of a generic Javascript question but I am curious if ES6 or angular has anything short that will accomplish this?
Answer: Try to use underscore.js and findIndex method.
The code would be something like that:
import * as _ from 'underscore';
/*
  rest of your code
*/

export class EmployeeSelectionComponent implements OnInit {
    ngOnInit() {
        // Push our results to the array if they don't already exist
        this._massEmpService.importedResults.subscribe(data => {
             if (this.searchResults.findIndex(elem => _.isEqual(elem,data)) == -1)
                 this.searchResults.push(data);
        });
    }
/*
  rest of your code
*/
}

Other solution would be to use .filter() method, but here you need to traverse all entries as well:
ngOnInit() {
   // Push our results to the array if they don't already exist
   this._massEmpService.importedResults.filter(data => {
             return this.searchResults.findIndex(elem => _.isEqual(elem,data)) == -1})
        .subscribe(data => this.searchResults.push(data));
}

I think it could be also good, to immediatelly reject objects with the same reference:
 this._massEmpService.importedResults.filter(data => data != data).... //another chain here

You could also try to experiment with _.indexOf: http://underscorejs.org/#indexOf
Comment: No, RxJS doesn't have any functions related to deep comparison, you always need to provide your own filter function
Comment: This may do the trick - Do you know if rxjs offers anything comparable to the underscore library in terms of this function/solution? I try to avoid needing to install a dependency for a one time use function but mayb need to do so.
Comment: I don't think so. The only other way which I see is to use .filter() method. But again you will need to go threw whole array and compare every element. I will update my answer with this solution in minutes.
Comment: Strange, I installed underscore and used both of the above code snippets and my final output still gets duplicated.
Comment: Ohh. Try to `console.log(_.isEqual(object1, object2))`. What is the output?
Comment: @MaciejTreder - Sorry just getting back to this, was in a meeting. What are my two objects in this case? I tried `console.log(_.isEqual(this.searchResults, data))` and I am getting `false` back in the console.
Comment: As far as I understand under this.searchResults you have **array**, and you are looking for **item**. Maybe that's the case? :) If you want to find item in array you can use _.indexOf(): http://underscorejs.org/#indexOf
Answer: try below myaaray is your array wityh duplicate entries and uniue array will contain array without duplicate entries
var unique = myArray.filter((v, i, a) => a.indexOf(v) === i);

Comment: Is this method doing deep compare, or just only comparing references?
Comment: this is not doing deep compare\
Comment: @RahulCv You can use this approach recursively for deep comparison.

Get unique results from observable


Resources to learn about block bootstrap in time series analysis

Question: Way back when, I used to work in finance, and I remember helping a coworker use some kind of block bootstrap. (I believe the application was: we had weekly data on some financial indicator X, along with weekly data on some stock, and we wanted to measure how well X could be used to predict the stock's movements. And I believe we needed to bring in the bootstrap, because we only had a couple months of weekly data, so we didn't really have many datapoints. I might be misremembering all this, though.)
In any case, I totally forget now how the block bootstrap worked, and I want to remember/review/learn more, so can anyone suggest a good tutorial on it? I tried googling, but all I found were some random research papers. I also tried looking in my copy of Efron & Tibshirani's "An Introduction to the Bootstrap Book", but didn't find anything (unless it's under a name other than "block bootstrap").
Comment: Do you want to give a full reference to Hardle, Horowitz et al.? The second part of your answer is actually a new question. Since this is not a discussion list, you should post it as a new question.
Comment: i have found some useful content in Hardle, Horowitz et al
But the methods mentioned there mainly deal with estimating mean (or, in general, moments) of time series data.....i wanted to know if the method applies to **regression** set-up also.I am currently knee-deep in a live project involving this without much idea of how to proceed....Any help would be greatly appreciated...thanks
Answer: Try the Handbook of Computational Statistics, Part III, section 2.4.
Answer: I have relied on Resampling Methods for Dependent Data by S.N. Lahiri and found it quite helpful. Once you determine some flavors you want to look at more closely (e.g. Circular Block Bootstrap, Stationary Block Bootstrap) it will be easier to find on-line resources discussing actual use cases and implementation details.
Answer: The textbook by Shumway and Stoffer has a short section on bootstrapping time series (state-space) models. Also you may look to:
Pfeffermann, D. and Tiller, R. (2005) Bootstrap approximation to prediction MSE for State-Space models with estimated parameters, Journal of Time Series Analisys, 26, 893-916,
and references therein.
Answer: For an evaluation of its effectiveness and a comparison to alternative methods, see:
Bertrand, Marianne, Esther Duflo and Sendhil Mullainathan. 2004. "How Much Should we Trust Difference-in-Difference Estimates?" Quarterly Journal of Economics. 119 (1): 249-275. [pre-publication version]


Git clone only a set of paths with full history

Question: I'm wondering if it is possible to clone only a set of specific paths from a repository, and the history of those files? Without having to clone the entire repository?
If not, is there a more-efficient way to go about this? I'd like to avoid cloning our entire repo regularly on our CI when I only need a small portion of the repo.
For example I have repository:
./
    - Src/
      - Dir1/
      - Dir2/
    - External/
      - Lib1/
        - file.cpp
      - Lib2/
        - file.cpp
      - Lib3/
    - Resources/
      - image.png
      - video.mp4

I want to clone only External/Lib1 and External/Lib2, as well as its history. I do not need to know about Resources, Source, Lib3, etc. So would be inefficient to clone these.
I have attempted to do this by doing
git clone --depth 1 --filter=blob:none --sparse <REPO>
then
git sparse-checkout set External/Lib1 External/Lib2
Which works well, however I cannot see the history of the files using this method. If there is a way I can sparse-checkout the entire history of only those files, this method would be ideal.
Any help/advice appreciated
Thanks
Comment: Maybe this helps: https://askubuntu.com/a/1074185
Comment: @leun4m This is what I followed for the attempt in the question, but unfortunately doesn't provide the history of the files :( Thanks for the response though
Comment: Don't think you can. Git works on commits, so when you do a sparse checkout it can't map that to commits, and thus not to history.
Answer: Our hosting service does not support partial clone. For CI jobs, we maintain a group of mirror repositories that CI jobs can access to. In practice, we use 2 strategies.
In the first strategy, the mirror repositories are created by git clone --mirror. They are bare repositories. When a CI job starts, it clones the repository with the option --reference-if-able /path/to/mirror/repository. This way, it borrows objects from the mirror repository and only fetches the missing objects that don't exist in the mirror repository. This option can be used with --single-branch, --depth <n> and git sparse-checkout if necessary. After the job, the CI repository is removed.
Regularly we update these bare repositories and run git gc, like once a day or once a week, so that the mirror repositories can hold as much data as possible.
In the second strategy, the mirror repositories are created by git clone --no-checkout. They are non-bare repositories without any checkout. When a CI job starts, it fetches the needed ref in the repository first and then it creates a work tree for the ref or commit by git worktree add /path/to/worktree revision. Sparse-checkout is also compatible with work trees. After the job, the CI work tree is removed. According to our experience, it's better to create the work trees on the same disk where the mirror repositories are located.
For these non-bare repositories, we run git gc regularly. When there are too many loose objects, some git commands would become very slow.
With the help of mirror repositories, we find a point where storage cost, time cost and network cost are all balanced.


Is there a way to test pickups or to determine which pickup to buy

Question: I don't like the sound of the stock active pickups on my Ibanez (ART-320 - Les Paul like body), so I'd like to change them.
I really love the sound of the passive pickups I have on my other guitar (Seymour Duncans SH6N, SHR1N, TB6) so I'm thinking to change my pickups to passive SDs.
But after spending some time on their website, I'm a little confused as pickups are a quite expensive and I don't want to mess up...
Once installed the pickups won't probably sound like they sound in the site demos: my guitar is different, the strings & tuning are different (tuned in C with Ernie Ball "Not even slinky" 12-56).
Is there a way to anticipate how they will really sound ?
Do you have any advice on how to choose new pickups without being too surprised by their sound once bought & installed ?
Bonus question : is there any issue with replacing active pickups by passive ones ?
Answer: The best way to anticipate how they will sound is to conduct a comparison. If you can find a music shop with guitars matching your current and proposed setup that would be ideal, however that may be tricky with an esoteric setup so you might just need to see what is closest.
You might also be able to find videos online demonstrating the sounds.
Doing that should mean no surprises.
Even the site demos will help, don't worry too much about your tuning.
There are issues with the differences between pickups - mostly around output signal level, sustain and signal to noise ratio - but it is very easy to replace pickups if you have a little electronics experience.
Answer: If you search on youtube the type and model of the pickup, there are videos people posted with their guitar and sound, which probably are closer than what you get on official site demo. May be that will give you a start.
I would go to a large local guitar stores to try out guitars installed with different pickups.
Of course, nothing can replace actually trying them on your guitar.


Function with certain value/derivative at 0 and bounded support.

Question: Hello fellow math people,
I would like to construct a function with the following properties:

$ f \in C^{\infty}(\mathbb{R}^d)$
$f(0) = 1$ and $ \partial_{e_i} f(0)=1$ for one $i =1,...,d$.
$\sup(f) \subset B_r(0)$ with $ 0 < r \leq 1$ where the ball is looked at with respect to the Euclidean norm.

I think one can construct this using splines for example, but I do not really know how to start, could anyone show me how to do this? An example for $i=1, r=1$ would suffice as well.
Thank you in advance!
Comment: Do you already know how to construct any non-trivial $f\in C^\infty(\mathbb{R})$ with compact support?
Comment: I could think of a bump function and I was playing around with it, but the above function is not symmetrical to the origin, so I would need some modification.
Answer: First note that if we have a function $f$ with this properties in $1$ dimension, we can take $g(x_1,\dots,x_d)=f(x_1)\dots f(x_d)$ to solve the problem in arbitrary dimensions (you have to choose the support of $f$ small enough so that $(\operatorname{supp}f)^d\subset B_r(0)$).
In $1$ dimension, let's start with any non-trivial $\phi\in C_c^\infty(\mathbb{R})$. Since $\phi\neq 0$, there is $x_0\in\mathbb{R}$ such that $\phi(x_0)\neq 0$, $\phi'(x_0)= 0$. Replacing $\phi$ by $\alpha \phi(\beta(\,\cdot-\gamma))$ with suitable $\alpha,\beta,\gamma$, we may assume that $x_0=0$, $\phi(x_0)=1$ and $\operatorname{supp}\phi\subset (-r,r)$. Then $f(x)=(1+x)\phi(x)$ has all the desired properties.
Answer: Thanks for your answer, lets see if everything works out:
So if I take $\phi(x) = e^{\frac{1}{r^2}}e^{-\frac{1}{r^2-x^2}}$ on $(-r,r)$ and $0$ elsewhere we have $\phi(0)=1$, $\phi^{\prime}(0)=0$ and $supp(\phi) \subset B_{r}(0)$.
Thus $f(x)=(1+x)\phi(x)$ would have the above properties for d=1.
Now if we take $r_d$ such that $\sqrt{d} r < r_d$ then the function $g(x_1,...,x_d) = f(x_1)...f(x_d)$ admits $supp(g) \subset B_{r_d}(0)$ since $(supp(f))^d \subset B_{r_d}(0)$ and has all the wanted properties for arbitrary $d$.
Is that correct?
Comment: Yes, looks good.


No UIKeyboardWillShowNotification when tapping the next UITextField

Question: I have several UITextFields listed below each other and would like to move the active field appropriately when the keyboard slides up.
I have added my controller as an observer to UIKeyboardWillShowNotifications and that works fine when the user first taps a text field. If he taps one of the other text fields without making the keyboard go away first no UIKeyboardWillShowNotifications appears though and I get no chance to adjust the position of the new active text field. I guess it somehow makes sense that no UIKeyboardWillShowNotification appears as the keyboard just stays there but...
What to do??
I do not see how I can add my adjusting code somewhere else as I need the keyboard size information which is kept in the userInfo in the keyboard notification.
Thanks a lot,
Stine
EDIT: Maybe it will be more clear what I need if I paste some of my code here:
- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cellInputViewWillOpen:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cellInputViewWillClose) name:UIKeyboardWillHideNotification object:nil];
}

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void) cellInputViewWillOpen:(NSNotification *)aNotification {
    CGRect keyboardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
    keyboardFrame = [self.view convertRect:keyboardFrame fromView:nil];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[self.tableView indexPathForSelectedRow]];
    self.tableView.contentOffset = CGPointMake(self.tableView.contentOffset.x, cell.frame.origin.y - ((self.tableView.frame.size.height - keyboardFrame.size.height) / 2.0f));
    self.tableView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, keyboardFrame.size.height - 44.0f, 0.0f);
    [UIView commitAnimations];
}

- (void) cellInputViewWillClose {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    self.tableView.contentInset = UIEdgeInsetsZero;
    [UIView commitAnimations];
}

Comment: I've updated my answer based on the new information
Answer: Use textField:didBeginEditing instead. You may need to keep track separately of if your keyboard is already showing so you don't scroll twice.
EDIT : I didn't realise you were talking about a table view, sorry. In that case you can adjust the scroll view contents as you are already doing, then use the table view scroll to index path methods when you change the selection using the table view delegate methods.
Comment: But how can I get hold of the keyboard size information in there? :)
Comment: Keep your original code from keyboardwillshow, this is just for your subsequent fields. This is what I meant by keeping track of the keyboard separately, sorry.
Comment: Sorry, if I am slow here, but I don't understand what I will be doing in the `textField:didBeginEditing`?
Comment: You will scroll to the new textfield. Unless I've completely misunderstood the question?
Comment: ARGH! It woooorks!! :D Thank you sooo much!!


Exclude a single file from Apache https redirect

Question: I have a redirect rule in my http.conf file to redirect all HTTP requests to HTTPS:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

This works well as a blanket approach, however I'd like to exclude robots.txt from being redirected to https (so it should be http://www.mysite.com/robots.txt)
This is mostly because google refuses to grab my robots.txt over ssl (?)
I've tried a couple of different ways but so far it either 404's the file or ignores it and goes to https://www.mysite.com/robots.txt (as per the rest of the site)
I tried something along the lines of:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^robots.txt
RewriteRule (.*)$ https://%{HTTP_HOST}/$1 [NC,R=301,L]

Any suggestions on this would be greatly appreciated.
Comment: You can do this, but it may not have the effect you want. Technically, `http://www.example.com/` and `https://www.example.com/` are different sites. Better to figure out _why_ Google won't fetch your robots.txt and fix that problem.
Comment: A fair point! I'll try and have a look in to this. Logwatch was showing `404 Not Found        /robots.txt: 3 Time(s)` which triggered my investigation.
Answer: Sure.
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^/robots\.txt$ - [L]
# or if this is in an htaccess or <Directory>:
# RewriteRule ^robots\.txt$ - [L]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Comment: Thanks for the reply, I've tried ...

 `RewriteCond %{HTTPS} off`
 `RewriteRule ^/robots\.txt$ - [L]`
 `RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}`

but still the same results as before, I'm afraid
Comment: @Mike Where is that configuration located?


Best way to search and replace text from blocks

Question: Is there a module or some other method to find and replace text from all existing blocks?  I've come accross Search and Replace Scanner Module but it looks like it only does search and replace on nodes.
Much Thanks.
Answer: Are you referring to custom blocks, not those provided by modules? If so, the main data is in the body column of the block_custom table in MySQL.
You could use an SQL query to perform the replacement.
UPDATE `block_custom` SET `body` = replace(body,"findstring","replacestring");

Credit: ChrisBrunner.com


Ruby Parsing: Error when I trying to put Cyrillic symbols into URL request

Question: I wrote a Bot for Telegram, where users can receive images for their requests. But there was one problem, which I could not solve.
Some example with parsing on Ruby:
json_object = JSON.parse(open("https://api.site.com/search/photos?query=" + message.text + "&per_page=10&client_id=42324d2lkedi234fs342dfse2c038fdfsdfs").read)

message.text - It's a field with request from users.
Everything works fine with latin literals, but when I send Cyrillic(API also supports Cyrillic alphabet) symbols I get the below error:

/Users/me/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/uri/rfc3986_parser.rb:21:in
  `split': URI must be ascii only
  "https://api.site.com/search/photos?query=\u0432\u0430\u0432\u0430&per_page=10&client_id=42324d2lkedi234fs342dfse2c038fdfsdfs"
  (URI::InvalidURIError)

I used Encoding with utf-8 and win-1252, but nothing helped. How should this be fixed?
Answer: You should encode your cyrillic string:
URI.encode('http://google.com?1=АБВ') # => "%D0%90%D0%91%D0%92"

So, use it like this (or encode whole url):
URI.encode(message.text)

Answer: Try with
"anything".parameterize.underscore.humanize.downcase


Haskell, Aeson - no instance for (ToJSON ByteString)

Question: So happy making it this far, encountered a new hurdle:
Got this code made to be encoded to JSON. However no matter when type I use as an instance, the compiler complains. Now I am obviously doing something wrong, but it is exactly what is in the documentation (when using DeriveGeneric obviously).
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}

import Data.Aeson
import Data.Text as T
import Data.ByteString.Lazy as B
import Data.ByteString.Lazy.Char8 as BC
import GHC.Generics

-- decode :: FromJSON a => B.ByteString -> Maybe a
-- decode' :: FromJSON a => B.ByteString -> Either String a
-- encode :: ToJSON => a -> B.ByteString

data System = System  { system :: BC.ByteString
                  , make :: BC.ByteString
                  , code :: Int
                  } deriving (Generic, Show)
instance ToJSON System
-- instance FromJSON System

platform = System { system = "FPGA"
                  , make = "Xilinx"
                  , code = 10165
                  }
encodePlatform :: BC.ByteString
encodePlatform = encode platform

Compiler output:
    • No instance for (ToJSON ByteString)
        arising from a use of 'aeson-184.108.40.206:Data.Aeson.Types.ToJSON.$dmtoJSON'
    • In the expression:
        aeson-188.8.131.52:Data.Aeson.Types.ToJSON.$dmtoJSON @(System)
      In an equation for 'toJSON':
          toJSON = aeson-126.96.36.199:Data.Aeson.Types.ToJSON.$dmtoJSON @(System)
      In the instance declaration for 'ToJSON System'
   |
17 | instance ToJSON System

Comment: If `ByteString` is really the correct type here, then you should probably not be converting it to JSON. Use binary serialisation instead. If those fields actually contain text rather than binary data, then make the type `Text`. If they do contain binary data but you _need_ to use JSON, use base64 or something like that.
Answer: That's because there is no ByteString instance for ToJSON typeclass. Historically, it used to be present but it was removed because JSON strings should be valid unicode.
You can find more details here:

https://github.com/bos/aeson/issues/126
https://github.com/bos/aeson/commit/9ee73f303cacb8ae73b2325f2f47288522607420
https://github.com/bos/aeson/pull/148/files

For fixing it, I would convert it to Text type and then encode into JSON.


Como passar valor vindo do service para var?

Question: Possuo um serviço REST para buscar os valores do visitante. Porém, não consigo manipular os valores vindos do serviço fora da promise.
export default{
  data(){
    return{
      visitor: {}
    }
  }
}

created(){
   this.VisitorService.show(this.visitorStorage)
      .then(visitor => {
        this.visitor = visitor;
        console.log(this.visitor);
        // dentro da promise ok, apresenta o valor.
      }).catch(error =>{
      console.log(error);
    });

    console.log(this.visitor);
    // fora, imprime somente o objeto
}

Alguém possui alguma ideia do que posso estar fazendo de errado?
Resultado impresso dentro da promisse

Resultado que é impresso fora da promisse
Comment: Tem como mostrar o que tá sendo apresentado em cada caso?
Comment: @LINQ Inclui duas imagens com as saídas
Comment: Esse `created` está fora do objeto, devia estar depois do `data()`. Acho que é só esse o problema do teu código. O que é esse `this.VisitorService`? como estás a adicioná-lo ao objeto do Vue?
Answer: Você está utilizando o escopo this dentro da promise, isto faz com que não seja utilizando o escopo do Vue e logo, sua variável não receberá o valor. Crie um ponto de acesso ao escopo do Vue com o nome de outra variável e utilize este ponto para fazer a associação posteriormente. Ficaria da seguinte forma:

export default {
  data() {
    return {
      visitor: {}
    }
  }
}

created() {
  var self = this;

  this.VisitorService.show(this.visitorStorage)
    .then(visitor => {
      self.visitor = visitor;
    }).catch(error => {
      console.log(error);
    });

  // Não pode ser utilizado o console.log logo após uma requisição
  // pois você não tem certeza que a chamada foi finalizada...
  // o correto é utilizar dentro do then da promise como fez.
  // console.log(this.visitor);
}

Fazendo desta forma, o visitor será alimentado no vue e assim, tendo efeito no html caso o esteja utilizando. O que não pode é utilizar a chamada do console.log fora do escopo da promise esperando que ele tenha o valor correto. A promise serve exatamente pra isso, mas para acessar o escopo do Vue, você precisa antes armazenar em uma variável sua instância pois o this será dentro do contexto da promise e não do vue.
Comment: Na verdade eu havia declarado o visitor já dentro do data(). Irei editar para deixar esta informação junto do exemplo. também seguindo conforme o seu exemplo, acaba retornando o componente..
Comment: Fiz uma atualização, veja se ficou melhor para entender.


RAID Spare Drive on ProLiant G6 Server

Question: I have a question about the Spare Drive on an HP ProLiant Raid Disk Array.
Does the Spare Drive have to be greater or equal the size of the largest RAID drive?
For example (is this configuration possible?):
Drive Bay 1  = 600 GB = RAID 5
Drive Bay 2  = 600 GB = RAID 5
Drive Bay 3  = 450 GB = RAID 5
Drive Bay 4  = 450 GB = RAID 5
Drive Bay 5  = 450 GB = RAID 5
Drive Bay 6  = 450 GB = Spare Drive on Standby
Thanks!
Answer: If the disks are part of the same array, the smallest disks would dictate the size used on the larger disks.  That being the case, the 600GB would be utilized as 450GB.
Generally speaking, it's not advised to run different types of disks in the same array.
Depending on how fickle your controller is, it may not handle the mismatched disks.  However, most modern controllers are tolerant of this.
Comment: +1, If he's using a HP SmartArray P or E series it will work exactly as described here. It is also specifically advised against by HP.
Answer: Drive Bay 1 = 600 GB = RAID 5
Drive Bay 2 = 600 GB = RAID 5
Drive Bay 3 = 450 GB = RAID 5
Drive Bay 4 = 450 GB = RAID 5
Drive Bay 5 = 450 GB = RAID 5
Drive Bay 6 = 450 GB = Spare Drive on Standby
Should be possible but your usable space will be 450 * 5 - 450 (parity) = 1800GB and not (600*2) + (450 *3) - 450 (parity) = 2100GB because the RAID array can only use smallest drive.
Now just because it should be possible doesn't mean I would run it that way.

RAID Spare Drive on ProLiant G6 Server


Is the basin of attraction of a $p$ starshaped wrt to $p$?

Question: Let $p\in\Bbb C^n$ (with $n\ge2$) be an attractive fixed point for $F\in\operatorname{Aut}\Bbb C^n$ (i.e. holomorphic bijection), that is $F(p)=p$ and all the eigenvalues of $F'(p)$ are in  modulus $<1$.
The basin of attraction of $F$ in $p$ is defined as
$$
\Omega_{F,p}:=\{z\in\Bbb C^n\;:\;\lim_{j\to+\infty}F^{(j)}(z)=p\}
$$
where $F^{(j)}$ is the composition of $F$ with itself $j$-times.
Is $\Omega_{F,p}$ starshaped with respect to $p$?
Comment: Without thinking deeply about it I would imagine not, because you should be able to take any automorphism and 'twist' it around the fixed point to turn e.g. spiral arms non-convex. Concretely, you should be able to build a basin of attraction that's any 'nice' shape.
Answer: The answer is no, although it doesn't seem so easy to give a rigorous counter-example.
First, it is not the case that immediate basins of attracting fixed points are star-like for quadratic polynomials. Proof by picture:
https://upload.wikimedia.org/wikipedia/commons/c/c3/Julia_set_of_the_quadratic_polynomial_f%28z%29_%3D_z%5E2_-1.12%2B_0.222i.png
Then given say the quadratic polynomial $f_c(z)=z^2+c$ in the picture, you can perturb it to get a Henon map $g_c(z,w)=(f_c(z)+\epsilon w,z)$ that is an automorphism of $\mathbb C^2$. As $\epsilon \to 0$, the attracting basin of $g_c$ degenerates to that of $f_c$, so I expect it not to be star-like.


induction to prove $n^2 - 1$ is divisible by 4 by changing variables

Question: I have to prove $n^2 - 1$ is divisible by $4$, where $n\in\mathbb{O}_{>0}$.
It says, "You cannot prove this by induction on $n$. Rewrite $n^2 - 1$ in terms of a variable on which you can do induction."
Why is it not possible to do this by induction on $n$ and how would I change the variable?
All help is appreciated.
Comment: Is $\Bbb{O}$ supposed to be the set of odd integers? This is very nonstandard notation.
Comment: More importantly, the person demanding this be done by induction should be subjected to judgmental looks.
Comment: "You cannot prove this by induction on n." The person (?) having commited this nonsense should be hanged.
Comment: Yes $\mathbb{O}$ is supposed to be the odd set. Hanged? My prof got her phd from Columbia so I would hope she must know better.
Comment: Most likely, "you cannot" means "you are not allowed to".
Comment: {1,3,5,...,2k+1,2k+3,...} I don't see why induction couldn't be apply to the odd numbers. But whatever I guess they want you to change n to 2k+1 and only look at the set {1,2,3,4...,k,k+1,...}
Comment: It is much easier to just use a direct proof but we happened to be working on induction at the moment and I suppose she was looking for an easy exercise to make a point
Comment: I think his prof is saying that we cannot induct on $n$. We may replace $n$ by $2k+1$ and induct on $k$ instead
Comment: I agree with Barak: that "you can't" most probably meant "you're not allowed to".  +1
Answer: The text you are using takes a pretty narrow view of what it means to prove by induction. The statement is: $1^2-1$ is divisible by $4$, and if $k^2-1$ is divisible by $4$ where $k$ is odd, so is the next odd number ($k+2$). But
\begin{equation*}
  (k+2)^2-1 = k^2+4k+4-1 = (k^2-1) + 4(k+1),
\end{equation*}
which is divisible by $4$ since $k^2-1$ is by the inductive hypothesis.
I assume that what the text means is that since we are assuming $n$ is odd, we should instead use the statement $(2k+1)^2-1$ is divisible by $4$ if $k$ is a nonnegative integer. That is proven in much the same way: true for $k=0$, and if true for $k$, then
\begin{equation*}
  (2(k+1)+1)^2-1 = 4k^2 + 12k+9-1 = 4k^2+4k+4 + 8k+5 = (2k+1)^2 - 1 + 4(1+2k).
\end{equation*}
Answer: If $f(n)=n^2-1$
$f(m+2)-f(m)=(m+2)^2-m^2=4(m+1)$
$\iff4\mid f(m+2)\iff4\mid f(m)$
Now $f(1)=?$
Comment: In fact, $(2a+1)^2=8\dfrac{a(a+1)}2+1\equiv1\pmod8$
Answer: Put $\;n=2k-1\;,\;\;k\in\Bbb Z\;$ , so
$$n^2-1=(2k-1)^2-1=4k^2-4k+1-1=4k(k-1)$$
and clearly the rightmost term is divisible by $\;4\;$ so we're done.


How to calculate confidence interval of a data?

Question: How to calculate 95% CI data for the following 11 readings:
<code>102.61 100.31 107.04 95.00 105.61 97.75 107.76 96.56 92.90 96.98 102.03
</code>
Average = 100.41,
Std. dev. = 5.017
Comment: Check wikipedia: http://en.wikipedia.org/wiki/Confidence_interval
Comment: You don't make CI's for data. If you want a CI for the *mean* you should say that. If you want a PI, or a tolerance interval (which are arguably intervals for 'data'), then say that. If you want a CI for some other quantity, be specific.
Comment: I thank all of you @Salvador Dali ,@Matt Krause And Glen_b for your response .To be frankly with you I Have no clue about how to phrase the question nor to solve it.I was requested to find the 95% CI of series of tests to a known reference which is 100 PPM,my results are shown above.
Answer: You can easily get the CI with the following formula: $\textrm{CI} = \textrm{mean}(\textrm{data}) \pm Z(a/2) \frac{std}{ \sqrt{n} }$

mean(data) is already known to you,
$Z(a/2)$ can be found from a table, where $a = 0.95$. For your particular case it will be $1.96$
standard deviation is also given
$n$ is the number of elements in your data
Comment: For a sample size this small, I'd use a t-based interval.
Comment: Here you go (for the formulas) http://math.stackexchange.com/help/notation
Comment: can someone please show me how to create nice formulas here? Would be very thankful.


What does an asterisk on top of a set mean?

Question: I'm reading an article which defines something called a hash function.

Let $n\in\mathbb{N}$ and let $H:\{0,1\}^*\to\{0,1\}^n:m\to h=H(m)$...

I know that $\{0,1\}^n$ is the cartesian product of the set with itself $n$ times, but I am not familiar with the meaning of the asterisk in this context for $\{0,1\}^*$
Is anyone familiar with the notation?
Comment: I think this is [Kleene star](https://en.wikipedia.org/wiki/Kleene_star).
Comment: It should be emphasized that the answer given here (the Kleene star) applies to *this particular case*, as easily inferred from the context. There are dozens, if not hundreds, of different uses of a superscript asterisk in mathematics (and whatever text you're reading is not doing a very good job if the notation has not been clearly introduced and occasionally recalled).
Answer: In your case $$\{0,1\}^*=\bigcup_{n=0}^\infty\{0,1\}^n$$
In context of hash-functions, $\{0,1\}^*$ would be the set of strings with "letters" 0,1; including the empty string but no single infinite string.


Cannot install socket.io using NPM on Windows 8.1

Question: This is a problem many people have had it seems, yet none of the solutions I have found seem to work. I am trying to install socket.io on Windows 8.1 using,
npm install socket.io
I get a ton of red errors that seem to take issue with some file,

node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\node_modules\nan\nan.h

I have Visual Studio 2012 Express installed as per suggestions in other threads. Python version is 2.7.8, Node is 0.12, node-gyp is 1.0.3. The goal is to install email@example.com.
What should I do?
EDIT: There are the errors

... Lots of errors here ... And then ...
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(457): error C2039: 'Dispose' :
  is not a member of 'v8::Persistent' [C:\Users\
  Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modu
  les\ws\build\validation.vcxproj]
            with
            [
                T=v8::Object
            ]   C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(458): error C2039: 'Clear' : is
  not a member of 'v8::Persistent' [C:\Users\Ni
  khil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_module
  s\ws\build\validation.vcxproj]
            with
            [
                T=v8::Object
            ]   C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(462): error C2039: 'NewSymbol'
  : is not a member of 'v8::String' [C:\Users\Nikhi
  l\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\w   s\build\validation.vcxproj]
            C:\Users\Nikhil.node-gyp\0.12.0\deps\v8\include\v8.h(1599) : see declaration of 'v8::String'
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(463): error C2228: left of
  '.As' must have class/struct/union [C:\Users\Nikhil\A
  ppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\b
  uild\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(463): error C2059: syntax error
  : ')' [C:\Users\Nikhil\AppData\Roaming\npm\node_
  modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(475): error C2039: 'NewSymbol'
  : is not a member of 'v8::String' [C:\Users\Nikhi
  l\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\w   s\build\validation.vcxproj]
            C:\Users\Nikhil.node-gyp\0.12.0\deps\v8\include\v8.h(1599) : see declaration of 'v8::String'
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(475): error C2228: left of
  '.As' must have class/struct/union [C:\Users\Nikhil\A
  ppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\b
  uild\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(475): error C2059: syntax error
  : ')' [C:\Users\Nikhil\AppData\Roaming\npm\node_
  modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(477): error C2039: 'GetCurrent'
  : is not a member of 'v8::Context' [C:\Users\Nik
  hil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules
  \ws\build\validation.vcxproj]
            C:\Users\Nikhil.node-gyp\0.12.0\deps\v8\include\v8.h(5223) : see declaration of 'v8::Context'
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(477): error C2227: left of
  '->Global' must point to class/struct/union/generic t   ype
  [C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-cl
  ient\node_modules\ws\build\validation.vcxproj]
            type is ''unknown-type''   C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(475): error C3861: 'NewSymbol':
  identifier not found [C:\Users\Nikhil\AppData\Ro
  aming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\vali
  dation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(477): error C3861:
  'GetCurrent': identifier not found [C:\Users\Nikhil\AppData\R
  oaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\val
  idation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(518): error C2146: syntax error
  : missing ';' before identifier 'request' [C:\Us
  ers\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_
  modules\ws\build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(518): error C4430: missing type
  specifier - int assumed. Note: C++ does not supp   ort default-int
  [C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\
  engine.io-client\node_modules\ws\build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(490): error C2065: 'request' :
  undeclared identifier [C:\Users\Nikhil\AppData\Ro
  aming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\vali
  dation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(490): error C2228: left of
  '.data' must have class/struct/union [C:\Users\Nikhil
  \AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws
  \build\validation.vcxproj]
            type is ''unknown-type''   C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(529): error C2039: 'NewSymbol'
  : is not a member of 'v8::String' [C:\Users\Nikhi
  l\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\w   s\build\validation.vcxproj]
            C:\Users\Nikhil.node-gyp\0.12.0\deps\v8\include\v8.h(1599) : see declaration of 'v8::String'
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(529): error C3861: 'NewSymbol':
  identifier not found [C:\Users\Nikhil\AppData\Ro
  aming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\vali
  dation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(536): error C2039: 'NewSymbol'
  : is not a member of 'v8::String' [C:\Users\Nikhi
  l\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\w   s\build\validation.vcxproj]
            C:\Users\Nikhil.node-gyp\0.12.0\deps\v8\include\v8.h(1599) : see declaration of 'v8::String'
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(536): error C2228: left of
  '.As' must have class/struct/union [C:\Users\Nikhil\A
  ppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\b
  uild\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(536): error C2059: syntax error
  : ')' [C:\Users\Nikhil\AppData\Roaming\npm\node_
  modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(549): error C2039: 'New' : is
  not a member of 'v8::String' [C:\Users\Nikhil\AppD
  ata\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\buil
  d\validation.vcxproj]
            C:\Users\Nikhil.node-gyp\0.12.0\deps\v8\include\v8.h(1599) : see declaration of 'v8::String'
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(550): error C2466: cannot
  allocate an array of constant size 0 [C:\Users\Nikhil\
  AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\
  build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(550): error C2440:
  'initializing' : cannot convert from 'int' to 'v8::Local'
  [C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client
  \node_modules\ws\build\validation.vcxproj]
            with
            [
                T=v8::Value
            ]
            No constructor could take the source type, or constructor overload resolution was ambiguous
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(549): error C3861: 'New':
  identifier not found [C:\Users\Nikhil\AppData\Roaming\
  npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\validation   .vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(555): error C2065: 'uv_work_t'
  : undeclared identifier [C:\Users\Nikhil\AppData\
  Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\va
  lidation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(555): error C2065: 'req' :
  undeclared identifier [C:\Users\Nikhil\AppData\Roamin
  g\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\validati
  on.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(555): error C2448:
  'NanAsyncExecute' : function-style initializer appears to be   a
  function definition
  [C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_mo
  dules\engine.io-client\node_modules\ws\build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(560): error C2065: 'uv_work_t'
  : undeclared identifier [C:\Users\Nikhil\AppData\
  Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\va
  lidation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(560): error C2065: 'req' :
  undeclared identifier [C:\Users\Nikhil\AppData\Roamin
  g\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\validati
  on.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(560): error C2448:
  'NanAsyncExecuteComplete' : function-style initializer appear   s to
  be a function definition
  [C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client
  \node_modules\engine.io-client\node_modules\ws\build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(570): error C2039: 'request' :
  is not a member of 'NanAsyncWorker' [C:\Users\Nik
  hil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules
  \ws\build\validation.vcxproj]
            C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.
  io-client\node_modules\ws\node_modules\nan\nan.h(487) : see
  declaration of 'NanAsyncWorker'
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(571): error C2065:
  'NanAsyncExecute' : undeclared identifier [C:\Users\Nikhil\Ap
  pData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\bu
  ild\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(571): error C2065:
  'uv_after_work_cb' : undeclared identifier [C:\Users\Nikhil\A
  ppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\b
  uild\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(572): error C2146: syntax error
  : missing ')' before identifier 'NanAsyncExecute   Complete'
  [C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine
  .io-client\node_modules\ws\build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(572): error C2059: syntax error
  : ')' [C:\Users\Nikhil\AppData\Roaming\npm\node_
  modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(716): error C2661:
  'v8::Local::New' : no overloaded function takes 1 argument   s
  [C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-clie
  nt\node_modules\ws\build\validation.vcxproj]
            with
            [
                T=v8::String
            ]   C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(769): error C2039: 'AsciiValue'
  : is not a member of 'v8::String' [C:\Users\Nikh
  il\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\
  ws\build\validation.vcxproj]
            C:\Users\Nikhil.node-gyp\0.12.0\deps\v8\include\v8.h(1599) : see declaration of 'v8::String'
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(769): error C2065: 'AsciiValue'
  : undeclared identifier [C:\Users\Nikhil\AppData
  \Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\v
  alidation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(769): error C2146: syntax error
  : missing ';' before identifier 'value' [C:\User
  s\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_mo
  dules\ws\build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(769): error C3861: 'value':
  identifier not found [C:\Users\Nikhil\AppData\Roamin
  g\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\validati
  on.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(817): warning C4267: 'argument'
  : conversion from 'size_t' to 'int', possible lo   ss of data
  [C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engin
  e.io-client\node_modules\ws\build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(829): warning C4267: 'argument'
  : conversion from 'size_t' to 'int', possible lo   ss of data
  [C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engin
  e.io-client\node_modules\ws\build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(832): error C2065: 'value' :
  undeclared identifier [C:\Users\Nikhil\AppData\Roam
  ing\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\valida
  tion.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(840): error C2065: 'value' :
  undeclared identifier [C:\Users\Nikhil\AppData\Roam
  ing\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\valida
  tion.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(840): error C2228: left of
  '.length' must have class/struct/union [C:\Users\Nikh
  il\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\
  ws\build\validation.vcxproj]
            type is ''unknown-type''   C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(858): warning C4267: 'argument'
  : conversion from 'size_t' to 'int', possible lo   ss of data
  [C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engin
  e.io-client\node_modules\ws\build\validation.vcxproj]
  C:\Users\Nikhil\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\
  node_modules\ws\node_modules\nan\nan.h(873): error C2065: 'value' :
  undeclared identifier [C:\Users\Nikhil\AppData\Roam
  ing\npm\node_modules\socket.io\node_modules\socket.io-client\node_modules\engine.io-client\node_modules\ws\build\valida
  tion.vcxproj]
Comment: And the ton of red errors is, if you don't mind to share it?
Comment: They don't fit into the character limit for the question. I've added less than half of them.
Answer: I had the same problem, so I decided to start up a clean Windows 8.1 installation in Hyper-V and step through the process.
What I've come up with:
1) Install Node.js
2) Install git

CLI commands should be executed with administrator rights
Select "Use Git and optional Unix tools from the Windows Command Prompt

3) Upgrade npm to npm 3.x.x (optional step)
Even though you've just installed Node.js it doesn't necessarily mean you have npm in version 3.

CLI commands should be executed with administrator rights
Run npm install -g npm-windows-upgrade in the command line interface.
Run Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force in the command line interface
Run npm-windows-upgrade in the command line interface
Select the newest version and let it install
When it finishes the install run npm --version and make sure it responds with something like 3.x.x

4) Install Python 2.7.x

Go to https://www.python.org/downloads
Click the button to download Python 2.7.x
Run the installer.
Select Install for all users - click next.
Select to install in C:\Python27 - click next

Be sure to select Will be installed on local hard drive in Add python.exe to Path - click next

Finish up the installation

5) Install Visual Studio Express 2013 for Windows Desktop with Update 4
Even if you have another version of Visual Studio installed on your system do install this as well.

Go to http://www.microsoft.com/en-gb/download/details.aspx?id=44914
Select English or some other available language and click Download
Check wdexpress_full.exe and click "Next"
Run the file downloaded. Begin the installation.
If you're unable to start the installation, it means you already have the necessary tools for this step. Abort the installation.

6) Now run npm install --msvs_version=2013 and you should be able to reach the end without node-gyp throwing errors.


What is average tree size?

Question: Suppose that you generate a sequence which stops with prob q at every step or proceeds with prob p. That is you will get bernulli sequence 0 or 10 or 110 or 11...10 with corresponding lengths 1, 2, 3, ... and probabilities $q$, $pq$, $p^2q$, ...
This is a geometric series with average length of $E[len] = 1*q + 2*pq + 3p^2q + \cdots = 1/q$. That is, if prob of failure is 1/5 then we normally will generate 5-digit lists with 5 trials.
Let the randomly generated list be

Now, suppose that 1-labeled nodes, which are considered "real" or "non-terminal", will also have children subtree. That is, once you have generated a list with method above, you generate another list below every 1-node. An example tree generated after the root node above would be (yes, we consider that 3-element list above as a "root")

You see that, in addition to having potentially long nodes, the trees may descend inifnitely downwards. How many trials do we need to generate such a tree?
My simulation experiment demonstrates that the tree blows up at $p \geq 1/2$. That is, random tree generator never ends at such prob of spawning a node. I am curious to know the analytic solution, dependence of avg tree size on p.
Comment: Some essential information seems to be missing.  Exactly what "sequence" are you referring to?  The stopping probabilities?  How does such a sequence "represent a node" of a tree? How many nodes will be generated at each step and with what probabilities? What is the definition of "size"--number of nodes, number of children, depth, number of leaves, ...?
Comment: @whuber Thanks. This motivated me to explain clearly with illustration.
Comment: Thank you for clearing that up.  Here is a simulation in `R` that--if you analyze it--will give you the answer. `tree <- function(p) {if (runif(1) < p) c(tree(p), tree(p), 1) else 0}`. (The output is a postfix representation of the tree.) You can study it by repeating the simulation, as in `p <- 0.4;
x <- replicate(1e4, length(tree(p)));
(c(Expectation=1/(1-2*p), Mean=mean(x), Std.Err=sd(x) / sqrt(length(x))))`
Comment: "How many trials do we need to generate such a tree?" The literal answer is "one".  Presumably, you intend some other meaning. If so, you should be explicit.
Answer: For each node in your tree you have one child with probability $p$ and 0 with probability $q = 1-p$.  Let $X$ be the random variable denoting the number of nodes (including leaves) in your tree.
If the first node has no children then the tree has one node.  If it has two children then the two subtrees are independent and have the same distribution as the original tree. Therefore, conditioned on the first node having two children, the expected number of nodes in the tree is $1 + 2 \mathbb E(X)$ (one original node plus the two subtrees).
Therefore we may write
$$\mathbb E(X) = q + p(1+2\mathbb E(X))$$
which we may rearrange to get
$$\mathbb E(X) = \frac 1{1 - 2p}$$
as long as $2p < 1$.  If $2p \geq 1$ there are no positive real solutions and the tree has infinite expected value.
Comment: It is interesting that you seem have intuitively proven that q$\sum_0^\infty (n+2)p^n = 1 + q\sum_0^\infty (n+1)p^n$, which can be done starting with $1 = q/q = q/(1-p) = q (1+p+p^2 + \cdots) = q((2-1) + (3-2)p + (4-3)p^2+\cdots) = q(2 + 3p + 4p^2 + \cdots) - q(1+ 2p + +3p^2+\cdots)$ in the list case. What is more interesting is your idea that $E = 1 + pE$ does agree with your $E = q + p(1+E)$ because $p+q = 1$ and we get $E = q + p + pE = 1 + pE$. It is like you assume  $E = 1 + pE$, plug it into $E = q + pE$ to get $E = q + p(1+E)$ and get it back, after simplifying the latter ;). Amazing
Answer: A related problem is finding the average depth of such a tree.
Note that if you clip all the leaf nodes in your tree (of which there are n = E(X) = 1/(1-2p) on average), you will get an ordinary binary tree of size n/2 (with 0 1 or 2 children for each node instead of 0 or 2.)
The number of such trees is the Catalan number C((n-1)/2), and the expected depth of the tree grows as ~sqrt(n/2) = O(sqrt(1-2p)). (Trees of other depth have exponentially decaying probability, so it is safe to expect tree size roughly equal to the expected tree size.)

What is average tree size?


Open new activity for searchview when search is clicked

Question: I want to open a new activity whenever the search icon is clicked on the mainactivity. This new activity called SearchableActivity will handle all the relevant search results in the listview. I have followed the steps described in this post.
This is what I currently have:

I want to open up the SearchableActivity when the user enters into SearchView.
Here is what my code looks like:
AndroidManifest.xml
     <activity
            android:name=".MainActivity"
            android:launchMode="singleTop">

            <meta-data
                android:name="android.app.default_searchable"
                android:value=".SearchableActivity" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SearchableActivity"
            android:parentActivityName=".MainActivity">

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />

            <meta-data android:name="android.app.searchable"
                android:resource="@xml/searchable" />
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
        </activity>

MainActivity
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.options_menu, menu)
        val manager = getSystemService(SEARCH_SERVICE) as SearchManager
        (menu?.findItem(R.id.search)?.actionView as SearchView).apply {
            setSearchableInfo(manager.getSearchableInfo(ComponentName(this.context, SearchableActivity::class.java)))

        }
        return true
    }

SearchableActivity
class SearchableActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_searchable)
        Toast.makeText(this@SearchableActivity, "SA created", Toast.LENGTH_LONG).show()
        handleIntent(intent)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (intent !== null)
            handleIntent(intent)
    }

    private fun handleIntent(intent: Intent) {
        if (Intent.ACTION_SEARCH == intent.action) {
            val query = intent.getStringExtra(SearchManager.QUERY)
            Toast.makeText(this@SearchableActivity, "QUERY: $query", Toast.LENGTH_LONG).show()
        }
    }
}

Answer: there is a method that handles option menu item click it is called
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    if(item.itemId == R.id.myItemId){
        startActivity(Intent(applicationContext, searchAcctivity::class.java))
    }
    return super.onOptionsItemSelected(item)
}

this code is written in kotlin, it shouldn't be that different in java just press ctrl + o and it should open a list of override methods search for "onOptionsItemSelected"
Answer: I'm not sure what you're trying to do but you can simply pass in the Search query to the intent of the activity at its creation.
First, add a companion object to your SearchableActivity :
  companion object {
        private const val EXTRA_QUERY = "SEARCH_QUERY"

        fun newIntent(context: Context?, query: String): Intent {
            return Intent(context, SearchableActivity::class.java)
                .putExtra(EXTRA_QUERY, query)
        }
    }

My understanding is that you want to open a new activity with the search query from MainActivity, next thing is handling the intent:
         private fun handleIntent(intent: Intent) {
                if (Intent.ACTION_SEARCH == intent.action) {
                    val query = intent.getStringExtra(EXTRA_QUERY)
                    Toast.makeText(this@SearchableActivity, "QUERY: $query", Toast.LENGTH_LONG).show()

            SearchableActivity.newIntent(this, query)
    }
  }

..et voila.


How to match string values of datetime format in both Jquery and PHP?

Question: For example -
In Jquery using the function (new Date()).getTime() am getting current datetime as 1470291303352.
But In PHP using strtotime(date('H:i:s')) am getting it as 1470291299.
Here i need to get the same string values. How to do it?
Comment: @madalinivascu Updated.
Answer: Firstly, php returns the number of seconds since 1970/01/01, jquery returns a number of milliseconds, so there is no way to be the same value.
Second - even if you've got the fastest server in the world it comes to the milliseconds in the execution of lines of code. So exactly the same value can hardly be achieved :)
What you can do to try to trim jquery for the last three numbers representing the milliseconds (this of course if you do these two lines of code to execute in one second :))
And for last, there is a issue of clocks on your server and client computer - it must be exactly the same.
Answer: The javascript method getTime() returns microseconds (http://www.w3schools.com/jsref/jsref_gettime.asp) whereas PHP time() (or in your case strtotime() http://php.net/manual/en/function.strtotime.php) returns seconds. The first depends on your clients clock, the latter on your servers clock...
Mostly you never will get the same timestamps this way... maybe you could work around using some kind of AJAX api to have the same timestamp on both sides...
Answer: Check this :
In php:
echo strtotime(date('H:i:s')); // 1470294647

In Script :
var date = new Date();
var d = Date.parse("'"+date+"'")/1000;   // 1470294647
alert(d);


Can i run Ubuntu WSL2 on a VPS which runs Windows Server 2022 Datacenter

Question: I want to use a 8GB RAM, 4 VCore VPS Server which my hoster Contabo  offers with Windows Server 2022 Datacenter image.
This is for a build server that should generate executables for Windows and Linux. Cross compilation is an always buggy and messy hell so i want to use WSL2 on this system to do the Linux builds too and save the money and energy/CO2  for just another VPS.
Is this possible? What with other solutions like virtual box? Do they allow nested virtual machines with different operating systems?
Answer: Make sure that your hoster supports nested virtualization. WSL2 and VitrualBox will work on the virtual Windows 2022


Laravel 4 blade templates causing FatalErrorException?

Question: I'm getting an unexplained FatalErrorException when trying to implement a simple page layout using blade templating. I'm not sure if it's something I'm doing wrong or Laravel is. I'm following the tutorial on L4's documentation about Templating and my code seems to follow it. Here's my code.
app/routes.php:
<?php
Route::get('/', 'HomeController@showWelcome');

app/views/home/welcome.blade.php:
@extends('layouts.default')
@section('content')

Hello World!

@stop

app/views/layouts/default.blade.php:
<!doctype html>

    <title>The Big Bad Barn (2013)</title>

      @yield('content')

app/controllers/HomeController.php:
<?php
class HomeController extends BaseController {
  protected $layout = 'layouts.default';
  public function showWelcome()
  {
    $this->layout->content = View::make('home.welcome');
  }
}

Laravel just throws a FatalErrorException. The output error page says "syntax error, unexpected '?'". The file blade is generating inside the storage/views directory has PHP where the

<?php echo $__env->make('layouts.default')

<?php $__env->startSection('content', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>; ?>

Hello World!

<?php $__env->stopSection(); ?>

Comment: Can you add a blank line after the `@extends` line?  It looks like the `?>` that should be on the first line has ended up on the 3rd line.
Answer: Yesterday I encountered the same problem you did, however the other answers didn't fix my problem. You've probably figured it out already, but maybe this post prevents others from spending as much time as I did figuring out what is wrong while it's such a small (but frustrating!) thing.
I'm using Notepad++ as text-editor and for some strange reason it had decided to use "MAC format" as the End-Of-Line (EOL) format. Apparently the Blade framework can't cope with that. Use the conversion function (in notepad++ : Edit -> EOL Conversion) to convert to Windows Format and it will work just fine..
Comment: Wow, thank you SO much. You just saved our team a day of work!
Comment: I am unable to fix it. I am using phpstorm.
Answer: Eric already gave the right answer, I just wanted to add that if you want to use
protected $layout = 'layouts.default';

in your HomeController, then leave showWelcome action intact and remove this line
@extends('layouts.default')

from welcome.blade.php file. That should work too.
Regards,
Vlad
Answer: Your controller should be just returning View::make("home.welcome") instead of attaching it to the layout.
The welcome view then calls the layout so the controller is only concerned about the body template in this case.
Edit for showing example controller:
class HomeController extends BaseController {
  public function showWelcome()
  {
    return View::make('home.welcome');
  }
}


Partial derivatives from two or more data points

Question: Let's say that I have some function $z = f(x,y)$.
I know that if I want to calculate the partial derivatives of $x$ and $y$ numerically that I can use finite differences, like the central differences method below:
$$\frac{dz}{dx} = \frac{f(x+\varepsilon, y) - f(x-\varepsilon,y)}{2*\varepsilon}\\
$$
and
$$
\frac{dz}{dy} = \frac{f(x, y+\varepsilon) - f(x,y-\varepsilon)}{2*\varepsilon}$$
However, let's say that I have two (or more) triplets of $z=f(x,y)$.  Like say $2 = f(4,5)$ and $3=f(8,2)$.  Can I use that information to estimate partial derivatives?
My attempt at a guess on how to do this would be:
$$\frac{dz}{dx} = \frac{3-2}{8-4} = \frac{1}{4}$$
and
$$\frac{dz}{dy} = \frac{3-2}{2-5} = \frac{1}{-3}$$
Is that method valid? Are there better ways? What sort of accuracy can I expect?
Answer: From two points separated by a vector in the direction $\hat{u}$, the best you can do is to estimate $\hat{u}\cdot \nabla f$.
Using more points you can indeed estimate the partial derivatives (as lnog as the set of sample points is not co-linear). One way to do that is by a weighted least-squares fit to a linear function that approximates $f$; the weighting should emphasize the points near to the point at which you need the gradient.  In one dimension, the central difference method is equivalent to fitting to a line, using zero weighting on all but the nearest two points.
This is somewhat of an art, and numerical calculation of derivatives is trickier than numerical integration. For example, if you are allowed to choose the points for evaluation, then moving far from the desired point leave you vulnerable to the effect of higher derivatives, while moving too close leaves you vulnerable to arithmetic precision effects from subtracting two nearly-equal quantities.
Answer: $dz = \frac {\partial z}{\partial x} dx + \frac {\partial z}{\partial y} dy$
If you have 3 pairs of (x,y) you can find the vectors $\mathbf u = (x_1-x_0, y_1-y_0), \mathbf v = (x_2-x_0, y_2-y_0)$
$\frac {\partial z}{\partial \mathbf u} = \frac {z(x_1,y_1) - z(x_0,y_0)}{\|\mathbf u\|}\\
\frac {\partial z}{\partial \mathbf v} = \frac {z(x_2,y_2) - z(x_0,y_0)}{\|\mathbf v\|}$
There exists some $a,b$ such that $a\frac {\mathbf u}{\|\mathbf u\|} + b\frac {\mathbf v}{\|\mathbf v\|} = (1,0),$ and $m,n$ such that $m\frac {\mathbf u}{\|\mathbf u\|} + n\frac{\mathbf v}{\|\mathbf v\|} = (0,1)$
$\frac {\partial z}{\partial x} = \frac {a \frac {\partial z}{\partial \mathbf u}+ b\frac {\partial z}{\partial \mathbf v}}{\sqrt {a^2+b^2}}\\
\frac {\partial z}{\partial y} = \frac {m \frac {\partial z}{\partial \mathbf u}+ n\frac {\partial z}{\partial \mathbf v}}{\sqrt {m^2+n^2}}$
if $\|\mathbf u\|,\|\mathbf v\|, \sqrt {a^2+b^2},\sqrt {n^2+m^2}$ are large the errors in your estimates increase.


JSON google geocode API get country

Question: I have a JSON: http://maps.googleapis.com/maps/api/geocode/json?latlng=49,19&sensor=false
and I need get only short_name of country. (For this example 'SK').
Therefore I get the short_name which the attribute "types" contains [ "country", "political" ].
I have...
 data.results[0].address_components

thanks.
Answer: This will loop through the address components and look for the country type then political. If you only want the country to be returned if both appear then let me know. Although its not hard to modify this code as the main helping point was the for loop.
// extract country short name (e.g. GB for Great Britain) from google geocode API result
function getCountry(addrComponents) {
    for (var i = 0; i < addrComponents.length; i++) {
        if (addrComponents[i].types[0] == "country") {
            return addrComponents[i].short_name;
        }
        if (addrComponents[i].types.length == 2) {
            if (addrComponents[i].types[0] == "political") {
                return addrComponents[i].short_name;
            }
        }
    }
    return false;
}

console.log(getCountry(data.results[0].address_components));

Answer: <?php
$address = '77-379 North End road, London London SW61NP, United Kingdom'; // Your address(Please USe exist address)
$prepAddr = str_replace(' ','+',$address);

$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&key=API_KEY&sensor=false');
$output= json_decode($geocode);

if ( isset($output->results) ) {
    if ( isset($output->results[0]) ) {
        if ( isset($output->results[0]->address_components) ) {
            foreach ($output->results[0]->address_components as $key => $value) {
                if ( isset($value->types) ) {
                    if ( isset($value->types[0]) ) {
                        if($value->types[0] == 'country'){
                            print_r($value->short_name); //GB
                        }
                    }
                }
            }
        }
    }
} ?>

Comment: You should add some context to your answer so readers may understand better, instead of just the code snippet.
Answer: This one is to look for the address, city name, and Province
200 Dufferin St, Toronto, ON
geocoder.geocode(function (responses) {
    res = responses[0].address_components[0].short_name.concat(' ')
        .concat(responses[0].address_components[1].short_name).concat(', ')

    for (var i = 0; i < responses[0].address_components.length; i++) {
        if (responses[0].address_components[i].types[0] == "locality") {
            res = res.concat(responses[0].address_components[i].short_name).concat(', ');
        }
    }

    for (var i = 0; i < responses[0].address_components.length; i++) {
        if (responses[0].address_components[i].types[0] == "administrative_area_level_1") {
            res = res.concat(responses[0].address_components[i].short_name);
        }
    }
    alert(res);
});

JSON google geocode API get country


How to use unique validation a column name

Question: I have a profiles table and I have a mobile column name.
I want to validate unique mobile name.
    $validator = $request->validate([
        'phone' => ['required','unique:profiles,mobile',new CheckMobile],
    ]);

my client sending phone parameter.
but it doesn't check unique column.
Answer: If you are using Laravel version 6 or higher try using a model name space instead of a table name
$validator = $request->validate([
    'phone' => ['required','unique:App\Models\Profile,mobile'],
]);

or try this
use Illuminate\Validation\Rule;

$validator = $request->validate([
    'phone' => [
          'required',
          Rule::unique('profiles','mobile'),
     ]
]);

Answer: Use | instead of ,:
Check docs:
Writing The Validation Logic
$this->validate($request, [
    'phone' => 'required|unique:profiles'
]);


How to enable excel export button for jqGrid

Question: Hello
I want to show "export to excel" button in the pager of jqgrid. I tried many ways, read many articles/posts, but I don't see this button. Documentation does not have anything useful too. Which actions should I do to see this button
Ps. I use ASP.NET MVC
PSS. my code is
<link href="../../Scripts/jquery.UI/css/redmond/jquery-ui-1.8.1.custom.css" rel="Stylesheet"
    type="text/css" />
<link href="../../Scripts/jquery.jqGrid/css/ui.jqgrid.css" rel="Stylesheet" type="text/css" />

but I don't see the excel import button.
http://ru.magicscreenshot.com/jpg/t97BDzCIO0Q.html
why?
Answer: Assuming markup of

Something along the lines of
$('#grid')
    .jqGrid({
             datatype: "clientSide",
             height: 190,
             colNames: headers,
             colModel: model,
             multiselect: true,
             pager: '#pager',
             pgbuttons: false,
             pginput: false,
             caption: "Random Data",
             deselectAfterSort: false,
             width: 930
    })
    .jqGrid('navButtonAdd',
            '#pager',
            {caption:" Export to Excel ",
            buttonicon:"ui-icon-bookmark",
            onClickButton: genCSV, position:"last"});

genCSV will be  a JavaScript function that will make the call to the controller action to generate a CSV file.
Here's an example, in combination with jQuery flot. Create some data, select some grid rows and then click the generate graph button in the bottom left of the grid to plot the points. Note that this will not work in Internet Explorer less than 8 as it requires support for the HTML 5 canvas element (and I haven't bothered to include excanvas).
EDIT:
Your markup is not working because you need to initialize a navGrid before being able to set a custom button (see note on page). You can do this like so
jQuery(document).ready(function () {
    jQuery('#EmployeeTable').jqGrid({
        url: '/Employee/EmployeeData',
        datatype: "json",
        mtype: 'POST',
        jsonReader: {
            page: "page",
            total: "total",
            records: "records",
            root: "rows",
            repeatitems: false,
            id: ""
        },
        colNames: ['Id', 'Имя', 'Фамилия', 'Email', 'Date'],
        colModel: [
        { name: 'Id', width: 20 },
        { name: 'FirstName', width: 105 },
        { name: 'LastName', width: 100 },
        { name: 'Email', width: 150 },
        { name: 'Date', width: 150, formatter: ndateFormatter }
        ],
        pager: '#EmployeeTablePager',
        excel: true,
        viewrecords: true
    })
      /* Need to initialize navGird before being able to set any custom buttons */
      .jqGrid('navGrid', '#EmployeeTablePager', {
        add: false,
        edit: false,
        del: false,
        search: false,
        refresh: false
    }).jqGrid('navButtonAdd',
    '#EmployeeTablePager',
    { caption: " Export to Excel ",
        buttonicon: "ui-icon-bookmark",
        onClickButton: genCSV, position: "last"
    });
});
function genCSV() {
    alert('a');
}

function ndateFormatter(cellval, opts, rwdat, _act) {

    var time = cellval.replace(/\/Date\(([0-9]*)\)\//, '$1');
    var date = new Date();
    date.setTime(time);
    return date.toDateString();
}

Comment: the same result :( any ideas more?
Comment: @user285336 - it is working, take a look here - http://jsfiddle.net/russcam/7H3xC/ the only thing that I've changed is to replace the AJAX to fetch data with 'clientSide', but you can see the button is there
Comment: do copy/paste to my new test page - does not see excel import button!!! Why it can be? Maybe js/css files? Which files do you include?
Comment: I have set the following paragraphs during download jqgrid http://ru.magicscreenshot.com/jpg/mRKpgs9hjk4.html and http://ru.magicscreenshot.com/jpg/dW4IxbEQK0Y.html . Version of jqgrid 3.8.2
Comment: I have included all modules, download and it works!!! documentation is invalid, says only "Import/Export" and "XML/JSON" modules
Comment: how do I disable the export feature?
Answer: What I did was to create a csv file on the server and display a download link next to the grid in my view.
It's not as slick as what you have in mind but it is quick and easy to implement.
Extension method to create a csv file from a list (from another post on SO):
    public static string AsCsv<T>(this IEnumerable<T> items)
                                     where T : class
    {
        var csvBuilder = new StringBuilder();
        var properties = typeof(T).GetProperties();
        foreach (T item in items)
        {
            //string line = properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray().Join(",");
            string line= string.Join(", ", properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray());
            csvBuilder.AppendLine(line);
        }
        return csvBuilder.ToString();
    }

    private static string ToCsvValue<T>(this T item)
    {
        if (item is string)
        {
            return string.Format("\"{0}\"", item.ToString().Replace("\"", "\\\""));
        }
        double dummy;
        if (double.TryParse(item.ToString(), out dummy))
        {
            return string.Format("{0}", item.ToString());
        }
        return string.Format("\"{0}\"", item.ToString());
    }

Controller:
            model.AListOfData.ToArray().AsCsv();

            using (StreamWriter sw = System.IO.File.CreateText(errorFilePath))
            {
                sw.Write(values);
            }

            model.ErrorFullFileName = errorFilePath;

In the view:
<%=Html.ImageLink("", "AssetUpload", "DownloadErrors", "/?filename=" + Model.ErrorFullFileName, "/Content/Icons/excel.png", "Download errors and warnings", "imagelink")%>

Answer: I used this and it works pretty well
            jQuery("#table_resultats").jqGrid('navGrid', "#yourpager").jqGrid( //#pager
            'navButtonAdd', "#yourpager", {
            caption : "Excel export",
            buttonicon : "ui-icon-arrowthickstop-1-s",
            onClickButton : null,
            position : "first",
            title : Excel export,
            cursor : "pointer"
        });


InsertButton Probleme redirection to other page

Question: I would like to put an Add button to my table.
I use "insertRow" in BootstrapTable, in otpions I put "insertBtn: createCustomInsertButton"
And in the createCustomInsertButton function, I have customized my button and I wish that when clicked it redirects to another page.
    render() {
        {
            console.log(this.props.store.environnements.length)
        }
        return (

                <BootstrapTable selectRow={selectRow} data={this.props.store.environnements} options={options} deleteRow insertRow
                                pagination striped hover condensed>
                    <TableHeaderColumn isKey={true} dataField="id" hidden={true}>ID</TableHeaderColumn>
                    <TableHeaderColumn dataField='nom' filter={{type: 'TextFilter'}}>Nom</TableHeaderColumn>
                    <TableHeaderColumn dataFormat={buttonFormatter}>Action</TableHeaderColumn>
                </BootstrapTable>

        );
    }

const options = {
    deleteBtn: createCustomDeleteButton,
    insertBtn: createCustomInsertButton
};

function createCustomInsertButton() {
    return (
        <InsertButton
            btnText='Ajouter'
            btnContextual='btn-success'
            className='btn-list btn-success-maif'
            btnGlyphicon='glyphicon-edit'
            onClick={test()}
       />
    );
}

function test() {
    return (
        <Redirect to='/environnement/add'></Redirect>
    );
}

Comment: What is your question? What have you tried? What error messages are you getting?
Comment: I'm trying to redirect from the button
Currently I tried with the function test in the "OnClick"
Comment: my error : Uncaught Invariant Violation: Expected `onClick` listener to be a function, instead got a value of `object` type.
Answer: Provided everything above the createCustomInsertButton definition works the way you'd expect, onClick expects a function. Your code instead calls a function, so whenever createCustomInsertButton is invoked, test is too.
Instead, pass the function to onClick (no parentheses):
onClick={test}

From the React docs:

With JSX you pass a function as the event handler, rather than a string.

React Handling Events Docs
Comment: I have no more mistakes using this.
However, my redirection does not work
Comment: Could you be more specific? What have you tried? What error messages are you getting?
Comment: I changed the "Onclick", and I tried to click on the button, I get no error but the redirection does not work
Comment: Is `/environnement/add` supported by your router? What happens if you visit it directly (typing it straight into your browser bar and hitting enter)?
Comment: When I go to the url /environment/add my page is displayed
Comment: it works thank you ! i use  and insert
Answer: Use
 onClick = { () => test() }

or
onClick = { test }

If you have a SPA, you should use the Link from react-router
import { Link } from 'react-router-dom'

<Link to="/page"> Page </Link>

Comment: it works thank you ! i use  and insert


How can I get all related entities of a node programmatically?

Question: I am writing some drush scripts and find myself needing to get related entities (nodes) of the current node. However I can only find info for constructing views that do this.
Can anyone tell me is there a programmatic way to pull all entities that relate to the current nid with a filter on the entity type?
Ultimately I need to get a list of node ids that relate to the current node id.
The relationship depend on the relation module.
Comment: You should mention how your nodes are related to one another to get the answer you're looking for. For example, are you using the Relation or Entity Reference module?
Comment: @shawn-conn Good point. It's using the Relation module.
Comment: To me it would be a `db_query`  (through a script, module or theme)  including the reference field and the row result would return the `entity_target_id`
Comment: @mchar It is looking that way. I'm writing some not so efficient queries to the field_data_endpoints table that seem to be delivering good results.
Answer: Like this, you will get all the referenced items of the node being displayed.
<code>  $current_path = explode('/', $_GET['q']);
  if ($current_path[0] == 'node' && is_numeric($nid = $current_path[1])) {
    $field = 'my_field';
    $bundle = 'my_bundle';
    $query = db_query("SELECT {$field}_target_id FROM field_data_{$field} WHERE entity_id = :nid AND bundle = :bundle",
      array(
        ':nid' => $nid,
        ':bundle' => $bundle,
      )
    );
    foreach($query as $row) {
      $target_ids[] = $row->{$field . "_target_id"};
    }
    $nodes = node_load_multiple($target_ids);
  }
</code>
If you have more entity reference fields, you have to expand the query (with more joins) according to your fields.
Comment: I am writing some drush scripts so I don't have the current path. Also I think to find the related nodes you only really need to query the "field_data_endpoints" table when all your content it related via the relations module.
Comment: The current path can be anything, this is just an example, to your script it could be another query fetching all `nids`. The `node` table isn't needed, yes.