Create a new node when a field is added to a node

Question: How can a element (say an image) that is entered as a field (when creating a new node), also be created as a separate new node at the same time (either through copying the image or by referencing it)?
Comment: i know a way, but first just let me know why would you want that in the first place?!
Comment: Because that piece of content is relevant not only as a field content type X - but as a node of content type Y as well
Comment: what would the title of this sepearate new node Y be? the same title as node of x?
Answer: Option A
I myself wouldn't do that - I think that generally it's a practice that doesn't worth the time and risks (as would be explained in Option B) but anyway:
In drupal 7 this can be done with the Multi Node Add module. There isn't a version for Drupal 8 yet; If you don't have the knowledge to port it to Drupal 8 you might hire a PHP programmer to do that for you. An alternative would be to copy the desired fields from 1 node to another via this module. This module is going through a porting process at this era.
Guessing that both modules work only on 1 content type at a time, and can't recreate content in another Content type: You could handle that by cloning your nodes inside the same content type (X) with Node Clone or a similar module, and than convert all clones to their other, similar content type (Y) with Node Convert or a similar module.
Option B - Advice and workaround with Views.
As an SEOer, I would recommend on finding other way to enrich your sites' content; Cloned content is quite a good recipe for lowering both your PQS (Page quality scores) and in some cases - Your PageRanks as well... This becomes more serious with every passing year.
It could be better to create more sophisticated content pieces based on the first node content via the Views module (which is part of the Drupal 8 core); Here is an intro to Views 8. Many tutorials are available in Youtube for that module.
Comment: The possible problem with Multi Node Add and Node Clone is that they probably work only if they are in the same content type **(never used them, just guessing based on module descriptions)**. Unfortunately, oper wants node from content type x to node of content type y.
Comment: I've edited my answer according to your blessed comment.


PyTorch: Perform add/sub/mul operations using 1-D tensor and multi-channel (3-D) image tensor

Question: Note: I am looking for the fastest/optimal way of doing or improving on this, as my constraint is time
Using PyTorch, I have an image as a 3D tensor, lets say of dimension 64 x 400 x 400, where 64 refers to channels and 400 is the image dimensions. With this, I have a 64 length 1D tensor, all with different values, where the intention is to use one value per channel. I want to use a value per 1D tensor to apply to the entire 400x400 block of the channel. So for example, when I want to add 3d_tensor + 1d_tensor, I want 1d_tensor[i] to be added to all 400x400 = 160000 values in 3d_tensor[i], with [i] ranging from 0 to 63.
What I previously did:
I tried doing it directly, by using the operators only:
output_add = 1d_tensor + 3d_tensor

This returned an error that the dimension of 3d_tensor (400) and 1d_tensor (64) are incompatible.
So my current form is using a for loop
for a, b in zip(3d_tensor, 1d_tensor):
   a += b

However at one stage I have four different 1D tensors to use at once in either addition, subtraction or multiplication, so is this for loop method the most efficient? I'm also planning on doing it 20+ times per image, so speed is key. I tried maybe extending the 1d tensor to a dimension of 64 x 400 x 400 also, so it could be used directly, but I could not get this right using tensor.repeat()
Answer: You should add some dimension to the 1D array: convert from 64 to (64 x 1 x 1):
output_add = 1d_tensor[:, None, None] + 3d_tensor

with this None type indexing you can add dimension any where.
The [:, None, None] will add two additional dimension to the 1D array after the existing dimension.
Or you can use view for the same result see:
output_add = 1d_tensor.view(-1, 1, 1) + 3d_tensor

The result has the same dimension as the 3D array: (64, 1, 1). So the pytorch can use broadcasting.
Here a good explanation for broad casting: How does pytorch broadcasting work?
Comment: Thank you. This worked, and the timing decreased from 200ms to 110ms


Declare two fields of a struct as mutually exclusive in CueLang?

Question: I want to ensure that my users only set one of two fields:
rotations:
  - type: weekly
    time_restrictions:
      # Allow only ONE of the following fields:
      weekday_time_of_day: {...}
      time_of_day: [...]

I came across the OneOf pattern on Cuetorials, but this does only seem to help when wanting to enforce a schema while writing cue files.

#OneOfTimeRestrictions: {time_of_day: [...string]} | {weekday_time_of_day: [...string]}

rotations: [{
    type:         *"weekly" | "daily"
    restrictions: #OneOfTimeRestrictions | {} // won't work, naturally, because nothing is "chosen"
}]

(The values of the mutually exclusive fields are actually additional, more complex structs, not strings, in case that might matter - but for the sake of a shorter example I've omitted them.)
However, I'm trying to vet YAML instead.
The problem is that when defining this:
#OneOfTimeRestrictions: rotations: [{
    type:         *"weekly" | "daily"
    restrictions: {time_of_day: [...string]} | {weekday_time_of_day: [...string]}
}]

Both fields are acceptable, including when giving them at the same time.
Pointers?
Answer: Not a cue expert but,
in CUE {} can be a closed or an open structure depending on the context.
#A: {} is a closed schema, meaning you can't add new field to it.
While B:{} is an open value where you can add new field to it.
#A:{}
a: a & {someKey: true} // will produce an error

B:{}
b: b & {someKey: true} // will pass

_C:{}
c: _C & {someKey: true} // will pass

(You can test it here: https://cuelang.org/play/?id=XigxaAJ1bcp#cue@export@cue)
(And read more about it here: https://cuetorials.com/deep-dives/closedness/)
So in your first CUE code example, the line restrictions: #OneOfTimeRestrictions | {} says restrictions must match either a closed schema with either a weekday_time_of_day or time_of_day field and nothing else or must match an unclosed {} which will match every non-null object.
In your second code example, you are saying restictions as to match to an open structure that has the weekday_time_of_day field or match to an open structure that has the time_of_day field. So, they are basically identical.
Try it like this
#OneOfTimeRestrictions: {time_of_day: [...string]} | {weekday_time_of_day: [...string]}

#Restrictions: {
    restrictionA: string
    restrictionB: bool
    // ...
    restrictionZ: bool

    #OneOfTimeRestrictions
}

rotations: [...{
    type: *"weekly" | "daily"
    restrictions: #Restrictions
}]

Or if you don't like the additional schema, like this
#OneOfTimeRestrictions: {time_of_day: [...string]} | {weekday_time_of_day: [...string]}

rotations: [...{
    type: *"weekly" | "daily"
    restrictions: {
        restrictionA:     string
        restrictionB:     bool
        // ...
        restrictionZ: bool

        #OneOfTimeRestrictions
    }
}]

But these solutions will make the objects in relations closed. So, you will have deliberately defined every additional restriction.
(I'm not certain why restrictions is close in my second example, but in my test it is closed).
If you need that the objects inside relations are open, you can use something like this:
rotations: [...{
    type: *"weekly" | "daily"
    restrictions: {

        time_of_day: [...string]
        weekday_time_of_day: [...string]

        _tr1: bool | *false
        _tr2: bool | *false

        if time_of_day == [] {
            _tr1: true
        }
        if weekday_time_of_day == [] {
            _tr2: true
        }

        _time_restiction_valid: true
        _time_restiction_valid: (_tr1 && !_tr2) || (!_tr1 && _tr2) // append '|| (!_tr1 && !_tr2)' if you want to allow that nither can be set
    }
}]

Comment: Ha! I wasn't fully aware of how closed/open structs work, it seems. That makes a lot of sense. I was wondering why my schema seemingly matches anything I throw at it.
Comment: In your second example, `restrictions` is closed because it embeds `#OneOfTimeRestrictions`, which is closed. See the [spec on embedding](https://cuelang.org/docs/references/spec/#embedding), specifically: "if an embedding resolves to a closed struct, the corresponding enclosing struct will also be closed"


Major module update with Composer

Question: I have some modules in 8.8.5 that need an major update.
What is the best practice without loosing data or settings?
For example:
drupal/admin_toolbar          1.27.0          2.2.0

Do I need to uninstall the module in de admin backoffice Drupal?
If so, I first need to uninstall both modules: Required by: admin_toolbar_tools, adminimal_admin_toolbar
Finally uninstall admin_toolbar
Composer remove drupal/admin_toolbar
Composer require drupal/admin_toobar
Drush updatedb
Drush cr

Is that the correct way?
Or can I simply remove the old version with composer and require the new one?
Comment: `composer update` is the simpler way, if there aren't issues with updating the other modules. Once the code is updated, you can visit update.php, after being sure you are logged in as administrator.
Answer: No you don't uninstall the module first. You want to have the module enabled when updating to let possible database updates kick in. Which may be performed to update existing data/entities. If you already have the latest 1.x version installed you could simply do

$ composer require drupal/admin_toolbar to upgrade the module.
$ drush cr && drush -y updb to perform database updates.
And finally $ drush -y cex to export any eventually updated config.

If you don't have the latest 1.x version installed yet, it's better to upgrade incrementally. And to play really safe to also do two consecutive releases for that.

$ composer update drupal/admin_toolbar --with-dependencies && drush cr && drush -y updb && drush -y cex to first update to the latest 1.x version, followed by a release.
And then $ composer require drupal/admin_toolbar && drush cr && drush -y updb && drush -y cex to get the latest major upgrade, followed by another release.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/107911/discussion-between-leymannx-and-lance).
Comment: @ anyone why do we need --with-dependencies for composer update but not for composer require ?
Comment: @Juc1 – For the [require](https://getcomposer.org/doc/03-cli.md#require-r) command it's `--update-with-dependencies` or `--update-with-all-dependencies`. Sounds clever to use that combination. Try it out and let us know.

Major module update with Composer


Perform Get request with body - Node js

Question: I'm trying to perform a GET request to elastic search api
which is needed in this form
GET /_search
{
    "query": {
        "more_like_this" : {
            "fields" : ["title", "description"],
            "like" : "Once upon a time",
            "min_term_freq" : 1,
            "max_query_terms" : 12
        }
    }
}

I used request
But I can't find how to add body to the request.
Any help?
Answer: You can see the document about request(options, callback)
Also, GET method should't send any body, please confirm it's not POST.
request.get('http://localhost:8092/_search', {
  json: true,
  body: {
    "query": {
        "more_like_this" : {
            "fields" : ["title", "description"],
            "like" : "Once upon a time",
            "min_term_freq" : 1,
            "max_query_terms" : 12
        }
    }
  }
})

Comment: API is really GET method, it's works but weird. https://www.elastic.co/guide/en/elasticsearch/reference/6.3/_the_search_api.html
Comment: yes the GET request not recommended with body but it's happened :D
BTW i was missing the `json: true,`
Comment: More about `GET` with body at this thread: https://stackoverflow.com/questions/978061/http-get-with-request-body
Answer: If you use GET, you can't have body, you just have query.
You can convert your query to string and add to your url, or use option with qs:
option = {
    url: 'your_url',
    qs: your_query
};
request(option, (error,res)=>{});

If want use body, you should use POST.
Answer: Hi have you tried simply passing your body as a second argument to your request?
request.get('yourEndpoint', { // your body })

Comment: i did it before but it was missing a param
Answer: You can not add body to a get request, you will have to add a query string for the request to send those data.
Comment: GET can take body with the request, Thanks for your effort.

Perform Get request with body - Node js


What hardware specs is needed to serve 100,000 clients on OpenVpn?

Question: Serving vpn clients (tcp connections) with OpenVpn server relies on what ? Or how can we calculate the clients count with hardware specs ?
Does it rely on server bandwidth speed, like if we have a server with 1 GB (1024MB/PS) we can serve 1024 user (every user can get 1MB)? Or something else?
Answer: We can't properly answer capacity planning questions since they are highly dependent on your actual use cases and usage patterns.
The vendor documentation more or less says the same:

CPU requirements are very difficult to specify because of the wildly different requirements and use-cases.
...
Memory requirements are highly dependent on the amount of connected devices, and how much NAT traffic you're doing.

But comes with some extremely rough guidelines for a first approximation :
CPU

As a rule of thumb you should assume that on a modern CPU with AES-NI chipset, for every megabit per second of data traffic (in one direction) you need about 20MHz.

To saturate your gigabit uplink that would be  (1 up + 1 down) * 1000 megabit * 20 Mhz = 40'000 Mhz
That is about 20 cores worth of a modern CPU's
Memory

if your users are only accessing resources on your private network 500 megabytes of memory per 100 connected devices. ...  If your users route all their Internet traffic through the VPN server, double that to 1000 megabytes per 100 connected devices.

That would mean a terabyte of RAM for 100'000 concurrently connected devices.
(Both in addition to whatever your OS requires.


Error rendering static html

Question: This code:
<code>var app = require('express').createServer();
var ejs = require('ejs');
var fs = require('fs');
var indexTemplate = fs.readFileSync(__dirname + '/templates/index.html');

app.get('/', function(req, res){
    res.end(ejs.render(indexTemplate, {}));
});
</code>
Gives me the following error

TypeError: Object         Address
               has no method 'substr'
      at Object.parse (/home/lowerkey/node_modules/ejs/lib/ejs.js:152:20)
      at /home/lowerkey/node_modules/ejs/lib/ejs.js:192:13
      at Object.render (/home/lowerkey/node_modules/ejs/lib/ejs.js:235:10)
      at /home/lowerkey/workspace/address book/server/server.js:60:14
      at callbacks (/home/lowerkey/node_modules/express/lib/router/index.js:272:11)
      at param (/home/lowerkey/node_modules/express/lib/router/index.js:246:11)
      at pass (/home/lowerkey/node_modules/express/lib/router/index.js:253:5)
      at Router._dispatch (/home/lowerkey/node_modules/express/lib/router/index.js:280:4)
      at Object.handle (/home/lowerkey/node_modules/express/lib/router/index.js:45:10)
      at next (/home/lowerkey/node_modules/express/node_modules/connect/lib/http.js:203:15)

What am I doing wrong?
Answer: Your indexTemplate variable actually contains buffer instead of string, due to default encoding of the readFile return value. You may want to try to add the encoding in readFileSync 2nd parameter to set it, like the following:
<code>...
var indexTemplate = fs.readFileSync(__dirname + '/templates/index.html', 'utf8');
...
</code>

Error rendering static html


Is there an instrument combination of a guitar and a harp?

Question: I wonder whether there is guitar that is extended with strings like a harp - or otherwise a harp that has inbuilt a neck with frets with guitar strings. Does this instrument exist already and how would you call it?
Answer: This instrument exists and is called:
HARP-GUITAR
Comment: You'll find more if you don't require it to be labelled "harp." https://www.youtube.com/results?search_query=metheny+picasso+guitar


Probability that at the end of the four exchanges, all balls are where they started? [DBertsekas P56, 1.20]

Question:
We have two jars each containing initially $n$ balls. We perform four
  successive ball exchanges. In each exchange, we pick simultaneously and at random a
  ball from each jar and move it to the other jar. What is the probability that at the
  end of the four exchanges all the balls will be in the jar where they started?
Solution:  (Soln uses subscripts) Let $P(i, n - i)[k]$ be the probability that after $k$ exchanges, a jar will contain $i$ balls that started in that jar and $n - i$ balls that started in
  the other jar.
  We want  $P(i, n - i)[4]$. Argue recursively, using the total probability theorem :

I'm flummoxed by this question; I seem to only apprehend $P(1, n - 1)[1] = 1$
. This is because the first ball exchange must transfer one ball from each jar and to the other. Afterwards, each ball must contain $n - 1$ original balls but the $1$ from the other.
Could someone please explicate what's happening? The solution looks terse.
Source: P56, 1.19, An Intro to Pr, 2nd Ed, D Bertsekas
Comment: Try slowly working backwards. So for $P_{n-2,2}(2)$ there is $n/(n-1)$ chance of drawing an original ball from a jar (and $1/n$ chance of getting the alien ball, and that is leading to $p_{n,0}(2)$), and the same factor works for the other jar.
Comment: http://math.stackexchange.com/questions/804491/probability-bertsekas-question
Answer: From the bottom up:
The second swap can hit zero, one or two of the balls swapped by the first swap. There are $(n-1)^2$, $2\cdot1\cdot(n-1)$ and $1^2$ choices for the balls, respectively, and these need to be divided by the total number $n^2$ of choices to get the corresponding probabilities.
For the third swap, we're only interested in the probability that it results in a state with one pair of balls swapped, because that's the only case in which the fourth swap can restore the original state. Again we need to count the number of choices that lead to the desired result: If two pairs are swapped, there are $2^2$ choices that unswap one pair; if one pair is swapped, there are $2\cdot1\cdot(n-1)$ choices that hit one swapped and one unswapped ball, leaving the number of swapped pairs at $1$, and if no pair is swapped, all $n^2$ choices result in one swapped pair.
Answer: I will try to explain each step below:

step (4): pn,0(4) = $\frac{1}{n}$$\frac{1}{n}$ pn-1,1(3)

This is because if you want to be in the perfect state after 4 step, there is only 1 way, which is by having 1 pair of balls swaped at step 3, and then swap those 2 exactly (picking each with probability $\frac{1}{n}$) from each jar.

step (3): pn-1,1(3) = pn,0(2) + 2 $\frac{n-1}{n}$$\frac{1}{n}$ pn-1,1(2) + $\frac{2}{n}$ $\frac{2}{n}$ pn-2,2(2)

To get to right state ready forstep (3), there are 3 ways

you can start from a perfect state in step 2, in that case, you can swap whatever you want and you will only have one pair of balls swapped (getting ready for step 4)
you can start from one pair of misplaced balls in step 2, in that case, you need to maintain in the same state by swapping one misplaced ball with one correctly placed ball. There are two ways to doing it

pick a misplaced ball from first jar (prob $\frac{1}{n}$) and a correctly placed ball from second jar (prob $\frac{n-1}{n}$) and swap them
pick a correctly placed ball from first jar (prob $\frac{n-1}{n}$) and a misplaced ball from second jar (prob $\frac{1}{n}$) and swap them

you can start from two pairs of misplaced balls in step2, in that case, you have to pick one of the misplaced balls (prob $\frac{2}{n}$) from the first jar and one of the misplaced balls (prob $\frac{2}{n}$) from the second jar and swap them

step (2): pn,0(2) = $\frac{1}{n}$ $\frac{1}{n}$ pn-1,1(1)

To get to this state of step 2, we need to revert step 1 by picking exactly the right balls ($\frac{1}{n}$ $\frac{1}{n}$)

step (2): pn-1,1(2) = 2 $\frac{n-1}{n}$ $\frac{1}{n}$ pn-1,1(1)

To get to this state of step 2, we have 2 ways again
- pick a misplaced ball from jar 1 and a correctly placed ball from jar 2, then swap
- pick a correctly placed ball from jar 1 and a misplaced ball from jar 2, then swap

step (2): pn-2,2(2) = $\frac{n-1}{n}$ $\frac{n-1}{n}$ pn-1,1(1)

To get to this state of step 2, we need to generate another pair of misplaced balls by choose the correctly placed balls from jar 1 and jar 2 and swap them

step (1): pn-1,1(1) = 1

To get into the state of one pair of misplaced balls, you can swap any balls from each jar
Note: You can also try to read the steps from bottom to top if that makes more sense to you!


Comparing the ratios of occurrences

Question: There are two groups:

treatment
control.

Each group has three categories of outcomes:

High
medium and
low blood pressure.

The number of subjects is 100 for each group.
Now, let's say, for control group, the number of observations is 40, 40, 20 for high, medium, and low blood pressure, respectively.
And, for the treatment group, the number of observations is 10, 50, 40 for high, medium and low.
What I want to test is whether the ratio of occurrences (High/Low) ignoring the medium is different between these two groups. 2 (=40/20) for control vs. 0.25 (=10/40) for treatment.
What statistical test should I use?
Comment: It's rather late to make this suggestion, but you might bear it in mind for your next experiment.  In order to assess whether blood pressure was high, medium or low, you must have actually measured it and got a result in mmHg.  You would get much better power from such an analysis using the actual blood pressures in mmHg than categorising them.  Additionally, categorising the blood pressures before doing the analysis, presumes you know how to categorise appropriately.  It is quite conceivable that for different treatments different categorisations would be appropriate.
Comment: The approach here seems difficult to justify. Looking at ratios of frequencies is equivalent to considering frequencies on logaritmic scale and that itself points to Poisson regression. But that aside ignoring the medium group when it's part of the measurement protocol and part of the total pattern of variation seems arbitrary. For most readerships (whether you are preparing dissertation, thesis, report, presentation, paper) that's likely to seem somewhere between puzzling and perverse and something you would need to explain and defend at length.
Comment: Thanks all for your answers. Just to let you know, the thresholds for High, Medium, Low were preset before the experiment so there is no hindsight bias. As someone suggested changing these thresholds could change our inferences, but by carefully setting the thresholds that are meaningful to our experiment before the experiment, we avoid the data-snooping issues.
Thanks Jean for your suggestion on using either a randomization test or a bootstrapping method.
Answer: I can't help but ask, why do you want to compare the high/low ratios?  Is this some standard way to assess blood pressures?  Why not use a chi-squared test to compare the groups?  Did you know you were going to conduct this sort of analysis before you saw the data?  Or did you see the data, see the differences in the high and low categories, and decide the best way to show a difference between the groups was to look at the high/low ratio?
If you knew in advance that you wanted to analyze the high/low ratios, then you could use a randomization test or bootstrapping.
For a randomization test, you would randomly assign the 200 subjects to treatment and control groups of 100 subjects each and calculate the difference between the trt hi/lo and the ctl hi/lo.  This random assignment and difference calculation is repeated 1000 times or more, so that you have a distribution of randomly generated differences.  Then you compare the observed difference (1.75) to that distribution and see if it is in the extreme 5% (or whatever alpha) tails.
For bootstrapping, you would randomly select (with replacement) 200 subjects from the full sample of 200 subjects and calculate the difference between the trt hi/lo and the ctl hi/lo.  This random selection and difference calculation is repeated 1000 times or more ... and the rest is similar to the randomization test described above.  (You may want to use a bias-corrected bootstrap.)

Comparing the ratios of occurrences


How can I find values which does not contains characters and spaces?

Question: Below is sample data from the list I am working with:
74
7491
75
75010
75013
78
8081
84
8400 Winterthu
852
9000 Aalborg
974
A
A CORUÑA
aa
Aalborg
Aargau
Aarhus
aas
AAT
AB
ABERC
Abu Dhabi
Abuja
AC
ACT
AD

Using [^\p{L}-] I can get a list but it also includes the following values which I do not want in the list
Abu Dhabi
Puerto Rico
Hong Kong

How can I do this?
Comment: It seems you need `^[^\p{L}-]+$` - strings that do not contain letters and hyphens.
Comment: Please let know if it works, else explain the rules.
Answer: You want to find multiple items, so you must use g option.
You will be checking each line separately. Usual way the pattern
for such case is constructed is ^...$, but both  ^ and $
should match begin and end of each line, not the whole string.
So you must use m option.
And the last point, what should be the accepted content of a candidate
line, i.e. what should be between ^ and $: Any not empty sequence of
letters in any language or literal minus, i.e. [\p{L}-]+.
So, to sum up, the whole regex should be:
/^[\p{L}-]+$/gm

This way names containing a space (e.g. Puerto Rico) will not be matched
(as you specified).
Answer: Say your file is test.dat
A 1 simple line in grep will give wat you want:
grep -o -P  "[0-9]+$" test.dat

Output:
74
7491
75
75010
75013
78
8081
84
852
974


About transformation in linear algebra

Question: I have a confusion about transformation in linear algebra.
Consider a vector(1,1) in x,y coordinate. I have a translation 1 unit upwards.
(x',y') = (1,1) + (0,1)=(1,2)
this means my vector now is in (1,2) in x,y coordinate? or I am in some x',y' coordinate?
If I am in a new coordinate frame x',y', my new vector should be still (1,1)? Since my new coordinate frame x',y' should be also transformed 1 unit upward.
Or this transformation is describing coordinate frame. Then my coordinate frame move 1 unit upwards.
Then my new vector should be (0,-1) in x',y' , but how can I get -1 from the transformation?
Similarly in rotation, I don't quite understand the rotation matrix is rotating the vector or rotating the coordinate frame.
Thank you!
Answer: A Linear Transformation always preserves linearity in the sense that:
$$L(\sum_{i=1}^{n}\alpha_i e_i) = \sum_{i=1}^{n}L(\alpha_i e_i)$$
This is, if you input $x=(x,y)=e_1+e_2=(1,1)$, then $L(x,y)=L(1,1)=L(e_1+e_2)=L(1,0)+L(0,1)$. Then you can visualize the output as a transformation of (x,y), so this vector is $(x',y')=L(x,y)$.
This is, you got two pairs, first the origin or input point $(x,y)$ and the transformation point $(x',y')$. You can either update $(x,y)$ to be $(x',y')$ or maintain $(x,y)$ and $(x',y')$ separated. Of course, the inverse of the linear transformation (if it's a non singular matrix) would return to $(x,y)$ given the point $(x',y')$.

About transformation in linear algebra


How to resolve "Parcel build failed. @parcel/optimizer-terser: "_" is redeclared" error

Question: Good day everyone!
When I tried to build my parcel-based app, I encountered the following error:
Build failed.

@parcel/optimizer-terser: "_" is redeclared

3724 |
  > 3725 | let _ = (t1)=>t1
  >      |    ^ "\_" is redeclared
    3726 | , t;
    3727 | // src/components/visually-hidden/visually-hidden.styles.ts

  ℹ It's likely that Terser doesn't support this syntax yet.

Normally, I would have tried to comb through the console logs to try and debug the issues at hand, but I haven't been able to figure out where to start with this one.
Could someone help guide me in that direction please? Thanks mate!
Answer: For me the issue was a wrong import of styled() method when extending a material ui component:
Was importing:
import { styled } from '@mui/material/styles';

instead of:
import styled from 'styled-components';

and was obviously using the styled-components syntax:
const StyledAutocomplete = styled(Autocomplete) <IStyledAutocompleteP>`
// some css here
`;


Are Greg Irwin's finger fitness exercises really useful to increase guitar players' skills?

Question: I'm wondering: does doing exercises of the book Finger Fitness - The Art of Finger Control by Lorraine C. and Gregory G. Irwin really help to increase finger dexterity and flexibility and is it useful for guitar players as suggested in the description?

You will be able to master your finger control and tune your brain in with the movements of your hands. This hand control is critical if you are a musician or magician in need of delicate and subtle hand/finger movements.

There are also YouTube videos available for some of the exercises.
So I'm wondering: does practicing these exercises really help guitar players?
I'm asking because I want to practice them if they are actually useful.
Comment: Looks like they probably are helpful but it also looks like you could basically get the same finger workout while also learning to play guitar. If you spend a lot of time in situations where you could do these exercises and couldn't play guitar, then maybe they would help without being a waste of time. But I would never put down my guitar to do these exercises, I would just work on guitar exercises.
Comment: I saw the images in the fluteworld link and thought: "Was that the guy I saw on The Tonight Show in the late 80s?"  [Yes, it was.](https://www.youtube.com/watch?v=pDr7NuEcZls)  One thing those exercises are good for is doing the kind of performance he did there.   (Jump to about 7:00.)
Comment: @Theodore I saw the video and it was quite interesting!
Answer: Some guitar players report improvements in their finger control and flexibility after practicing the exercises. The exercises should be used as a supplement to regular guitar practice and performed correctly with proper technique to avoid injury. Seeking guidance from a qualified guitar teacher or hand therapist may be helpful to ensure that you are performing the exercises safely and effectively.
Answer: Yes this is Greg Irwin who appeared on The Tonight Show. The Finger Exercise program is designed as a supplement for your guitar playing.  Of course playing the guitar will exercise your fingers and develop their ability best for guitar.
The exercises are great to do while away from guitar and also as a warmup before playing. Good Luck with your Hands.


How to trigger browser download from Node.JS socket stream?

Question: my node.js app connects through var socket = net.createConnection(port, ip); to download a file from another server. As soon as connection is made the server sends the file as data.
I catch it then by doing
socket.on('data', function(data) {

}).on('connect', function() {

}).on('end', function() {
console.log('DONE');
});

My initial goal is, to download the file using the method above and at the same time give the bytes to the client's browser as a downloadable file. For example: user clicks a button on the site which triggers the server-side download function and the user gets the file-save prompt. Node.JS then downloads the file from the remote server and at the same time gives each new byte to the user at the browser client. Is this possible? I imagine it would need to send headers of octet-stream to trigger file transfer between browser Node.JS. But how?
Update
Now I tried the code below with the help of the answer below:
app.get('/download', function (req, res) {

res.setHeader('Content-disposition', 'attachment; filename=' + "afile.txt");
res.setHeader('Content-Length', "12468")

var socket = net.createConnection(1024, "localhost");
console.log('Socket created.');
socket.on('data', function(data) {

    socket.pipe(res)

}).on('connect', function() {
// // Manually write an HTTP request.
// socket.write("GET / HTTP/1.0\r\n\r\n");
}).on('end', function() {
    console.log('DONE');
    socket.end();
});

 });

The data is being sent to the user's browser as a download, but the end result is a broken file. I checked the contents within and it seeems that something along the process causes the file to corrupt.
I think now I have to write byte per byte? rather than doing socket.pipe?
Comment: You can't do that, but you can receive the whole file in memory using sockets and then make the user download the file using a data URI. Like so: http://stackoverflow.com/questions/3665115/create-a-file-in-memory-for-user-to-download-not-through-server. Streaming the file directly for the user to download however isn't possible using websockets.
Comment: File download is only avaialable over http. That interface is not there for websocket as sending file over it is yet to be standardised. See another similar question http://stackoverflow.com/questions/9871357/receive-file-via-websocket-and-initiate-download-dialog.
Comment: You are mixing on('data') and pipe. Your first chunk of data is lost when you attach `.pipe`
Answer: You need to set content-disposition header in your http response:
  response.writeHead(200, {
    'Content-Disposition': 'attachment; filename=genome.jpeg; modification-date="Wed, 12 Feb 1997 16:29:51 -0500"'
  });
  yourDataStream.pipe(response);

see RFC2183
Comment: The file is being sent over websocket.
Comment: why can't you serve it over http?
Comment: You can but that is not what OP is asking for.
Comment: I don't see reference to websockets in the question. Everything in question is possible via plain old http/ajax
Comment: Sorry, may be you're right. I assumed the code in question that catches file runs on browser. Otherwise you answer it correctly.
Answer: It looks like you may want this:
app.get('/download', function (req, res) {
  res.attachment('afile.txt');
  require('http').get('http://localhost:1234/', function(response) {
    response.pipe(res);
  }).on('error', function(err) {
    res.send(500, err.message);
  });
});

Answer: I found the solution!
by doing res.write(d) i was able to direct the bytes from the other connection to the user browser download.
app.get('/download', function (req, res) {

res.setHeader('Content-disposition', 'attachment; filename=' + "afile.jpg");
res.setHeader('Content-Length', "383790");
res.setHeader('Content-Type','image/jpeg');

var socket = net.createConnection(1024, "localhost");
console.log('Socket created.');
//socket.setEncoding("utf8");
socket.on('data', function(d) {
    console.log(d);
    res.write(d);
}).on('connect', function() {
// // Manually write an HTTP request.
// socket.write("GET / HTTP/1.0\r\n\r\n");
}).on('end', function() {
    console.log('DONE');
    socket.end();
});

});


Get divs from an external file by class name.with jQuery

Question: Sorry if this has been answered before but I searched for hours trying to find how to do what I am trying to do. I know php would probably have an easier solution but php might not an option. Jquery is preferable although pure javascript would be great too.
I'm trying to get divs from an external file by class name. There are multiple divs using the same class name. I want to get all the div of that class put in an array that I can loop through in a later part of the script.
I'm trying keep the contents of the divs of this page synced up to the divs of a page of an external html file that will always be changing. But I'm not sure how best to do this.
I have had good results getting data from csv files into divs in other projects, no problem, but this one has me stymied.
I tried the following (for testing purposes, I was just logging to console). I have confirmed that the external file loads just fine. I can see it load in the Chrome Dev Tools. But the data never really seems to go anywhere after that.
$(document).ready( function() {
    var array = [];
    var testfunc =  $('.test').each(function () {array.push(this.innerHTML);});

    $.get('sharedResources/Bio.html', function(testfunc){
            console.log(array);
                                     });

});

I tried other variations but they were even messier and the script started pulling from classes of the current page instead of the external file. I could see the innerHTML of the current page showing up in the console log.
I'm sure there is a much better way that I'm not seeing.
I also tried something else I saw suggested online but this didn't works either. This gave me 'contents is undefined' error... not to surprised at that one.
$.ajax('sharedResources/Bio.html').done(function(e) {
    $('.test').attr('innerHTML', contents);
});

Sorry if I am not asking this well. I don't often ask anything on these forums.
Thanks!
Answer: Assuming the URL is within the same origin, all you really have to do is
$.get('sharedResources/Bio.html', function(html){
    var elements = $('
', {html: html}).find('.className');
}).fail(console.log);

And note that elements would only be available within that callback functions scope, as it's asynchronous.
Also note the added fail handler, and make sure you open the console and check for errors.
Comment: Yes, the urls are all the same origin. Awesome!!! Thank you sooo much... that worked great! One error I noticed with the close squiggly bracket but after that it worked fine. {html: html should be {html: html}
Comment: Don't forget to mark it as an answer if this helped you.
Answer: I thought it might be useful to someone else searching for this sort of thing to post what I ended up doing.
I used what I learned from adeneo's great suggestion (above) and was totally able to do what I needed to do. Thanks, adeneo
I needed to take team profile info from a bio page that often changes on the site and reuse & rearrange it on another page which needed to always be synced up.
So here is the code I ended up going with:
$.get('Bios.html', function(html){
    var t_name = $('
', {html: html}).find('.t_name');
    var t_creds = $('
', {html: html}).find('.t_creds');
    var t_title = $('
', {html: html}).find('.t_title');
    var t_bio = $('
', {html: html}).find('.t_bio');
    var t_img = $('', {html: html}).find('.t_img');
    var t_imgTn = $('', {html: html}).find('.t_imgTn');

            var arrayLength = t_name.length;

            for (var i = 0; i < arrayLength; i++) {
                $('#name'+[i]).html(t_name[i]);
                $('#creds'+[i]).html(t_creds[i]);
                $('#title'+[i]).html(t_title[i]);
                $('#bio'+[i]).html(t_bio[i]);
                $('#bioImg'+[i]).html(t_img[i]);
                $('#bioTn'+[i]).html(t_imgTn[i]);
                }
            }).fail(console.log);

});

It worked like a charm :-)


Updating A boolean value in MS SQL

Question: I am having a hard time with this one. I can't seem to identify what't wrong. It is not updating my data on vote stat but it updates the vote count..
<code>Dim myreader As SqlDataReader

'  Try

Dim president As New SqlClient.SqlCommand("SELECT * FROM PRESIDENT WHERE name=@name ", con) ' + ComboBox1.Text + "';", con)
president.Parameters.AddWithValue("@name", ComboBox1.Text)
myreader = president.ExecuteReader()

While myreader.Read()
    prevote = myreader.Item("VoteCount")
    prevote = prevote + 1
End While

myreader.Close()

president.CommandText = "Update President set [VoteCount]= " & prevote & " where [Name] ='" & ComboBox1.Text & "'"
president.Connection = con
president.ExecuteNonQuery()
president.Dispose()

Dim LRN As Int64
LRN = TextBox3.Text

Using Stud_Vote_Stat As New SqlClient.SqlCommand("UPDATE Voters SET [VoteStat] = 1  WHERE [VOTERSNAME] = @VOTERSNAME", con)
    Stud_Vote_Stat.Parameters.Add("@VOTERSNAME", SqlDbType.TEXT).Value = TextBox2.R
    Stud_Vote_Stat.ExecuteNonQuery()
End Using
</code>
Comment: That code is replacing a good Parameterized SELECT query with a BAD concatenated UPDATE query.  `Dim rows = myCmd.ExecuteNonQuery()` will tell you how many rows were updated.  You should also use `Add` rather than `AddWithValue`  And a `Using` block would remove the need to close and dispose things.
Comment: `UPDATE Voters SET [VoteStat] = 1 WHERE [LRN] = @LRN`
Comment: Your code doesn't make to much sense. What do you try to do?
Comment: @TeacherAi Then it is likely that AddWithValue is messing up the parameter `@LRN`. What is the type of the `[LRN]` column in the database? What is the type of the LRN variable in your program?
Comment: @TeacherAi You treat `LRN` in your code like it is a string-value. Edited my answer.
Comment: @ZoharPeled I am trying to update the a column VoteStat (datatype is bit) to true so that, the student whose LRN (primary key) can no longer vote in the future because the student already voted. Default vaue is set to false.
Comment: @Plutonix  that code works well if I am updating a voteCount (adding 1 to its value), the datatype is number, but it doesn't seem to work with VoteStat where the data type is bit.
Comment: In my access database, it works well.
Comment: I also tried this code in management studion and works great.

update dbo.voters set VoteStat=~VoteStat where lrn=1
Comment: it doesn't work @AndrewMorton.. I been working on it since 3 hours ago... the value remains false.
Comment: `Dim rows = myCmd.ExecuteNonQuery()` will tell you how many rows were affected
Comment: LRN in Database is bigint...LRN in program is Int64
Comment: I tested this code, UPDATE Voters SET [VoteStat] = 1  WHERE [LRN] = 1" and it works..thank you @AndrewMorton.. I think its the LRN ..my problem now is what should I declare with LRN?
Comment: @MatSnow, I ommitted some because in ask for more details than code. but those are just  for connection and messageboxes.
Comment: Your title says you are attempting to update a boolean, but a comment says the field is a bigint . . is this part of the problem?
Comment: @peterG The value to be set is a "boolean" but the column in the predicate is a bigint.
Answer: The following should work:
<code>'*** This part is presumably not needed
'*** if the "prevote"-variable is needed after the UPDATE,
'*** then use this part
'Dim prevote As Integer
'
'Using president As New SqlClient.SqlCommand("SELECT COUNT(*) FROM PRESIDENT WHERE name=@name", con)
'    president.Parameters.Add("@name", SqlDbType.VarChar).Value = ComboBox1.Text
'    prevote = CInt(president.ExecuteScalar) + 1
'End Using
'
'Using president As New SqlClient.SqlCommand("UPDATE President SET [VoteCount]=@prevote where [Name]=@name", con)
'   president.Parameters.Add("@prevote", SqlDbType.Int).Value = prevote
'   president.Parameters.Add("@name", SqlDbType.Int).Value = Name
'   president.ExecuteNonQuery()
'End Using
'******************************************

'*** Replaces upper part
'*** If VoteCount just should be incremented by 1 everytime,
'*** then use this part
'*** assumes that only one row exists per "name" in table "PRESIDENT"!
Using president As New SqlClient.SqlCommand("UPDATE President SET [VoteCount]=(CASE WHEN [VoteCount] IS NULL THEN 1 ELSE [VoteCount]+1 END) WHERE [Name]=@name", con)
    president.Parameters.Add("@name", SqlDbType.VarChar).Value = Name
    president.ExecuteNonQuery()
End Using
'****************************

Dim LRN As Int64
LRN = CLng(TextBox3.Text)

Using Stud_Vote_Stat As New SqlClient.SqlCommand("UPDATE Voters SET [VoteStat]=1 WHERE [LRN]=@LRN", con)
    Stud_Vote_Stat.Parameters.Add("@LRN", SqlDbType.BigInt).Value = LRN
    Stud_Vote_Stat.ExecuteNonQuery()
End Using
</code>
Comment: You get any exception?
Comment: I think you're also good with the LRN. Maybe the problem was the missing conversion to long. Also wanted to suggest to change data-type of votersname to varchar. ;-)
Comment: `Dim president As New SqlClient.SqlCommand("SELECT COUNT(*) FROM PRESIDENT WHERE [name]=@name", con)` would get that part working with just an ExecuteScalar. As it is, the code is setting `prevote` to the *last* returned value of `[VoteCount]` + 1. I suspect that is not intended.
Comment: @AndrewMorton Yes and probably no. The `SELECT` returns probably only one row everytime. So it worked, but the code still was kind of ugly. If `[VoteCount]` just needs to be incremented by 1 on every run then only one `UPDATE` is necessary. I've edited my answer and added comments.
Comment: sir, it still doesn't work. I should probably change the LRN to the Voters Name.. I'll try if it will work.
Comment: Should not be necessary. I'm asking again, do you get any exception? `it doesn't work`  is not helping much
Comment: The program does not throw any error. When I click the button where this code is being placed, it has no error. But if I enter the LRN again for the second time, the name of the student still shows instead of a message box telling the student that he or she already voted.
Comment: I suspect the problem is somewhere else in your code. Please update your question with all the relevant code of your `Button_Click`-method
Comment: I tried to replace the LRN int64 with the votersname which is text in db. It now throws something, Additional information: The data types text and text are incompatible in the equal to operator. or Additional information: The data types text and nvarchar are incompatible in the equal to operator.
Comment: It is now worki... I change the LRN to voters name and I change the data type of VOtersname in the db to varchar(50).. Thank you so much for helping me :)

Updating A boolean value in MS SQL


Fixed-Do Solfege in A Major scale with accidentals

Question: I am learning solfege by myself and I have a question about reading of notes with accidentals. As far as I studied, There are 2 different ways in solfege, fixed-do and movable-do. There are also variations such as chromatic and non-chromatic.
The image below is A major scale with accidentals.

In movable-do/non-chromatic, it should be:
| do do re re | mi fa fa sol | sol la la ti | do do ti | ti la la sol | sol fa mi mi | re re do |
In movable-do/chromatic, it should be like:
| do di re ri | mi fa fi sol | si la li ti | do do ti | te la le sol | se fa mi me | re ra do |
But I am very confused with Fixed-do. I don't know how to read notes with accidentals. I am not sure but in fixed-do/chromatic should be like:
| la li ti do(?) | di re ri mi | fa(?) fi sol(?) si | la la si | sol fi fa mi | me re di do | ti te la |
Is that correct? Fixed-do/non-chromatic is more complicated. I have no idea whether I should just ignore accidentals or indicate actual note.
Ignoring accidentals is very easy but E sharp will be "mi", etc. and I feel it's very weird.
| la la ti ti | do re re mi | mi fa fa sol | la la sol | sol fa fa mi | mi re do do | ti ti la |
Is that correct? Does anyone know the standard way of fixed-do solfege in the scale with key signature and accidentals?
Thank you for your attention.
Comment: Hugely related, if not actually a duplicate: https://music.stackexchange.com/questions/33858/are-there-solfege-syllables-for-diminished-and-augmented-imperfect-intervals
Comment: @AndrewLeach it is closely related, but might be hard to find "fixed vs. movable" in that answer via simple searches.
Comment: I wouldn't call that scale an "A major", but I could be wrong. The way you said it omits that it is chromatic and not just the 7-tone scale with mostly whole steps.
Comment: @LeifWillerts - I read it as such initially. OP means 'A major scale - with accidentals. Accidentals are those # and b NOT included in the key sig.
Comment: This question is so distorted - unclear what is being asked, AND it somehow seems like if Sekine is asking multiple questions at once.  Downvoted and voted to close. -1.
Answer: the names are like Tim says correctly "do-dièse" (C#) and "mi bémol" (Eb) etc.
These expressions  are used to name  the key!
Examples:
Bach: Messe an Si- mineur
or:
https://fr.wikipedia.org/wiki/Suites_fran%C3%A7aises
Bach:
1.1 Suite française no 1 en ré mineur, BWV 812
1.2 Suite française no 2 en ut mineur, BWV 813
1.3 Suite française no 3 en si mineur, BWV 814
1.4 Suite française no 4 en mi bémol majeur, BWV 815
1.5 Suite française no 5 en sol majeur, BWV 816
1.6 Suite française no 6 en mi majeur, BWV 817
Rachmaninov, Prelude en do dièse mineur (-> C# minor)
But actually the French just sing the non-altered name - also DO for C# and MI for Eb etc. and the rest (sharps and flats they think or mind as it is written in the sheet notes:
the list you are asking for is here:

https://en.wikipedia.org/wiki/Solf%C3%A8ge
"In the fixed do system, shown above, accidentals do not affect the syllables used. For example, C, C♯, and C♭ (as well as Cdouble sharp and Cdouble flat, not shown above) are all sung with the syllable "do".
Answer: Fixed do, as used in France, therefore I'll use the French version, would use diese for sharp, and bemol for flat. So F♯ is called fa-diese, and B♭ is called si-bemol. I don't thnk it's productive to call, as in your first example, both A and A♯ (in movable, key A) as do, because it somewhat defeats the objective.
Comment: I agree with you, Tim, but the French do so. (And I wonder how they can mind and recognize the key without notes. (While the English spelling of the absolute names like Bflat, Eflat is correct but not very comfortable and "musically" for singing.)
Answer: Thank you everyone for responding to my question.
I think I understood about fixed-do solfege thanks to your comments and the information from websites Jody Nagel's page and reddit issue.
From my understanding, traditionally, fixed-do solfege is non-chromatic.
So, Fixed-Do / Non-chromatic syllables for the music above is:

It seems weird for me because E# is sung as "mi", etc., but it's the rule here.
There are also newly devised system to differentiate chromatic notes.
By using Shearer's system, fixed-do/chromatic syllables for the music above is:

Now, everything is clear. Thank you!


Add a field programmatically to a custom entity

Question: I am defining a new entity following the steps related here: http://www.istos.it/en/blog/drupal-entities/drupal-entities-part-3-programming-hello-drupal-entity
My question is how I can add a field programmatically to the Entity when I define it. I have read some links but I can't get it work.
My code:
function generador_examenes_entity_info() {
  $return['question_section'] = array(
    'label' => 'Apartado',
    'controller class' => 'SectionController',
    'base table' => 'question_section',
    'uri callback' => 'section_uri',
    'fieldable' => TRUE,
    'entity_keys' => array(
      'id' => 'sid',
    ),
    'static cache' => TRUE,
    'bundles' => array(
      'question_section'=> array(
        'label' => 'Question Section',
        'admin' => array(
          'path' => 'admin/structure/question-section/manage',
          'access arguments' => array('administer'),
        ),
      ),
    ),
    'view modes' => array(
      'full' => array(
        'label' => t('Full Content'),
        'custom settings' => FALSE,
      )
    ),
    'access callback' => 'section_access',
  );
  return $return;
}

Thanks
Comment: You could considering use features depending on your requirements
Answer: You'll need to define a field and an field instance in your module's .install file. The function can either be in hook_enable() or hook_install(). The field will provide the name of the field and some default settings. The field instance can be seen  as the link between the field and the entity you want to place the field on.
The format of the settings differs per field type (a text field has a maximum length, an entity reference field can define the selectable bundle(s), etc). Often the available settings are explained in the module's hook_field_info implementation. For core fields these can be found on the following page: 7 functions implement hook_field_info().
For non-core fields the settings are likely to be explained in the hook_field_info implementation as well, for example entityreference_field_info().
The process Drupal follows when registering a field is as follows:
The field is registered in the field api first, with it's default settings (the settings as defined in hook_field_info()). But your module can override them in the settings array of your field_create_field function. So that the field with your name will have by default your settings. Other values such as cardinality (how many values can the field hold) and translatability can be defined as well. See the detailed information on field_create_field() for all values.
From there the field is attached to the entity and it's bundle by means of a field instance. This instance defines which field should be attached to which entity and bundle. Here the settings can be overridden once more for this specific fields implementation on this specific entity. You can also select the widget here; the way the field is to be selected. Modules define their widgets in hook_field_widget_info(), available widgets for core fields can be found here: 7 functions implement hook_field_widget_info(). For a textfield you would use the widget text_textfield, for an image you can use image_image, for a non-core module you'll need to lookup the available widgets yourself in the hook_field_widget_info() implementation.
For a full lis tof all properties you can set on field instances, see field_create_instance().
Image field example
function mymodule_enable() {
  // Check if our field is not already created.
  if (!field_info_field('my_image')) {
    $field = array(
      'field_name' => 'my_image',
      'type' => 'image',
      'locked' => TRUE, // Settings can not be changed
      'settings' => array(
        'no_ui' => TRUE, // Field is not visible in field UI and can only be instantiated programmatically.
      ),
    );
    field_create_field($field);

    // Create the instance on the bundle.
    $instance = array(
      'field_name' => 'my_image',
      'entity_type' => 'my_entity',
      'bundle' => 'my_entity_bundle', // If your entity does not have bundles, this is the same as the entity type.
      'label' => 'Featured image',
      'required' => TRUE, // Field must have a value.
      'widget' => array(
        'type' => 'image_image',
      ),
    );
    field_create_instance($instance);
  }
}

Entity reference example
function mymodule_enable() {

  // Create an entityreference field.
  $field = array(
    'field_name' => 'my_entityreference',
    'type' => 'entityreference',
    'settings' => array(
      'target_type' => 'my_other_entitytype',
    ),
    'cardinality' => 1, // Field may only have one value.
    'translatable' => FALSE,
  );
  field_create_field($field);

  $instance = array(
    'field_name' => 'my_entityreference',
    'entity_type' => 'my_entitytype',
    'bundle' => 'my_entitytype_bundle',
    'label' => 'Reference to my_other_entitytype',
    'required' => TRUE,
    'widget' => array(
      'type' => 'options_select',
    ),
  );
  field_create_instance($instance);
}

Comment: Perfect answer (+1):I would just add that I prefer to use hook_install to create fields (and hook_uninstall to delete them, in order to don't touch DB/use CPU when enable/disable)... and, above all, that "drush field-info types" could be very useful to know available fields, widgets and default widgets.


Needing help in order to infer the statistical hypothesis tests performed in an old paper

Question: I am in great need of help in order to infer the statistical hypothesis tests performed in an old paper. However I need to make some reasonable guesses only from the abstract of the paper since the original text is in chinese which i can not understand (after extensive search i was also unable to find the original text even in chinese)
The title of the paper is:
"Detection of sister chromatic exchange in workers exposed to coal tar pitch and to coke oven volatiles"
The abstract of a paper (which was published in 1998 is the following):
In order to know the changes of genetic toxicological effects on workers occupationally exposed to polycyclic aromatic hydrocarbons (PAHs), sister chromatic exchange(SCE) was detected by the methods of peripheral lymphocyte culture in 23 workers exposed to coal tar pitch (CTP) and in 19 workers exposed to coke oven volatiles (COV) and 12 normal controls. The results suggested that the SCE in occupational workers was significantly higher than that in controls (11.31 vs 6.37, P < 0.001). The SCE in workers exposed to CTP and to COV was higher than that of control (10.27 and 12.58 vs 6.37) respectively. In workers exposed to CTP and COV, there were no differences of SCE for smokers and nonsmokers (P > 0.05). It is indicated that CTP and COV caused strong genetic toxicity and injury to chromosome.
In your opinion how do you think that the above reasarch was organized
For example: a) What types of statistical hypothesis testing was performed by the reasearchers b) What kind of data was collected and used for each statistical hypothesis test c) What methods were employed for the each hypothesis test ?
Answer: It's impossible to say for sure, but my guess is that they simply did pairwise t-tests. They looked at the average responses from the groups that interested them and did t-tests.
An option for these data would have been a two-way ANOVA (unbalanced, no doubt) with smoking and exposure group as the factors. There is no evidence from the abstract that the researchers attempted any such a thing. The advantage to such a model would be more degrees of freedom for error and better estimate of error (assuming constant variances!).
In my experience, a lot of researchers don't go further than pair-wise t-tests.


Como percorrer uma tabela com várias linhas e selecionar apenas uma específica?

Question: Estou tentando fazer que, ao clicar em uma tr com um id único, abrir um slideToggle com uma outra tabela embaixo da mesma linha que foi clicado. Eu fiz esse exemplo abrindo a primeira e a segunda linha, só que eu queria fazer algo dinâmico.
Até consegui fazer com todos de uma vez mas queria dessa forma que falei. Se alguém poder me ajudar, agradeço.

$(document).ready(function() {

  $('.slide').hide();
  var contar = $('.contar');
  var qtd = 0;
  contar.each(function() {
    qtd++;
  });

  $('#' + 1).click(function() {
    $('.slide' + 1).slideToggle();
  });
  $('#' + 2).click(function() {
    $('.slide' + 2).slideToggle();
  });

});
<tr class="info aba" id="<?php echo $cont ?>">

    <?php echo $listaPedidosSemanais[ "NOME"]?>

    <?php echo $listaPedidosSemanais[ "SERVIÇO"]?>

    <?php echo $listaPedidosSemanais[ "OPERADORA"]?>

  <a href="javascript:void(0);" onclick="abrir('pedidos_Semanais_prescricao.php?id=<?php echo $listaPedidosSemanais[" ID "]?>&dtIni=<?php echo $_POST["periodoInicial "]?>&dtFim=<?php echo $_POST["periodoFinal "]?>','600','600')">Prescrição

<tr id="<?php echo $cont ?>">

    <th class="labelAzul slide  <?php echo " slide " . $cont ?>" data-field="PRESCRICAO" data-sortable="true">PRESCRIÇÃO
    <th class="labelAzul slide <?php echo " slide " . $cont ?>" data-field="DATAINICIO IRGENCIA" data-sortable="true">DATA INICIO VIRGENCIA
    <th class="labelAzul slide <?php echo " slide " . $cont ?>" data-field="DATAFIMVIRGENCIA" data-sortable="true">DATA FIM VIRGENCIA
    <th class="labelAzul slide <?php echo " slide " . $cont ?>" data-field="DATALIBERACAO" data-sortable="true">DATA LIBERAÇÃO
    <th class="labelAzul slide <?php echo " slide " . $cont ?>" data-field="DIFERENCA" data-sortable="true">DIFERENÇA

  <?php $qryPrescricao=$ dao->listar_prescricoes($listaPedidosSemanais["ID"], $_POST["periodoInicial"], $_POST["periodoFinal"] ); $qtdPrescricao = count($qryPrescricao); foreach ($qryPrescricao as $pacientes){ ?>

    <td style="text-align: center" class="labelAzul slide <?php echo " slide " . $cont ?>">
      <?php echo $pacientes[ "IDPRESCRICAO"]?>

    <td style="text-align: center" class="labelAzul slide <?php echo " slide " . $cont ?>">
      <?php echo $pacientes[ "DT_INI_VIRGENCIA"]?>

    <td style="text-align: center" class="labelAzul slide <?php echo " slide " . $cont ?>">
      <?php echo $pacientes[ "DT_FIM_VIRGENCIA"]?>

    <td style="text-align: center" class="labelAzul slide <?php echo " slide " . $cont ?>">
      <?php echo $pacientes[ "DT_LIBERACAO"]?>

    <td style="text-align: center" class="labelAzul slide <?php echo " slide " . $cont ?>">
      <?php $duracao=$ funcao->diferenca_data_hora($pacientes["DT_LIBERACAO"], $pacientes["DT_INI_VIRGENCIA"]); $dia = (int) substr($duracao, 0, 2); $tam = strlen($duracao); if($dia >= 2 && $tam >= 11){ $classHoraUtil = 'labelVermelho'; $fora_prazo++;} else{ $classHoraUtil =
      'labelAzul'; $dentro_prazo++;} echo "
      ".$duracao.""; ?>

    <?php }?>

Comment: Você está usando algum framework ? Bootstrap ou algo do tipo ?
Comment: tente capturar o click nas `tr` com
`$("tr").on('click', function() {
    $('.slide' + $(this).attr('id')).slideToggle();
});`
Answer: Olá !
Você não precisa necessáriamente usar Jquery para fazer isso, em um código semelhante meu fiz o seguinte:

    Nome Exemplo

Então no JavaScript recuperei desta forma:
 function slide(id) {
  $('.slide' + id).slideToggle();
 }

Caso esteja trabalhando com Bootstrap, pode usar essa lib que tranforma a tr em um link clicável: http://www.jasny.net/bootstrap/javascript/#rowlink
Edit: Talvez para exibir a informação abaixo da linha, seja interessante usar a classe collapse do bootstrap.
Simple collapsible

      Texto Exemplo

Abraços,
Comment: Olá Lucas, dessa forma ele mostra as informações para todas as tabelas e eu queria que funcionasse só em baixo da que fosse clicada. Muito obrigado pela a ajuda.
Comment: sim, eu estou usando Bootstrap.
Comment: Ah sim, achei que a dúvida era sobre não precisar programar manualmente a chamada de cada registro, para exibir a informação abaixo da linha, talvez seja interessante usar a classe collapse do bootstrap, basta criar uma div com a `class="collapse"` e no seu link colocar `data-toggle="collapse"` como no exemplo que vou adicionar à resposta


Win32 getmessage loop stops executing when App window looses focus..! i want to run a infinite loop in my application without stopping

Question: Win32 getmessage() loop stops executing when App window looses focus..! i want to run a infinite loop in my application without stopping...
The program works flawless when the mouse pointer moves on the window,as it raises a event and the getmessage processes,but when the application window looses its focus or the mouse is not over it,it STOPS!...
i have a function which needs to be called continuously even when the win32 app is minimized or lost focus...
i am calling the function like this...
MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
    showFrame();
    }

i know,only when any event is raised the getmessage processes it and in turn the showFrame() function is called,but i want to call the function continuously...
please give me a clue how can i achieve it or do i need to use threading??
Answer: GetMessage() blocks until there is a message available to retrieve.  If you don't want to wait, then use PeekMessage() instead:
MSG msg;
do
{
    ...
    while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
        ...
    }
    ...
}
while (...);

You can also use either GetQueueStatus() or MsgWaitForMultipleObjects() to detect when there are messages available before then retrieving them, eg:
MSG msg;
do
{
    ...
    if (GetQueueStatus(QS_ALLINPUT))
    {
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            ...
        }
    }
    ...
}
while (...);

MSG msg;
do
{
    ...
    if (MsgWaitForMultipleObjects(0, NULL, FALSE, 0, QS_ALLINPUT) == WAIT_OBJECT_0)
    {
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            ...
        }
    }
    ...
}
while (...);

Alternatively, you can use SetTimer() to post periodic WM_TIMER messages to the queue, and then your loop can show the frames each time it receives that message.
Alternatively, use a standard GetMessage() loop, and have a separate thread drive your frame logic.  Whenever it needs to show a new frame, it can post a user-defined message to the main thread queue so your loop can show the frame.
Comment: Thank you,that helped me!,now i just have to learn on loading icons to my app to complete it!


Laravel webapp login from iOS with Facebook SDK

Question: i have a webapp working with Laravel.
i have some users registered in my webapp.
users who dont want to create a account can use Facebook/Google+ login.
to make Facebook/Google+ connection, i used a oAuth2 connexion with :
oauth-4-laravel
on the iOS application, users can login using username and password but they can login too with Facebook/Google+ using FB/G+ SDK.
my questions is, how to login on my webapp users from iOS who are connected by Facebook/Google+.
artdarek/oauth-4-laravel require a "code" given by the social network, and i dont know how to get it on iOS.
here the code for users who want to connect to the webapp by web browser :
 public function loginWithFacebook() {

// get data from input
    $code = Input::get( 'code' );

    // get fb service
    $fb = OAuth::consumer( 'Facebook' );

    // check if code is valid

    // if code is provided get user data and sign in
    if ( !empty( $code ) ) {

        // This was a callback request from facebook, get the token
        $token = $fb->requestAccessToken( $code );

        // Send a request with it
        $result = json_decode( $fb->request( '/me' ), true );

       // $message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
        //echo $message. "
";

        //Var_dump
        //display whole array().
       // dd($result);
        if (User::where('fb_id','=', $result['id'])->count() == 0) {
             $user = new User;
            $user->firstname = $result['first_name'];
            $user->lastname = $result['last_name'];
            $user->username = $result['email'];
            $user->email = $result['email'];
            $user->fb_id = $result['id'];
            $user->yearofbirth = substr($result['birthday'],6,9);
            $user->fk_role=3;

            if ($result['gender'] == 'male') {
                $user->sex = 1;
            }
            else{
                $user->sex = 0;
            }

            $user->save();

        }
        else{
            $user = User::where('fb_id','=', $result['id'])->first();

        }

    Auth::login($user);

    Userslog::log('desktop_facebook_login');

    return Redirect::to('/')->with('message', 'Logged in with Facebook');

    }
    // if not ask for permission first
    else {
        // get fb authorization
        $url = $fb->getAuthorizationUri();

        // return to facebook login url
         return Redirect::to( (string)$url );
    }

}

Answer: i finally find a solution in the issues of oauth-4-laravel on github,
i just have to use iOS AccessToken and connect the user to the webapp using this token.
here the code laravel code to use the Token ;)
use OAuth\OAuth2\Token\StdOAuth2Token;

$token_interface = new StdOAuth2Token(Input::get( 'token' ));
$network = OAuth::consumer( 'Facebook' );
$network->getStorage()->storeAccessToken('Facebook', $token_interface);
$result = json_decode( $network->request( '/me' ), true );
$fb_id = $result['id'];

To Resume,
the best way is  ; to login with Facebook/Google+ on iOS,
when login finish with success, get the AccessToken and send to the webapp.And then the webapp use you token to login again the user to Facebook/Google+ and finally , the user is verified and you can login it to laravel webapp.
have a nice day.
Answer: I'm quite in the same situation here.
With the solution you provide, how are you preventing other applications to send their own AccessToken and access your Laravel application?
I assume you send the token via a POST request from you iOS app to a certain endpoint of your Laravel app, therefore any developper knowing this endpoint could pretend to be logged on your mobile application, no?
Comment: after login with facebook or google, users are logged on laravel Authentification system with laravel account. iOS users need to be connect to the laravel login to use my application.

developper can login on my application, it will be open for every people.

Have I answered your question? if no, can you give me more details.
Comment: on facebook application management, you can enable login only for you ;)
Comment: Thanks for the enlightenment :)


Procedural generation

Question: I'm interested in generating procedural map using php, it can be static. I just need to get me on the right way... I red a lot of articles about it and understand that I need to use noise generation to get basic map shape. but what after that?! I will be using simple tiles 32x32. It it even  possible/efficient to do it via php?
Comment: Can you provide an example of what you are trying to achieve? Also why would you use web technologies for such a task? Thanks
Comment: http://i.stack.imgur.com/T0o4T.png, something like this. it's going to be web based game.
Answer: Look into using Perlin or OpenSimplex noise.
You can either implement this yourself or simply use a library:
https://github.com/martinlindhe/php-noisegenerator
You can generate a heightmap into an array using this library:
<code>$perlin = new \NoiseGenerator\PerlinNoise(3000);
$width = 100;
$height = 100;

$octaves = array(64, 16, 4, 2);
$noise = array();
for ($y = 0; $y < $height; $y += 1) {
    for ($x = 0; $x < $width; $x += 1) {
        $num = $perlin->noise($x, $y, 0, $octaves);
        $raw = ($num / 2) + .5;
        if ($raw < 0) $raw = 0;
        $noise[$x][$y] = $raw;
    }
}
</code>
Now that you have your noise array populated, you can represent this with color on your front end using JS or whatever you want. I'll let you figure out the details on that end, but essentially, find the range of your numbers in your heightmap and determine thresholds for different types of terrain.
I wrote a tutorial on generating heightmaps and rendering them using noise over here: https://plaxdev.wordpress.com/2017/05/04/procedurally-generating-islands/
This doesn't use PHP, only JavaScript, but the idea behind rendering the heightmap in JS is included in that article if you're struggling with that.

Procedural generation


Proving linearly independence of the functions $t^{i}e^{\lambda_{0}t}$

Question: Following the question I asked here and is:

Let $P(\lambda)=(\lambda-\lambda_{0})^{r}$where $r$ is a positive
  integer. Prove that the equation $P(\frac{d}{dt})x(t)=0$ has solutions
  $t^{i}e^{\lambda_{0}t},i=0,1,\ldots,r-1$

I now wish to prove the solutions are  linearly independent.
I have two questions regarding this:

I learned to prove such independence with the Wronskian, but I am having trouble calculating it in (I calculated the derivatives of $e^{\lambda_{0}t},te^{\lambda_{0}t}$ but its getting too hard when it is a greater power of $t$ since I am getting longer and longer expressions). How can I calculate the Wronskian ?
If I think of the vector space that is the smooth real valued functions then it seems that this set (if I take the power of $t$ to be as big as I want, but finite) is linearly independent. did I deduce right ?

I would appriciate any help!
Comment: I was unsure what other tags to add, feel free to add tags if you think it is related.
Answer: To show that $t^i e^{\lambda_0t}$ are linearly independent, it suffices to show that $t^i$ are linearly independent.
Comment: Why, can you please add an explanation ?
Comment: Write the definition of "linearly independent".  If you don't know it, look it up.  Compare the two cases I mention.  You may use the fact that $e^{\lambda_0 t} \ne 0$.
Comment: We need to add that the vecotr space of all smooth real valued function have no zero divisors for this ? Edit: do you need it not to be the zero function, or that for all $t$ it doesn't equal to zero ?
Comment: "zero divisor" is not a concept for vector space.
Comment: Can we say that such a conclusion is right even if there was $t$ such that $e^{\lambda_{0}t}=0$ ? maybe we can say that this is a ring with the pointwise multiplication and then add the argument about zero divisors ?
Comment: You "can" do whatever you want, but it is not needed to solve this problem.
Comment: I am asking what is a good argument to show this is sufficient, since $e^{\lambda_{0}t}\neq 0$ I can argue that, but I ask if there was $t$ s.t. $e^{\lambda_{0}t}=0$ could we still argue it is sufficient ?
Comment: @Belgi Is there an $x$ such that $e^x =0$?.
Comment: @PeterTamaroff - no, I ask if an argument could of been made if the function would of had a point such that it will be zero on that point (in other words, how critical is the fact that $e^x$ doesn't have a zero)
Comment: @Belgi Tell me if my answer cleared the doubts.
Comment: @Begli if there is a point where the function which is a factor of all the terms you are working with is zero and you are trying to do a proof of linear independence, then work away from that point.  In practice this has never caused me a problem with the proofs.  The thing to remember is that functions are different if they differ at a single point.  As you say, this is not a problem here.
Answer: Since you have some doubts, I'll try to give you a longer answers and maybe clear them.
The assertion that the $n$ functions $f_k(t)=t^k e^{\lambda_0 t} \text{ ; }{k=0,1,\dots,n-1}$ are linearly independent is that if
$$\sum_{k=0}^{n-1} c_k f_k(t)= e^{\lambda_0 t}(c_0+c_1 t +c_2 t^2+\cdots+c_{n-1} t^{n-1})=0$$
then
$$c_0=c_1=\cdots=c_{n-1}=0$$
Since $e^{\lambda_0 t}\neq 0$ for any $t$, it suffices to prove that if
$$c_0+c_1 t +c_2 t^2+\cdots+c_{n-1} t^{n-1}=0$$
then $$c_0=c_1=\cdots=c_{n-1}=0$$ or that the Wronskian determinant of the $n$ functions, $p_k(t)=t^k \text{ ; }{k=0,1,\dots,n-1}$ is never zero $0$.
For example, for the case $n=3$, we have the functions
$$y_0(t)=c_0$$
$$y_1(t)=c_1 t$$
$$y_2(t)=c_2 t^2$$
The Wronskian determinant is
$$W(y_1,y_3,y_3)=\begin{vmatrix} {1}& {  t}  &{  t^2}  \\ {0}& {1}  &{2  t}  \\ {0}& {0}  &{2 } \end{vmatrix}=2 \cdot 1 \cdot 1 = 2! 1!$$
since all other combinations will occurr with a $0$.
You can try and prove the Wronskian determinant
$$\begin{vmatrix}
   1 & t &  \cdots  & {{t^{n - 2}}} & {{t^{n - 1}}}  \\
   0 & 1 &  \cdots  & {\left( {n - 2} \right){t^{n - 3}}} & {\left( {n - 1} \right)}  \\
    \vdots  &  \vdots  &  \vdots  &  \vdots  &  \vdots   \\
   0 & 0 & 0 & {\left( {n - 2} \right)!} & {\left( {n - 1} \right)!t}  \\
   0 & 0 & 0 & 0 & {\left( {n - 1} \right)!}    \end{vmatrix}$$
will be equal to $1! 2! 3! \cdots (n-1)!$ so it cannot be zero.
Alternatively, one can prove the result by induction. You can assume the result is proven for $1,2,\dots, n-2$ and show the result is true for $n-1$. I think it is much easier to use the Wronskian determinant.
Comment: The Wronskian is not required here actually, the linear independence follows just from the fact that the polynomial has no more than $n-1$ roots.
Comment: @Artem What do you mean by "required"? The Wronskian is a fair argument, as valid as you argument. I think saying "just from the fact" is rather disrespectful to the Fundamental Theorem of Algebra. Now, if you can adjoin a proof of that, we'll be cool. =D
Comment: What I meant was that the notion of the Wronskian is far less "obvious" (known, etc) than the "common wisdom" fact about the roots of a polynomial.
Comment: @Artem Sure. The OP explicitly asked for the use of the Wronskian, so I used that.


Prove that $\sec(\pi/7)\frac{(4-\sec^2(\pi/7))}{(2-\sec^2(\pi/7))}=4$

Question: Prove that $$\sec(\pi/7)\frac{(4-\sec^2(\pi/7))}{(2-\sec^2(\pi/7))}=4$$
MY ATTEMPT: I thought of writing $\sec^2(\pi/3)$ in place of 4 and $\sec^2(\pi/4)$ in place of 2 in the question, and then applying $\cos^2(A)-\cos^2(B)=\sin(A+B)\sin(B-A)$, but it didn't helped (it made the question more complicated).
I also tried converting the whole question to $\tan$, but it didn't helped too.
Can anyone help me out with a solution. Thanks.
Answer: Observe that $\cos\left(7\cdot\dfrac{(2r+1)\pi}7\right)=-1$ for any integer $r$
$7x=(2r+1)\pi\implies4x=(2r+1)\pi-3x$
$\implies\cos4x=-\cos3x$
$\iff8c^4+4c^3-8c^2-3c+1=0$  whose roots are $c_r=\cos\dfrac{(2r+1)\pi}7, r=0,1,2,3$
But $r=3\implies c_3=-1$
So, the roots of $$0=\dfrac{8c^4+4c^3-8c^2-3c+1}{c+1}=?$$
$c_r=\cos\dfrac{(2r+1)\pi}7, r=0,1,2$
Now replace $c_r=\dfrac1{s_r}$ and simplify
Comment: @user_1729,   Set $$c=\dfrac1s\implies8-4s-4s^2+s^3=0\iff s(4-s^2)=4(2-s^2)$$
Comment: How can I simplify $8c^3-4c^2-4c+1$ to $s\frac{4-s^2}{2-s^2}$? How to even introduce the denominator in the former?
Answer: $$
\begin{align}
\sec(\pi/7)\frac{(4-\sec^2(\pi/7))}{(2-\sec^2(\pi/7))}
&= \frac{1}{\cos(\pi/7)}\cdot\frac{4\cos^2(\pi/7)-1}{2\cos^2(\pi/7)-1}\\
&= \frac{2\cos(2\pi/7)+1}{\cos(\pi/7)\cos(2\pi/7)}\\
&= \frac{2\sin(\pi/7)(2\cos(2\pi/7)+1)}{(2\sin(\pi/7)\cos(\pi/7))\cos(2\pi/7)}\\
&= 4\frac{\sin(\pi/7)(2\cos(2\pi/7)+1)}{\sin(4\pi/7)}\\
&= 4\frac{(\cos(2\pi/7)\sin(\pi/7)+2\sin(\pi/7)\cos^2(\pi/7))}{\sin(4\pi/7)}\\
&= 4\frac{(\cos(2\pi/7)\sin(\pi/7)+\sin(2\pi/7)\cos(\pi/7))}{\sin(4\pi/7)}\\
&= 4\frac{\sin(3\pi/7)}{\sin(4\pi/7)}\\
& = 4
\end{align}
$$


How to block all incoming request through one network interface?

Question: Saying I have a linux server as a router from LAN to WAN.
I don't want any incoming WAN request for safety issue.
So how should I block all the incoming request through the WAN interface, but doesn't limit the LAN users' normal internet activity?
Which application should I use? (iptables?). Which service will be interrupted if I shut up all incoming traffic?
Answer: If you really want to block all incoming traffic from the WAN (or Internet), you can simply add a rule like the the following:
$ iptables -A INPUT -i eth0 -j DROP

assuming eth0 is the WAN interface. This is enough to block all incoming traffic. However, you need to allow all related/established connections to be able to request some service from the WAN/Internet. So, you need a rule like:
$ iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

Of course the ACCEPT rule should be added before the DROP rule. Doing so will prevent you from hosting any service within your network.
Comment: What do you mean by the last sentence "Doing so will you prevent you from hosting any service within your network"?  What if I do want to provide service for my LAN user?
Comment: I think what Khaled meant was that your server won't be able to proivde any services to the outside like FTP, HTTP, etc.
Comment: @hydroparadise: yes, that's right. Any connection from outside will be blocked.
Comment: This is incorrect and [Kranthi Guttikonda's answer](http://serverfault.com/a/775125/322144) is right. You need to add the `DROP` rule on the `INPUT` chain, not the `FORWARD` chain.
Answer: iptables -A FORWARD -i eth0 -j DROP

Will not block incoming traffic. You should add rule on INPUT chain, e.g.:
iptables -A INPUT -i eth0 -j DROP


Como pegar valores com espaço no JSON

Question: Olá.
Estou com um problema ao popular um select com JSON.
Quando o valor tem 2 ou mais palavras o 'value' do meu option não é preenchido corretamente.
Exemplo:
{
"Marcas": {
    "Acura": {
        "Modelos": ["Integra", "Legend", "NSX"]
    },

    "Alfa Romeo": {
        "Modelos": ["145", "147", "155"]
    }
}

$.getJSON('models.json', function(data) {
    $.each( data, function( key, val ) {
        $.each(val, function(make, value){
            console.log(make, value)
            var option = '<option value='+make+'>'+make+'</option>';
            $(option).appendTo("#marcas_list");
        });
    });
});

Results:

Note que o <option value="Alfa" romeo></option> está sendo preenchido de forma incorreta.
Alguma coisa errada com o código ?
Alguma sugestão ?
Abraços!
Comment: boa prática é quando a chave ( pode ser variável ) tiver mais de uma palavra usar minúsculo e juntas por um hífen, assim impede esses problemas , se você puder mudar essa parte evitaria esses problemas.
Comment: Como queres que apareça? Testa por exemplo: `var option = ''+make.join(' ')+'';` é parecido com o que procuras?
Comment: @Sergio quando tento usar o .join():
Uncaught TypeError: make.join is not a function
Comment: Solução: `var $option = $('')
      .prop('value', make)
      .prop('text', make);
      $("#marcas_list").append($option);`
Answer: A separação não tem problema em carregar olha o exemplo!

var items = {
"Marcas": {
    "Acura": {
        "Modelos": ["Integra", "Legend", "NSX"]
    },
    "Alfa Romeo": {
        "Modelos": ["145", "147", "155"]
    }
}};

var opt = "";
$.each(items.Marcas, function( key, val )
{
 opt = opt + '<option value="' + key + '">' + key + '</option>';
});
$("#marcas_list").html(opt);

<select id="marcas_list">
</select>

No seu código:
$.getJSON('models.json', function(data) {
    var opt = "";
    $.each( data.Marcas, function( key, val ) {
        opt = opt + '<option value="' + key + '">' + key + '</option>';
    });
    $("#marcas_list").html(opt);
});

Answer: Você pode fazer isso sem problema através de objeto, usando document.createElement.

var marcas = {
"Marcas" : {
    "Acura": {
        "Modelos": ["Integra", "Legend", "NSX"]
    },
    "Alfa Romeo" : {
        "Modelos": ["145", "147", "155"]
    }
}}

$.each(marcas['Marcas'], function(key, value){
  var option = document.createElement('option');
  option.textContent = key;
  option.value = key;
  $('#options').append(option);
})

<select id="options"></select>
Comment: Dessa forma funcionou também!
A solução que utilizei foi essa:

https://jsfiddle.net/xqgaevzo/

Como pegar valores com espaço no JSON


Characterization of Mathematical Analysis

Question: If algebra can be characterized as the study of algebraic structures and the structure-preserving maps between them, how could we characterize mathematical analysis as a field? In analysis, can we break it down into certain mathematical structures, maybe topologies or metric spaces, and the continuous maps between them? Would this be the best way to characterize analysis?
Answer: I really like this quote of Dieudonné (in french) : "L'analyse c'est minorer, majorer et approcher".
Comment: A translation could be : "Analysis is about find lower bounds, upper bounds and good approximations."
Answer: While Nicolas answer is very good, I dont think it is very pedagogical. These upper bounds, lower bounds and approximations all really boil down to sequences!
 (which in turn are connected to toplogies)
So I would say structures related to "sequences" of different kinds i.e functions, real numbers or even operators. As for connecting to your question, continous maps preserve toplogies and hence sequences.
So from a "structural" point of view, the answer I think is sequences.


Time and Key Signatures

Question: Why is it deemed necessary to put the key signature at the beginning of each line? And in the same vein, why do we need a time signature at all, when it's fairly apparent what it will be in the first bar or two? Or, a slightly different slant, as common time is so common, use that as default, and only write in other time signatures.
Comment: I don't know about your first question, but for the second, I can imagine circumstances where it is not immediately obvious what the time signature would be
Comment: I'm assuming a 'standard' piece where the timing is static.
Comment: Whether it's "fairly apparent" depends on the style of music you are playing. If you are in an orchestra pit looking at a part that starts with 32 bars rest and then has a succession of one dotted half note per bar (and nothing at all in your part that resembles "a tune"), how would you know whether to count the rests as 3/4 or 6/8?
Comment: @alephzero - I'd hope the player might have spent those 32 bars listening! If by then, they hadn't got the feel, what were they doing there anyway?
Comment: Would you apply the same logic to the clef, which is also repeated at the start of each line?
Comment: Reading some of the OP's comments, was this a question or just a rant?
Comment: Okay, so, after the first bar or two, you can tell what time signature this is in? https://youtu.be/jM4W3qaNfng Or this? https://youtu.be/FwkcRTNMsWs
Comment: @JörgWMittag - I recorded the first on an e.p. when I was 15! There were some clues also! And, apart, my question is about written music. The second needs some time sigs, obviously. But it's changing all the time. I meant 'standard'. In fact, maybe ic a piece is in common time, then it won't need a time sig. Sort of default.
Comment: @alephzero - it's a genuine question upon which I've pondered for many a year. If it comes across as a rant, that's maybe due to a little frustration as I have no convincing answer - yet.
Comment: @JimM - the majority of instruments use the same clef the majority of the time, so why not?
Answer: The time signature cannot be figured out from the content since both 2/2 and 4/4 have a whole note all-in-all but have different accents and drive.  It's even worse with 6/8 and 3/4.
The repetition of the key signature is just a visual reminder since the key signature pervades a piece.  If you start the piece from the second page, it would be really awkward to have to leaf backwards in order to figure out what notes to play.  Having each line "grounded" in its key signature makes it easier to be sure about what one is playing.
Arguably that would also hold with the meter.  Convention still has converged to not repeating it, just like one does not repeat a tempo mark like "Allegro".
Comment: Why would youy start from the second page? O.k. put the key sig. on each page. But then why not put the time sig. on each page, too? Each line doesn't display the time sig. anyway. Other points only back up the question.
Comment: Correction Allegro is a character mark not a tempo mark.
Comment: @NeilMeyer - that doesn't alter the point one jot. On my metronome it's marked as a vague tempo.
Comment: 6/8 and 3/4 are usually written out in different groupings. 6/8 will have 2 groups of 3 quavers, and 3/4 will have 3 groups of 2 quavers. So it's not difficult to recognise each.
Answer: Sure, you can generally discover the time after a few bars.  But why not know it BEFORE the first note?  It will make more sense of the conductor's upbeat when sight-playing, if nothing else.
There's a "fake book" style where after the first line not only time signature but also key signature and clef are omitted.  It's not helpful, particularly in e.g. a Broadway pit orchestra part where both key changes and cuts are common, so you can find yourself cutting into a different - unstated - key!  Some old-timers find the style "professional", though I think the only professional aspect was corner-cutting by paid-per-bar Union copyists.
Comment: I suppose the clinching argument is that a key signature on each line is standard notation, except in one genre of American commercial music.  No-one will play a wrong note because the key signature's there.  Some might if it isn't.
Comment: If there's a change in signature, it's paramount that it's stated. Without it, the piece is unplayable! I've played hundreds like this, and feel that one only needs a statement at the beginning of the piece or when a change occurs.
Comment: Yes, as I said, fake book style has its supporters.

Another argument against is that Sibelius doesn't do it easily. And surely no-one MINDS seeing a key signature on each line.
Another feature of fake-book style is a fixed 4 bars-per-line.  So it can't even be argued that omitting clef and key signature get more music on the page.
There's also the 4 bars-per-line proportionally-spaced thing  for jazz lead sheets, which sacrifices some readability of the notes in order to achieve metrical spacing of the chord symbols.  Useful when you're "playing the changes".
Comment: I've written music out for too many years with 4 bars per line - a bit like (real) poetry. Very easy, generally, to read. Part of my point is that if there needs to be a key sig. on each line, then why not a time sig.? If there's no change, why tell everyone? It's clutter, rather like putting a # back after a natural, when the barline does it anyway.
Comment: If one is in the middle of playing a piece, one should be thinking in that key, surely. Should one need reminding of that any more than 'by the way, we're in 6/8'.
Answer: Even in cases where you can figure out the time signature (there are cases where you can't), the part is not supposed to be a puzzle.  It's supposed to make things as clear as possible to the player.
Key signatures can often change so it's good to be reminded at every line what the current key signature is.  Sometimes, on lead sheets of simple tunes that have no key signature changes, it's only written on the first line.

Time and Key Signatures


Whether $f(x)$ is reducible in $ \mathbb Z[x] $?

Question: Suppose that $f(x) \in \mathbb Z[x] $ has an integer root. Does it mean $f(x)$ is reducible in $\mathbb Z[x]$?
Answer: No. $x-2$ is irreducible but has an integer root $2$.
If the degree of $f$ is greater than one, then yes. If $a$ is a root of $f(x)$, carry out synthetic division by $x-a$. You will get $f(x) = (x-a)g(x) + r$, and since $f(a) = 0$, $r=0$.
Comment: Why is  $g(x)$ an integer polynomial?
Comment: Look at the algorithm for performing polynomial division: at every step, to find the next term in the quotient, you are dividing an integer by the leading coefficient of $x-a$ (i.e. 1). Clearly this always gives an integer.
Comment: I get it now. Thanks.
Answer: If the degree of the polynomial is 1, then it is irreductible by definition. But if the degree is greater than one and it has an integer root $r$, then the polynomial is reductible, because it can be written in the form $f(x)=(x-r)g(x)+r(x)$, where $r(x)$ is a constant (by remainder division theorem). Plugging $x=r$ yields that $r(x)=0$ and therefore $f(x)=(x-r)g(x)$.
Answer: No. Counter example: $f(x)=x$.
Comment: are there any counterexample for degree greater than 1?
Comment: @user774025: If a polynomial has a root then it is divisible by a polynomial of degree 1.


extrair json dentro de resposta request

Question: import requests
r = requests.get('https://www.streamersonnew.world/list')
print(r.text)

dentro da variavel r, tem um json aprensentado como:

extrair json dentro de resposta request


Como aplicar uma função para vários objetos? (Javascript Puro)

Question: Por exemplo, tenho uma div dentro de uma variável obj
 obj = document.getElementById("objeto");

..Quero que uma função seja aplicada a ela, dessa forma
 window.onload = function(){
    window.onclick = function (){
       obj = document.getElemntById("obj");
       obj.ver();
    }
    function ver(){
       this.style.backgroundColor = "#333333";
    }
 }

Como poderia fazer para essa aplicação funcionar?
O meu código completo, abixo:

Comment: Este site explica como fazer várias coisas sem o uso do jQuery. Talvez te seja útil: http://youmightnotneedjquery.com/
Comment: Andrey, Obrigado, sim vai me ajudar!
Comment: @SamirBraga, deixei um comentário em baixo, aqui fica uma versão no jsFiddle também: http://jsfiddle.net/M238g/
Answer: Para fazer isso tem de extender o prototype e adicionar esse método aos elementos.
Exemplo: http://jsfiddle.net/xYfMa/
HTMLElement.prototype.ver = function() {
    this.style.backgroundColor = "#333333";
}

window.onload = function () {
    window.onclick = function () {
        obj = document.getElementById("obj");
        obj.ver();
    }
}

Usando a palavra prototype acede-se ao protótipo de todos os elementos e esse método fica disponivel em todos os elementos. Cuidado somente para não escrever por cima de métodos já existentes, pois esta ferramenta é bem poderosa.
Comment: ótimo exemplo do prototype. +1
Comment: Funciona, mas não no meu arquivo, eu vou editar a resposta, e vou coloca o código completo, você poderia me ajudar?
Comment: @SamirBraga, faça uma demo do problema no jsfiddle e coloque aqui que eu dou uma olhada.
Comment: Está aqui http://codepen.io/SamirChaves/pen/gFwpc
Comment: Exemplo funcionando sem a utilização do prototype
http://codepen.io/SamirChaves/pen/KHpyi
Comment: @SamirBraga, as funções que não usam prototype não podem usar o `this` da mesma maneira que com prototype. Mas pode usar assim `var este = e.target` como fiz neste exemplo: http://codepen.io/sergiocrisostomo/pen/JkGrA
Comment: Obrigado, você me ajudou muito!!


Create a blank first column in kendo ui grid

Question: I am new to kendo ui grid development.
I have a requirement where I want to display data in kendo ui grid.
I am able to bind the data to kendo grid using java-script.
This is how I did it.
(document.getElementById(divId)).kendoGrid({
            columns: cols,
            dataSource: data,
            change: onChange,
            selectable: "multiple",
            //selectable: "multiple cell",
            schema: {
                model: {
                    id: "ID"
                }
            }
        }).data("kendoGrid");

The data is displayed in the grid.
Now, I want to create a blank first column in the grid that will display a image. How can I do this. The grid is bound to data dynamically. I have not specified any hard coded columns. All columns are created dynamically.
Please anyone can tell me on this.
Answer: You will have to explicitly define the columns because:

You want to add a columns that is not in the model.
The content of the column is an image that is not a KendoUI basic type that can be inferred from the model definition.

Said so, you have to add a column that is something like:
var cols = [
    // Your other columns
    ...
    {
        title :"Image",
        template: ""
    },
    // More columns
    ...
];

In addition you might need to use an image that is not a constant but depending on the content of a column. Then you might do:
var cols = [
    // Your other columns
    ...
    {
        title: "Status",
        template: "# if (status) { #  # } else { #  # } #"
    },
    {
        title   : "Photo",
        template: ""
    }
    // More columns
    ...
];

Where depending on the value of field in your model called status I display the image ok.gif or nak.gif. Or directly use the content of the field image for generating the URL to the image being displayed.
Check here for an overview on KendoUI templates.
Comment: Thanks OnaBai for quick reply. surely will try on this. Just had a question how can I set the title for grid but should not be visible. What actually I want is on the click of the newly created column as mentioned above, I want to get some additional values which will be common for entire grid. So how can I set any additional/custom property and access it. Also it would be very helpful if I can set title for grid but should not be visible. Only I need to access its value. Again thanks for the reply.
Comment: I've seen that you posted a question on click on the image. Please, see my answer there. Regards.


Modify the store for hundreds of products

Question: I have a drupal 8 commerce website with 2 stores (store1 and store2). Most of the products belong to both stores but there are a few that only belong to either one.
Now, I need all the products (hundreds) to belong to a new store(store3) that i created on the website.
Obviously, I will not manually edit each product to assign it to the new store but what i was looking into is to write a SQL script (given that it's a one time thing) that will update the products in the DB. Soon after that i found out that it's more than the commerce_product__stores table that i would need to update, i would also have to update the commerce_promotion__stores and commerce_shipping_method__stores tables. and to make the things more complicated, some tables like the commerce_product__stores need its values updated where as with the other ones, i need to add the entries.
What better, Drupal way, ways of doing it are out there?
Another option that i found was talking about exporting all the products with the views data export module, modify the data and import it back in with the Feeds module but the author was complaining about some issues that were still not resolved in D8...
Any suggestions?
Answer: There are two methods that are the "Drupal" way.
One is to write a PHP script that changes the products as needed.  You would write a loop, load the products, update, and then save them.  You then can the execute this script with drush as drush scr whatever.foo.  This will bootstrap Drupal, and then execute the script in the context of a running Drupal install.  Just keep in mind that loading a lot of entities in the same process can cause problems with the static cache getting too big.  There are other questions here about how to handle this.
The second is to write a hook_update_N() function, and put it in a custom module.  This is essentially the same as the standalone script.  If you go with this approach, you can batch the changes (say update 50 at a time).  You can then run the update from the UI or with drush updb.  This approach works a little better with database backups / restores, and also works nicely if you have a dev -> staging -> production environment, especially if it also pulls the database backwards at each step and automatically runs updates.