How should my Nginx 'default' file in sites-available be configured for a MERN app?

Question: I'm deploying a MERN app and wondering how the 'default' configuration file in etc/nginx/sites-available should be setup for the server, client, and Mongo database to work?
I am using a Ubuntu machine on Digital Ocean. I have the server.js running with Pm2 setup and working fine. Nginx and Mongo status checks come back fine. I am just having trouble with the configuration.
Here is one configuration of default I tried.
server {
    listen 80;
    server_name 184.108.40.206;
    root /var/www/MERN_App/client/build;

    error_page 404 /index.html;

    location / {
            add_header Cache-Control no-cache;
            try_files $uri $uri/ /index.html;
    }

    location /api/ {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Forwarded-Host $remote_addr;
            proxy_pass http://220.127.116.11:5002;
    }
}

Of course this doesn't show any data from the Mongo database because the address localhost:27017 is nowhere in this file. Though this gives the least errors and app flashes on screen with the above configuration, but in the console of course I get errors to the effect of 'cannot read ____ of undefined.'
The other thing I tried was 'stream'. I obviously don't know where this file even goes because it doesn't seem to belong in sites-available.
stream {
        upstream stream_mongo_backend {
                server 188.8.131.52:27017;
                }

        server {
                listen 80;
                server_name 22.214.171.124;
                root /var/www/MERN_App/client/build;

                error_page 404 /index.html;

                location / {
                        add_header Cache-Control no-cache;
                        try_files $uri $uri/ /index.html;
                }

                location /api/ {
                        proxy_set_header Host $host;
                        proxy_set_header X-Real-IP $remote_addr;
                        proxy_set_header X-Forwarded-Proto $scheme;
                        proxy_set_header X-Forwarded-For $remote_addr;
                        proxy_set_header X-Forwarded-Host $remote_addr;
                        proxy_pass http://188.8.131.52:5002;
                }
        }
}

This configuration will not allow me to restart nginx and the error in the log is 'stream can't go here'.
I don't know if there is some combination of a file in a new directory I have to create called 'stream' and a configuration in sites-available or something completely different.
If you have a good guide or video to setting up these files I would appreciate it because I find all of this opaque and I must be too thick for the Nginx docs.
Thank you for reading!
Comment: So, the overall request flow is like this: Client makes request to your nginx server. Nginx server passes the request to your NodeJS application. Your NodeJS then connects to the MongoDB server. This means that there doesn't need to be any MongoDB related things in nginx configuration.
Comment: What is running at `http://188.8.131.52:5002`?
Comment: My server? That's the port it uses when I run it locally.
Comment: What does "My server" mean actually?
Comment: The back end. NodeJS. The thing with all of the routes. If a site is not static it has both a client and a server.
Comment: Okay. Thank you. That gives me a direction to go in. My clue in the console log about the problem is `502 bad gateway` and the nginx error.log error is saying `connect() failed (111: Connection refused) while connecting to upstream, client: 126.96.36.199, server: 220.127.116.11,`
Comment: If your nginx is running on the same server as NodeJS, you should use `127.0.0.1` as the destination address.
Answer: You should not edit the default server block at all. You should instead create your own server block, in a separate configuration file in sites-available.
The default shipped with nginx is meant in part as an example, and in part to catch requests which are not directed to your web site's hostname.
Speaking of which, you should be using a hostname instead of an IP address to serve your web site, for a lengthy variety of reasons.
You are not streaming audio or video, so you should not be using stream at all.
From your description it sounds like your app is having problems. You should go back to debugging your application rather than doing things with nginx that at best will have no effect at all and at worst will break your site.
Comment: "You should not edit the default server block at all." There was no 'server' block until I created one. Do you mean the one called 'default' inside the sites-available dir? The app works just fine locally.
Comment: Yes, I mean the one shipped with nginx.
Comment: My problem is getting nginx to work with Mongodb. If it's not a `stream` what additional configuration file should handle Mongo? I don't need a host name yet.
Comment: @Renoldus Why would nginx be talking to MongoDB?
Comment: I don't know. You wrote, "You should instead create your own server block, in a separate configuration file in sites-available." Was this not related to Mongo? Has my OP violated some kind of rule? Because I'm having problems. I wrote what I tried. I posted what I tried. I find these configuration files completely opaque. Is there some guide or docs I can refer to so we don't have to keep going on like this?
Comment: It doesn't make any sense that nginx would be connecting to MongoDB. Your application is what is supposed to talk to MongoDB. Why do you think nginx should be talking to MongoDB instead of your web app?


Theory: Sampling Theorem & Nyquist Frequency

Question: i've got a problem with the sampling theorem
Sampling theorem states that a signal can be reconstructed exactly from it's samples if the original signal has no frequencies above half the sampling frequency.
But what about frequencies exactly half the sampling frequency?? let's say i sample a sine (with an arbitrary phase and amplitude) with a frequency exactly double the sine frequency. I will be unable to reconstruct the phase and the amplitude of the sine because i don't know how the phase shifted the sine in relation to my samples (for example, if i happen to sample exactly on the zero-crossings of the sine, my samples will all be zero).
what's the solution to that problem?
Comment: This is a programming related question.  In fact programming is the only context in which it makes any sense.  Please do NOT vote to close questions just because *you* do not understand them.  Programming is a much larger field than that.
Comment: The people who closed this question have clearly never done any DSP or signal processing SOFTWARE. Sorry it's not a web, database, or cool language feature, but it most certainly IS programming.
Comment: @GregS - The FAQ says, not "software" but, that questions "should be about programming. You know, with a computer."  So the D in DSP means what exactly?  Or do you do the binary calculation by hand?  This question is so much more worthy for SO than the multitude of questions about spheres colliding and basic trig that get answered here all the time, that the rule really seems to be "only trivial questions about math are allowed."
Comment: I replied to your argument here because you made it here, which seems the right place for it since it's a discussion about whether THIS question should be closed.  You should feel free though to go on meta for a discussion if you like, but please don't tell me to.
Comment: The only signal that's bandlimited to frequency = half of sampling frequency and is zero at the sample points is a sine/cosine signal (appropriately phase-shifted), so you *can* reconstruct the original signal in this case too.
Comment: but i can't know the amplitude
Comment: it's not about amplitude... a non-periodic signal (like one that is always zero) is not bandwidth limited, so you can't possibly sample it at twice it's maximum frequency.
Comment: No, it is most definitely not related to programming simply because the resulting algorithms get implemented in software. This particular question contains zero software-related content. And I have done DSP programming.
Comment: Go on meta and argue your case there. It should make for an interesting debate.
Comment: where should this question be asked?
Answer: Check this: http://en.wikipedia.org/wiki/Nyquist_rate#Nyquist_rate_relative_to_sampling
It's clearly stated that the sampling rate should exceed the Nyquist rate, which is double the highest frequency component.
Comment: @martiert, a better reconstruction? if you sample at more than twice the maximum frequency contained in the signal, you can reconstruct the signal *exactly* from the samples... doesn't get any better than that :).
Comment: @vicatcu No you can't reconstruct it exactly. Not even close. All you can do is avoid aliasing.
Comment: @phkahler - No, vicatcu (and others) are correct.  The point of Nyquist is that you can exactly reconstruct the signal if you sample above the Nyquist rate.  Just google it and read the theorem (it probably won't say "exactly" as reconstruct means exactly reconstruct).
Comment: Just to clarify: http://en.wikipedia.org/wiki/File:CriticalFrequencyAliasing.svg that's at the nyquist rate, so how exactly do you reconstruct "the right one"?
Comment: and exceed it by a good margin
Comment: The Sampling theorem only states that it should exceed the Nyquist rate, not with a good margin. Of course, you will get a better reconstruction of the image with a higher sampling rate, but the sampling theorem is about avoiding aliasing, which happens if your sampling rate exceeds the Nyquist rate.
Answer: How about:

This sufficient condition can be weakened, as discussed at Sampling of non-baseband signals below.
More recent statements of the theorem are sometimes careful to exclude the equality condition; that is, the condition is if x(t) contains no frequencies higher than or equal to B; this condition is equivalent to Shannon's except when the function includes a steady sinusoidal component at exactly frequency B.


Fender telecaster - gap between neck pickup and pickguard

Question: Just today I finally made my dream come true and bought my first Telecaster. I brought it home and it plays like a dream!
After I got to play with it for sometime and upon closer inspection, I noticed that there is a gap between the neck pickup and the pickguard. That gap, in fact, is big enough to fit a pick inside, as you can see in this photo:

So since I'm not that knowledgeable about guitars, I'm wondering, would this be an issue? I'm just wondering whether dust or other debris can find its way in there...
Thanks for your answers!
Comment: Check out this related question - https://music.stackexchange.com/questions/49375/importance-of-the-neck-joint-on-an-electric-guitar. Some of the answers may be useful
Comment: Just checked my '70s MiJ Fender Tele - couldn't push a pick in there! Maybe the tolerances aren't so tight these days!
Comment: Thanks! Indeed, I learnt quite a few things in it!
Comment: Well, probably the guitars made in Japan are higher quality than those from Mexico too. But thanks for the information!
Answer: That's nothing to worry about, it will not cause any issues at all.
The important things in a guitar are others: wood resonance, good construction, straight neck, quality pickups and machine heads, well shaped nut, well aligned strings, good string action.


WOPI - Excel documents do not switch to edit mode when clicking on "Edit in Browser" button

Question: I have a WOPI service which returns in its CheckFileInfo all required data including:
"UserCanWrite": true,
"EditModePostMessage": true,
"UserCanNotWriteRelative": true,
"HostEditUrl": "domain.com/Home/Detail/fileId?action=edit",
"HostViewUrl": "domain.com/Home/Detail/fileId?action=view"

However, when WOPI returns the Excel in View mode, clicking on "Edit in Browser" button does not switch the document into Edit Mode.
What could be the cause? Are we missing anything?
Below is the image of the edit button for Excel online
Answer: You need to set WOPI host capabilities properly.
In your case, it's the SupportsUpdate that you need to set. You need to have PutFile and PutRelativeFile methods implemented. For editing, I'd strongly recommend implementing locks and indicating that via the SupportLocks property.
Answer: All of that was set. The issue was the official documentation which claimed that things should work out of the box after setting all of those properties in the CheckFileInfo response object.
Unfortunatly that was not the case. We had to implement the event listener for it to work accordingly.


Auto assign organic group to a content type

Question: I'm trying to assign the group audience to a content type at creation instant. The first thing I have done is to disable the group audience field. So I have implemented the hook_form_alter and done this:
$form['og_group_ref']['#access']= false;

Then, I have implemented the hook_node_insert and here is where I have tried to assign the group. In my use case, users can only have one group. That's my code:
/**
 * Implements hook_node_insert
 */
function og_autoassign_node_insert($node){
  //Get the type
  $type = is_string($node) ? $node : (is_array($node) ? $node['type'] : $node->type);

  if ($type == 'content_type1' || $type == 'content_type2'){
    // Get the user
    $user = user_load($node->uid);

    // Load the current user's group
    //$groups = og_get_entity_groups('user', $user);
    $groups = og_get_groups_by_user($user);

    // Load the GID
    $group_id;
    foreach(array_keys($groups['node']) as $id){
        $group_id = $id;
    }

    $values = array(
        'entity_type' => 'node',
        'entity' => $node,
        'field_name' => 'og_group_ref',
        'state' => OG_STATE_ACTIVE
    );
    og_group('node', $group_id, $values);

    dpm($node);
  }
}

When I print the node with dpm, I can not see the organic group associated. What I'm doing wrong? Can anyone help me?
Thanks a lot
UPDATE (I can't answer myself because I have less than 10 in reputation)
Well, I found one solution. Instead of implementing the hook_node_insert, I did that in my hook_form_alter:
function my_module_form_alter(&$form, &$form_state, $form_id){
...
// Load the current user's group
$groups = og_get_groups_by_user();

$form['og_group_ref']['und'][0]['default']['#default_value'] = $groups['node'];
}

And that set the field "Audience Group" with the user's group.
Answer: I just ran into this problem with hooks. It's being saved but you won't see this in node_insert due to the caching system of nodes in Drupal. Add this before your dpm code and you'll see the results immediately.
entity_get_controller('node')->resetCache(array($node->nid));

I'm so happy I can stop someone else from banging their head on the wall like I did. Ha.
Comment: I think there is something more becasuse I have added this, and the dpm shows the same.

I'm still banging my head on the wall :(


Seeking method for isotonic regression with bound constraints

Question: I would like to fit an isotonic regression (with respect to "ordinary" linear ordering) to observations y_1, ..., y_n subject to the additional constraints that a <= y_1^* and y_10^* <= b where a and b are given constants and the y_j^*
are the fitted values.
In other words, find
<code> y_1^*, ..., y_n^*
</code>
which minimise
sum_{i=1}^n (y_i - y_i^*)^2 subject to the constraints
(1) y_1^* <= y_2^* <= ... <= y_n^*, and
(2) a <= y_1^, y_n^ <= b where a and b are given constants.
Is there a known solution to this problem?
Note that it could be phrased as finding the projection onto the intersection
of the isotonic cone and the hypercube [a,b]^n.
Comment: You can use $\LaTeX$ markup on this site! See https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference?noredirect=1&lq=1
Answer: It turns out that the R package OrdMonReg, which is available on CRAN, handles this problem (and more).
The person who instigated my original question (via an email enquiry about my
"Iso" package) found the OrdMonReg package and let me know about it.
The theoretical background is to be found in the paper:
"Least-squares estimation of two-ordered monotone regression curves" by
Fadoua Balabdaouia, Kaspar Rufibachc and Filippo Santambrogioa,
Journal of Nonparametric Statistics Vol. 22, No. 8, November 2010,
pp. 1019–1037


Is the integral $\intop_{0}^{\infty}\frac{\cos x}{\sqrt{1+x^{3}}}dx$ absolutely convergent, conditionally convergent or divergent?

Question: I'm trying to solve the next problem: Determine if $\intop_{0}^{\infty}\frac{\cos x}{\sqrt{1+x^{3}}}dx$
is absolutetly convergent, conditionally covergent or diverges.
I think that the integral is abosolutely convergent and I tried to
do this: For all $x\geq0$ is true that
$$
\frac{\cos x}{\sqrt{1+x^{3}}}\leq\frac{\mid\cos x\mid}{\sqrt{1+x^{3}}}\leq\frac{1}{\sqrt{1+x^{3}}}\leq\frac{1}{\sqrt{x^{3}}}=\frac{1}{x^{3/2}}.
$$
Then, using the fact that $\int_{1}^{\infty}\frac{1}{x^{\alpha}}dx$
is convergent for $\alpha>1$ and the comparison test we can conclude
that the integral $\int_{1}^{\infty}\frac{\cos x}{\sqrt{1+x^{3}}}dx$
is absolutely convergent. Also, since the function $f\left(x\right)=\frac{\mid\cos x\mid}{\sqrt{1+x^{3}}}$
is continuous on $[0,\infty)$ then is Riemann integrable on $\left[0,1\right]$.
Therefore,
$$\int_{0}^{\infty}\frac{\mid\cos x\mid}{\sqrt{1+x^{3}}}dx=\int_{0}^{1}\frac{\mid\cos x\mid}{\sqrt{1+x^{3}}}dx+\int_{1}^{\infty}\frac{\mid\cos x\mid}{\sqrt{1+x^{3}}}dx.$$
And then, $\int_{0}^{\infty}\frac{\mid\cos x\mid}{\sqrt{1+x^{3}}}dx$
is convergent since in the last equality, the two sumands on the right
side are finite. Thus, the integral $\int_{0}^{\infty}\frac{\cos x}{\sqrt{1+x^{3}}}dx$
is absolutely convergent.
I don't know if what I did is right. Could you help me checking or
giving me some suggestion?
Thanks.
Comment: Yes. Thanks @Unit.
Comment: Where are you having doubts?
Comment: I have a little doubt where I separated the integral as the sum of those two integrals.
Comment: Here:$$\int_{0}^{\infty}\frac{\mid\cos x\mid}{\sqrt{1+x^{3}}}dx=\int_{0}^{1}\frac{\mid\cos x\mid}{\sqrt{1+x^{3}}}dx+\int_{1}^{\infty}\frac{\mid\cos x\mid}{\sqrt{1+x^{3}}}dx.$$
Comment: That's perfectly fine. You can convince yourself by writing $\int_0^\infty$ as $\lim_{b \to \infty} \int_0^b$.
Answer: This is correct. As you correctly noted, the absolute value of the integrand is continuous on $\Bbb R^+$; and thus in particular Riemann-integrable on any (bounded) interval $[0,I]\subset\Bbb R$.
Also, because you want to prove absolute convergence, your first inequality should be stated as
$$\left|\frac{\cos x}{\sqrt{1+x^3}}\right|\le\frac{|\cos x|}{\sqrt{1+x^{3}}}.$$
Comment: Alright, thanks.


Request Dinâmico entre ambiente de desenvolvimento e Produção

Question: Gostaria de saber como resolver o problema de request entre um ambiente local e de produção.
Exemplo:
tenho uma função JS que pega o contexo da aplicação e concatena com o request.
var ctx = window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));

ctx+'/Portal/listaProdutos'

Localmente ficaria: localhost:8080/"nomedaaplicação"/Portal/listaProdutos
Porém em produção, os requests estão pegando o contexto duplicado: www.nomedosite.com/Portal/Portal/listaProdutos.
Como resolver esse problema?
Outra dica:
Também tenho request assim: ctx+'/carregaBarSearch', sendo que estou navegando em paginas com o contexto /Portal , www.nomedosite.com/Portal/Home
Answer: Você deve definir um dns ou ip estático para os seus servidores e definir como path base das suas requisições.
Comment: Opa,na real eu apenas preciso saber como ficaria o contexto dinâmico em JS.
Comment: Cara na minha concepção, você deve definir uma variavel global e em determinado mometo usar um ajax para pegar essa informação do servidor. talvez fosse a forma mais certa.. mas dai entra a questão q vc nao tem o endereço do servidor pra usar pra fazer um ajax. Então acho que nesse caso teria que ser manualmente.


Pair users with smallest difference values with PHP / Javascript

Question: I've an array with name and some value like this :
$users = array(
    "name one"=>"2",
    "name two"=>"5.5",
    "name three"=>"8",
    "name four"=>"7",
    "name five"=>"2.5",
    "name six"=>"3"
 );

Now I want to make 3 pairs from it but both pairs value must be closest like example answer will :
name three pair with name four
name one pair with name five
name two pair with name six

I can't find any function in php or in javascript for making pairs like this or any related useful function for it.
Please let me know if there's any function available for same or similar thing or any custom codes to achieve it
Comment: What a logic to combine that pairs?
Comment: @splash58 actually that value is timezone so I want if we can make pairs then their timezone must not have too much difference like if my timezone is 5.5 and someone else is 10 something then it will be hard to get connected so I want pair as per their timezone and minimum time difference between pairs
Comment: How do you want to choose that `name five` pairs with `name one` and not with `name six`? it's the same delta? also, can one element be in 2 different pairs?
Comment: Do you want the pairs to be strings? Inside another array?
Comment: @Kaddath yes `name five` can be pair with any between `name one` or `name six` as difference are same
Answer: The only logic I can see is that they are the values that is the closest.
If that is the case then you can asort() the array to preserve keys and sort on value.
Then use array_chunk on 2 with third parameter true to preserve keys.
$users = array("name one"=>"2","name two"=>"5.5","name three"=>"8","name four"=>"7","name five"=>"2.5","name six"=>"3");

asort($users);
$users = array_chunk($users,2,true);

var_dump($users);

This returns:
array(3) {
  [0]=>
  array(2) {
    ["name one"]=>
    string(1) "2"
    ["name five"]=>
    string(3) "2.5"
  }
  [1]=>
  array(2) {
    ["name six"]=>
    string(1) "3"
    ["name two"]=>
    string(3) "5.5"
  }
  [2]=>
  array(2) {
    ["name four"]=>
    string(1) "7"
    ["name three"]=>
    string(1) "8"
  }
}

https://3v4l.org/7SR7C

Made it!
First look at first and last item if they are closer than first and second, if they are then add them to the new list using array_splice (which will remove them from the original array).
Then just merge it with the array_chunk.
asort($users);
$keys = array_keys($users);

if(end($users) + $users[$keys[0]] < $users[$keys[1]]-$users[$keys[0]]){
    $new[0][$keys[0]] = array_splice($users,0,1);
    $new[0][end($keys)] = array_splice($users,-1);

}

$new = array_merge($new, array_chunk($users,2,true));

var_dump($new);

https://3v4l.org/739TZ
array(3) {
  [0]=>
  array(2) {
    ["name one"]=>
    array(1) {
      ["name one"]=>
      string(3) "-11"   // <--- see here
    }
    ["name six"]=>
    array(1) {
      ["name six"]=>    // <--- see here
      string(2) "12"
    }
  }
  [1]=>
  array(2) {
    ["name two"]=>
    string(3) "5.5"
    ["name four"]=>
    string(1) "7"
  }
  [2]=>
  array(2) {
    ["name three"]=>
    string(1) "8"
    ["name five"]=>
    string(1) "9"
  }
}

Comment: This is perfection. (yeah it doesn't take much to impress me :P)
Comment: Now that OP has clarified it's timezones this will end up linking a -11 with a -6, instead of -11 with +12.
Comment: @MohitBumb Now I'm pleased with my answer.
Comment: Thanks @Andreas :)
Comment: Amazing I can accept answer after 4 mins. as per stackoverflow but amazing thanks :)


What does more than chance mean?

Question: I'm interested in what exactly sentences like this mean:

In the former case, participants correctly chose the larger city in
  55% of the pairs, in the latter in 54% of the pairs, both rates
  significantly different from chance.

Is it basically just that its significantly different from 50%?
UPDATE:
Here's another one:
<code>But now here's another one I've found: In a pretest, one brand had been rated as higher quality, and participants could identify the higher-quality product 59 percent of the time in a blind test (substantially higher than chance, which was 33 percent). I still don't get how is 33 determined?
</code>
How do they get 33?
Answer: Yes, that is probably what was intended, given the phrases "of the pairs".
Of course statistically significant, especially with a large enough sample, does not need to mean substantial.
Added as a response to comments:
The context seems to be described here, including

Imagine you are confronted with the names of two German cities, and
  you recognize neither of them. There is no more information available
  to infer which city is larger. What can you do?
...
Drösemeyer (2000) and Hell used the names of smaller German cities,
  between 45.000 and 60.000 and between 20.000 and 25.000 inhabitants.
  This resulted in their German participants sometimes having heard of
  neither of the two, and sometimes just recognizing the two by name,
  but with no further information available from memory. In the former
  case, participants correctly chose the larger city in 55% of the
  pairs, in the latter in 54% of the pairs, both rates significantly
  different from chance. Although these effects are tiny, they point to
  an interesting exploitation of information from the mere names, even
  if both cities are unrecognized.

That makes it clear that guessing one out of two is what was involved and suggests that there is on average a tiny positive amount of information about cities' sizes in their names.  But obviously it is not a particularly reliable way of estimating city size.
Comment: We're assuming that "chance" means 50%.  In many cases that's not so--consider an experiment in which more than two choices are possible, for instance.  Generally, "chance" refers to the probabilities assigned by the null hypothesis.
Comment: @Daniel What is *not* meaningful about comparing 54% to 50%?  Perhaps you are asking whether the difference is scientifically *important.*  That's a different question than statistical significance.  Its answer depends on the context.  It might help to think of a "significant" difference as being a *detectable* one.
Comment: @Daniel It means replacing aspects of the real world with idealized random processes.  In my preceding comment I treated the answers *as if* they had been obtained by drawing values out of a well-mixed box containing equal amounts of zeros and ones.  That's a probability model.  It describes a situation where respondents are independently guessing the answers to the questions.  A more complex model would be needed when it's likely answers will be correlated.  E.g., two questions might ask the same thing, so a *consistent* guesser would give identical answers.
Comment: @Daniel Mathematically, you give a probability distribution.  Coding the answers as 0/1 identifies the sample space with $\{0,1\}^6$.  A sufficient statistic is the sum of these answers, a 6D vector $(x_i)$ with components in $\{0,1,\ldots,15\}$.  Assuming independence among people (which is clear) and among questions (debatable but reasonable in many cases), the null distribution is given by $6$ Binomial$(15,1/2)$ distributions, assigning a probability of $2^{-15\times 6}\prod_{i=1}^6\binom{15}{x_i}$ to $x$.
Comment: so they are comparing 54% to 50% ? how can that be meaningful at all?
Comment: @whuber so for example in this case with 16 questions with 2 alternatives. How would you go about testing whether its significantly different from chance?
Comment: @Daniel In a standard way: adopt a probability model for "chance," select a test statistic, determine its distribution, and compare the actual statistic to that distribution.  One model views each answer as an independent random draw from a box with both alternatives (coded as 0 and 1) equally likely; a good statistic would be formed from the list of proportions of 1's, such as a negative log likelihood or (for largish samples) the sum of squares of their deviations from 1/2; large values of this statistic would be evidence of "significant differences from chance."
Comment: @Daniel It's worth noting that "significant" can be a rather subjective term. Levels chosen for significance can vary by discipline, and different tests may give contrary results.
Comment: @whuber I mean the more technical aspects. What does it mean technically to 'adopt a probability model for chance'?
Comment: @whuber so you basically mean giving answers to each question in a manner where 50% choose option1 and 50% choose option 2?
Comment: @Daniel Not quite: in this model, it will be unusual for the answers to split exactly 50:50.  This is a property of sampling with replacement.
Comment: @whuber okay but what I'm trying to figure out is how to specify such a model. for example I have 15 responses for 6 questions with two options each. and I would like to see whether people choose option a or b significantly more than chance. How do I go about specifying the chance model?
Comment: @whuber thanks now I understand. Can you recommend a book or paper where they discuss how to specify probability models based on different distributions?
Comment: @Daniel http://stats.stackexchange.com/questions/tagged/books+modeling
Comment: @whuber thanks for the useful links, however, I was hoping for something more basic to start with. for example specifying a simple chance distribution for the above problem, which shouldn't involve any complex considerations. just basically learning how to create sample distributions, etc
Comment: @Daniel I didn't want to offend you by suggesting basic stats texts, but that's where to begin.  Choose books by and for engineers if you want a lot of math; books by good statisticians if you want a good understanding with less math (I like Freedman, Pisani, & Purves, any edition); and books by social scientists if you want it all hidden from you :-).
Comment: @whuber thanks! i'll try to get the freedman book.
Comment: @Daniel Earlier editions are great and much cheaper than a new copy of the latest one.
Comment: @whuber thanks for the advice. But now here's another one I've found:  In a pretest, one brand had been rated as higher quality, and participants could identify the higher-quality product 59 percent of the time in a blind test (substantially higher than chance, which was 33 percent). I still don't get how is 33 determined?
Comment: @Daniel We're repeating ourselves: I answered that question in the very first comment here.

What does more than chance mean?


What test to look at impact over time?

Question: I am looking at the impact of a fungus on a plant over time by measuring key plant parameters (height, number of flowers, seeds, leaves etc) three times over the growing season. I have 12 replicates for each treatment and three treatments - two rust strains and a control.
What stats test would be most useful to determine any differences between treatments but also look take in consideration the impact of time?  A mixed effect model would group time together to give the overall trend, but what if the effect was more noticeable at one of the time points for example? Is it ok to compare the time points separately or is there a more suitable statistical test that I should use?
Answer: Given that you only have three time points and 36 measurements per time point (i.e., 12 per treatment), you could use a marginal multivariate regression model to assess differences over time. Using the nlme package in R, you could try something along these lines:
library("nlme")

gls(plant_height ~ time * treatment, data = <your_data>,
    correlation = corSymm(form = ~ 1 | plant_id),
    weights = varIdent(form = ~ 1 | time))

where time should be coded as a factor in your dataset. Then using the anova() function you could test for the interaction term between treatment and time that would tell you if there is a statistical indication for treatment differences over time.

What test to look at impact over time?


SQL Server performance for alter table alter column change data type

Question: We need to change the data types of some columns from int to bigint. Unfortunately some of these tables are large, around 7-10 million rows (but not wide).
Alter table alter column is taking forever on these tables. Is there a faster way to achieve this?
Answer: Coincidentally, I had to do something very similar about 3 hours ago.  The table was 35m rows, it is fairly wide, and it was taking forever to just do this:
alter table myTable add myNewColumn int not null default 0;

Here's what what I ended up going with:
alter table myTable add myNewColumn int null;

while 1=1
begin
    update top (100000) myTable
    set
        myNewColumn = 0
    where
        myNewColumn is null;

    if @@ROWCOUNT = 0 break;
end

alter table myTable alter column myNewColumn int not null;
alter table myTable add constraint tw_def_myNewColumn default (0) for myNewColumn;

This time around, the alter table statements were near-instant.  It took about 7-8 minutes (on a slow server) to do the update batches.  I'm speculating that SQL Server was generating undo in my original query to restore the values, but I didn't expect that starting off.
Anyway, in your case, maybe something similar would help.  You could try adding a new bigint column, update the new column in batches, then set the constraints on it.
Comment: I did not find any performance differences between changing the column size and copying into a new column in a table with 10 million + rows.
Comment: Which means it was slow in both cases?
Answer: create the new table you desire, with the right columntypes and indices. (script out the old table, and change the name.)
insert into new table (column list) select * from old_table;
rename the old_table old_table_back, rename new_table old_table.
create the old indices on the new table, drop any ri constraints on the old table and creaet them on the new table. Again, your rdbms will have some easy way to generate scripts to do this.
Comment: Is selecting into a new table into a column with a different data type any faster than changing the data type of an existing column? We are doing this for Primary Key columns.
Comment: Generally much faster; rather than having to resize each row, it's just creating new rows of the correct size.
Answer: I just ran across this issue...  A table with 447,732,310 records in it.  Had a coworker come up with an awesome solution, only took about 24 minutes to copy data to a new table, about 40 minutes to create indexes.
Here's what we did:
--Get ntiles of idOrders, split up into 100 groups - 1:20 minutes
IF(OBJECT_ID('TEMPDB..#x')) IS NOT NULL
    DROP TABLE #x

SELECT nt, MIN(idOrder) idOrderMin, MAX(idOrder) idOrderMax
INTO #X
FROM (
       SELECT idOrder, NTILE(100) OVER(ORDER BY idOrder) nt
       FROM (
              SELECT DISTINCT idOrder FROM order_raw_fields
       ) X
) Y
GROUP BY nt

-- view results
--SELECT * FROM #x ORDER BY idOrderMin

-- create new table
SELECT TOP 0 *
INTO ORDER_RAW_FIELDS_Intl
FROM ORDER_RAW_FIELDS

ALTER TABLE dbo.ORDER_RAW_FIELDS_Intl
    ALTER COLUMN value nvarchar(500)

--Build queries
SELECT 'insert into ORDER_RAW_FIELDS_Intl select * from order_raw_fields
where idOrder >= ' + CAST(idOrderMIn AS VARCHAR(100)) + ' and idOrder <= ' + CAST(idOrderMax AS varchar) InsertStmt
    INTO #inserts
FROM #X
ORDER BY idOrderMin

DECLARE insertCursor CURSOR LOCAL FAST_FORWARD FOR
    SELECT InsertStmt
    FROM #inserts

OPEN insertCursor

-- 24:04 minute execution time to match
DECLARE @insertStmt NVARCHAR(125)
FETCH NEXT FROM insertCursor INTO @insertStmt
WHILE @@FETCH_STATUS = 0
BEGIN
    --EXECUTE @insertStmt
    EXECUTE sp_executesql @statement=@insertStmt

    PRINT 'Execution Complete:  ' + @insertStmt

    FETCH NEXT FROM insertCursor INTO @insertStmt
END

CLOSE insertCursor
DEALLOCATE insertCursor

-- Add indexes
-- 21:37 minutes completion time
ALTER TABLE [dbo].[ORDER_RAW_FIELDS_Intl] ADD  CONSTRAINT [PK_ORDER_RAW_FIELDS_Intl] PRIMARY KEY CLUSTERED
(
    [idRow] ASC,
    [idOrder] ASC,
    [remoteFieldName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 92) ON [PRIMARY]
GO

-- 13:45 minutes completion time
CREATE NONCLUSTERED INDEX [IX_idOrder_remoteFieldName2] ON [dbo].[ORDER_RAW_FIELDS_Intl]
(
    [idOrder] ASC,
    [remoteFieldName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 94) ON [PRIMARY]
GO

-- drop table
TRUNCATE TABLE [dbo].[ORDER_RAW_FIELDS]
DROP TABLE [dbo].[ORDER_RAW_FIELDS]

-- renamed new table to old tables's name
EXEC sp_rename 'ORDER_RAW_FIELDS_Intl', 'ORDER_RAW_FIELDS';

Answer: I just ran into this a few weeks ago with a table with 639m rows.  I ended up creating a new table and copying the data over in "batches". It took about 2 days on the main server and replication took 3 days to replicate it all.  I then modified all the views and procs that used to old table.  This allowed me to clean up a few issues, like getting rid of a column I didn't want and picking (in some cases) better indexes. After all the data was moved sql changed, I then dropped the old table.
A mess, but am wiser for it now. Use big ints for you identity primary keys if the system will be long lived and there is any chance of multi-millions of rows.


How does $e^{i\ln(2)}=2^i$

Question: How does $e^{i\ln(2)}=2^i$?
I apologise in advance for the simplicity of the question, but I just can't seem to realise why... My mind has gone blank!
Thanks in advance.
Comment: $e^{i\ln(2)} = \left ( e^{\ln(2)} \right)^i = 2^i$
Comment: Of course! Thank you, @BalarkaSen!
Answer: You can write that as
$$ e^{i\ln(2)} = (e^{ln(2)})^i = 2^i $$
Because $e^{ln(x)}=x$.
Answer: Use the three following properties
$$a\ln b=\ln (b^a)$$
$$e^{a\ln b}=e^{\ln (b^a)}$$
$$e^{\ln a}=a$$
Answer: Use the formula $a^x=e^{x\cdot ln(a)}$
Comment: Why the downvote?
Answer: The definition of complex exponents is :
$$e^{bi} = \cos(b) + i \sin(b)$$
Assuming that the definition is consistent, we wish to know what
$$\left(e^{bi}\right)^c= ?$$
So applying the definition:
$$\left(e^{bi}\right)^c= \left(\cos(b) + i \sin(b)\right)^c$$
Applying trig identies and other stuffs...
$$ = \cos(bc) + i \sin(bc)$$
$$ = e^{bci}$$
The main point I'm trying to get across is that you can't just assume $\left(e^{bi}\right)^c = e^{bci}$ just because we are using an exponential notation, it follows from definition.  The definition could have been made where this doesn't follow, or there might not have even existed a definition where relations like this follow.  So don't let the other answers mislead you into thinking that you can just arbitrarily apply rules from one domain (reals) to another (complex).
Anyway, combine that with $2 = e^{\ln(2)}$ as the other answers mentioned and you get your relation.

How does $e^{i\ln(2)}=2^i$


Has Hashim Amla's religion directly affected his finances or game?

Question: I need to clarify the below two things about the former South African Test Captain Hashim Amla.

He is being fined 500$ per month for not wearing Castle Logo in his    jersey.
He was fasting during his triple century against England.

I want to know whether these two things are true or not. I need reliable references in the answer, since different sites reveal different things about the above.
Answer:
Hashim Amla pays a fine for not wearing Castle logo: FALSE

Reference: CSA's official Facebook page confirms this here.

Hashim Amla was fasting during the triple century against England: FALSE

Reference: Cricinfo commentary during this game says the following: (see 76th over)

Firdose Moonda, our South Africa correspondent at The Oval, confirms that Amla (and Imran Tahir) are only fasting on non-match days.

Until there is evidence to the contrary, I consider CSA and Cricinfo's word to be reliable enough.


What does error code "outcome = variable_name > 0 predicts data perfectly" indicate when using logistic regression in Stata?

Question: I have a longitudinal dataset and I am trying to create two variables that correspond to two time periods based on specific date ranges (pre- and post-) to be able to analyze the effect of each of those time periods on my outcome. However, when I tried to create these time period variables as exposures to use with my outcome using logistic regression, I get this error message "outcome = variable_name > 0 predicts data perfectly."
This is how I created my time period variables:
**Period 1:** bysort id_variable:  gen pre-period = binary_outcome if (date_of_eval < mdy(5,4,2020))
**Period 2** bysort id_variable:  gen post-period = binary_outcome if (date_of_eval > mdy(5,4,2020))

Does anyone know what this error code means or if I have incorrectly coded my variables?
Thank you!
Comment: @mkt I think this is quite different and hinges on issues in understanding how best to use Stata.
Comment: @NickCox Thanks for catching that, I'm not a Stata user and was guessing.
Comment: The closure reason does not apply. It is arguable rather that the question is off-topic.
Answer: There is a statistical question deep down here, which is about constant outcomes (or predictors), but it is hard to answer as you don't give the syntax for the Stata command that didn't work.  This would be a poor question for Stack Overflow for that and other reasons. You'd be better off on Statalist, but I will answer so far as I can, noting that there is too much to say to fit easily in comments.
Note that

bysort Id_variable: has no bearing whatsoever on the outcome of your calculations. It does no harm, but you'd get the same results without it.

post-period and pre-period are illegal Stata variable names, as containing hyphens, so presumably you used something else, perhaps underscores.

The biggest deal of all is that pre_period will be missing when post_period is equal to 1 and vice versa. So at best either would be a constant outcome if given as an outcome, or a constant predictor if given as a predictor, which may underlie your difficulties. Either way round, observations with missing values would be ignored for any variable mentioned.
My guess is that a single indicator variable
gen when = date_of_eval > mdy(5,4,2020)

is all that you need. It will have value 1 when true and value 0 when false.
Comment: Hi Nick, thank you for your help! I think this simpler code may work :)
Comment: Hi again Nick, thanks for the help. My Stata code for grouping variables by ID is **gen period_1 = date_eval < mdy(5,4,2020)** **preserve collapse  period_1=period_1** **count if period_1** and it gives me a number of individuals during that period. However, I get a different number if I use the SQL query in Python **evals_period_1 = ps.sqldf('SELECT id, COUNT(date_eval) FROM df WHERE strftime(date_eval) < strftime("%m/%d/%Y",{}) GROUP BY id'.format('5/4/2020'))**. Am I grouping by ID differently in these two codes? Please let me know what you think. Thank you!!
Comment: Please start a new thread on Stack Overflow following the guidelines there about minimal reproducible examples.  I can't help with Python queries on any forum.


A/B test and SRS

Question: I was reading about Simple Random Sampling (SRS) from this lecture notes. It says that SRS, which actually is a sampling without replacement makes $x_i$ not independent.
Then I thought about A/B testing. When doing A/B testing for a product feature, usually users are sampled randomly without replacement, put in one of two buckets, and only one group will see the feature. Also, usually I analyse the result using t-test, which assumes independence of samples.
Is this a problem and what should be the workaround?
Answer: The author is talking about a finite sample correction. When A/B testing, the population is rather large, unless you have some website that is only accessible to only a limited number of people, so the correcting factor:
$$\frac{N-n}{N-1}$$
tends to $1$ and can be ignored, as long as the sample you draw for A/B testing ($n$) is supposedly smaller than the population of potential visitors to your site ($N$). Even if the sample was large compared to the population, how would you go about determining the population size of potential visitors to your website?
If anything, the usual unbiased estimator of variance has a larger denominator ($\frac{1}{n-1}$) than the finite-sample corrected version. In other words, the worst case scenario is an overestimation of the variance, resulting in slightly less power.
Answer: As a practitioner, I am thinking about this too. We need to figure out what is population/sample in each scenario and what is our estimand. Here is my conclusion:

In Two Sample T-tests Scenario:
We have 2 populations and draw 2 srs samples to compare population
mean. Since our sample is srs, each sample is an unbiased represent
of corresponding population, we use sample mean/variance to estimate
population mean/variance and perform T-tests.

In A/B Testing Scenario:
We split users into 2 arms(control and treatment), and want to compare the mean difference of 2 arms. Thus, each arm itself is
a population, instead of a srswor sample from total users. So we do not need to use finite sample correction to estimate means' population variance.

A/B test and SRS


How to disabled textfield when i click the checkbox?

Question: I wanted to disable the div when i click the the checkbox. if the current address and permanent address are the same, the user just click the check box to disabled the field of the permanent address. Thanks!

                <input type="checkbox">Current and Permanent Address are the same.

                 Permanent Address
                 <input class="form-control" rv-value="address:address"
                    name="model.cid" data-validate="required" />

                 City <input
                    rv-value="address:city" rv-enabled="address:province" type="text" class="form-control typeahead" name="city"
                    id="city" data-validate="required"
                    placeholder="Current city" />

                 Province <input
                    rv-value="address:province" rv-enabled="address:country" type="text" id="province" placeholder="Select Province"
                    name="province" class="form-control typeahead">

                 Country
                 <select name="gender" class="form-control" id="gender">
                 <option value="" disabled selected>Country</option>
                 <option>Philippines</option>
                 <option>Hong Kong</option>
                 <option>South Korea</option>
                 <option>Singapore</option>
                 <option>China</option>
              </select>

                 Postal
                 Code <input class="form-control" rv-value="address:postalCode" name="postalCode"
                    id="postalCode" data-validate="required"
                    placeholder="Zip Code" />

Comment: Will this work for you? https://jsfiddle.net/88dz3fm7/
Comment: What checkbox? I can't seem to find any checkboxes in your code...
Comment: Updated Sir. Sorry...
Comment: the permanent address field, city, province and country
Comment: It works dude. but i change my script into this
Comment:
Comment: Can you post that as a fiddle or codepen?
Comment: https://jsfiddle.net/lazoskenneth/88dz3fm7/2/
Comment: Check that. It's working :) Thanks @k97513
Comment: If possible, could you accept my answer? Thanks.
Answer: Add the following JS to your code.

$(document).ready(function(){
  $('input[type="checkbox"]').change(function(){
    $('.permanentAdd').attr('disabled','disabled');
  });
});

                <input type="checkbox">Current and Permanent Address are the same.

                 Permanent Address
                 <input class="form-control permanentAdd" rv-value="address:address"
                    name="model.cid" data-validate="required" />

                 City <input
                    rv-value="address:city" rv-enabled="address:province" type="text" class="form-control typeahead" name="city"
                    id="city" data-validate="required"
                    placeholder="Current city" />

                 Province <input
                    rv-value="address:province" rv-enabled="address:country" type="text" id="province" placeholder="Select Province"
                    name="province" class="form-control typeahead">

                 Country
                 <select name="gender" class="form-control" id="gender">
                 <option value="" disabled selected>Country</option>
                 <option>Philippines</option>
                 <option>Hong Kong</option>
                 <option>South Korea</option>
                 <option>Singapore</option>
                 <option>China</option>
              </select>

                 Postal
                 Code <input class="form-control" rv-value="address:postalCode" name="postalCode"
                    id="postalCode" data-validate="required"
                    placeholder="Zip Code" />

Answer: You can try something like this
    <input type="checkbox" id="check_box" onchange="set_status();">

                             Postal
                             Code

Comment: have you get the answer?
Answer: Here is the example how you do this thing easy. make sure you have only one checkbox in this window. else this not working, then you need to change something.
jQuery
$( "input[type=checkbox]" ).on( "click", function(){
    var n = $("input[type=checkbox]:checked").length;
    if(n){
        $(".permanent-address").attr("disabled", 'disabled');
    }else{
        $(".permanent-address").removeAttr("disabled");
    }
});

HTML

        <input type="checkbox">Current and Permanent Address are the same.

<input class="form-control permanent-address" rv-value="address:address" name="model.cid" data-validate="required" />

Answer: Pure javascript anwser
function checkAddress(checkbox) {
  var inputs = document.querySelectorAll('input:not([type=checkbox])');
  var selects = document.querySelectorAll('select');
  for (var i = 0; i < inputs.length; i++) {
    inputs[i].disabled = checkbox.checked;
  }
  for (var i = 0; i < selects.length; i++) {
    selects[i].disabled = checkbox.checked;
  }
}

HTML code
<input type="checkbox" onclick="checkAddress(this)">

https://jsfiddle.net/0ba4f7jd/
Answer: Simply create a function that gets called when the checkbox is checked, which disables the div and all child elements:

$('#checkbox').change(function(){
 var div = $('#everything');
  if (div.attr('class')!="disabled") {
   div.addClass("disabled");
   $("#everything *").attr("disabled", true);
  }
  else {
    div.removeClass("disabled");
    $('#everything *').attr('disabled',false);
  }
});

DEMO


We have $a,b,c$ and $d$ are real numbers such that $\frac{b + c + d}{a} = \frac{a + c + d}{b} = \frac{a + b + d}{c} = \frac{a + b + c}{d} = r$.

Question:
If $a,b,c$ and $d$ are real numbers such that $\frac{b + c + d}{a} = \frac{a + c + d}{b} = \frac{a + b + d}{c} = \frac{a + b + c}{d} = r$ , find the sum of all the possible values of $r$ .

What I Tried :- First of all, when $a = b = c = d$ , the $4$ equations hold and we get $r = 3$ as $1$ solution .
For other solutions I simplified to get $6$ expressions as :-
$b^2 + bc + bd = a^2 + ac + ad$
$bc + c^2 + cd = a^2 + ab + ad$
$bd + cd + d^2 = a^2 + ab + ac$
$ac + c^2 + cd = ab + b^2 + bd$
$ad + cd + d^2 = ab + b^2 + bc$
$ad + bd + d^2 = ac + bc + c^2$
Now I have no idea how to start finding solutions for $r$ from here . Can anyone help?
Comment: The variable $r$ is here to help....
Comment: There are various ways of doing this which don't involve multiplying out the fractions - I have spotted two simple ideas. So give it a go to see if you can spot something easier. I don't think there is an easy hint which isn't a solution.
Comment: Hint: If any two of the numbers differ, you can show that they cannot have the same sign.
Answer: First of all $$\frac{b + c + d}{a} = \frac{a + c + d}{b} = \frac{a + b + d}{c} = \frac{a + b + c}{d} = r$$ gives you $$b + c + d=ar\\a + c + d=br\\a + b + d=cr\\a + b + c=dr$$ summing all these we get $$3(a+b+c+d)=r(a+b+c+d)$$ Now if $(a+b+c+d)\neq0$ then we must have $r=3$.
Now if $(a+b+c+d)=0$, then $r=\frac{a+b+c}{d}\implies r=\frac{a+b+c+d-d}{d}=\frac{-d}{d}=-1$ (For clarity: since we are writing $a,b,c,d$ in the denominators, we must need $a,b,c,d$ to be non-zero.). Therefore the sum of all possible values of $r$ is $3-1=2$.
Comment: @Subhrajit Bhattacharya , that was the exact idea I thought of , but what if $(a + b + c + d) = 0$?, then I suppose we will get $a = -(b + c + d)$ , so $r = (-1)$ right?
Comment: This is a fresh solution. I liked it more than mine.
Comment: Yes got it , thank you for the help .
Comment: @SouradipDas you are most welcome.
Comment: @SouradipDas I have added for that case.
Comment: @iam_agf Thanks!
Answer: First of all, the equation only makes sense when $a,b,c,d\neq 0$ so you can use this: If
$$\frac{x}{y}=\frac{a}{b}$$
Then
$$\frac{x}{y}=\frac{x+a}{y+b}$$
So your problem solves proving this property, and the only value will be
$$\frac{3(a+b+c+d)}{a+b+c+d}=3$$
But if you get the case $a+b+c+d=0$, then WLOG, $a+b+c=-d$, then you achieve that $a+b+c=-dr$, implying $r=-1$.
Then the only solutions are $r\in \{-1,3\}$, so the solution to the problem would be $3-1=2$.

So to achieve the identity, notice that
$$x(y+b)=y(x+a)$$
$$xy+ab=yx+ya$$
And substracting $xy$ to both sides you get:
$$xb=ya$$
$$\frac{x}{y}=\frac{a}{b}$$
The other side is the same way.
Comment: You forgot the case $a+b+c+d=0$.
Comment: Sorry, I didn't consider it. Adding. Thanks for mentioning it.
Answer: Here is the second thing I thought of (@iam_agf has the other). Add $1$ to all the terms and set $a+b+c+d=E$ and you get$$\frac Ea=\frac Eb=\frac Ec=\frac Ed=r+1$$ from which either $E=0$ or $a=b=c=d$
In the first case $r=-1$ and in the second $r=3$
Just putting $a+b+c+d=E$, which should be an early thing to try, also gets to the same place.
Answer: We obtain: $$\frac{b+c+d}{a}+1=r+1$$ or
$$\frac{a+b+c+d}{a}=r+1.$$
Now, $a+b+c+d=0$ gives $r=-1$, but for $a+b+c+d\neq0$ we obtain:
$$\frac{a}{a+b+c+d}=\frac{1}{r+1}$$ and
$$\frac{4}{r+1}=\sum_{cyc}\frac{a}{a+b+c+d}=1,$$ which gives $$r=3.$$
Comment: Sorry, I had a superficial look to your solution. I was mislead by the fact that you didn't give the final solution $3+(-1)=2$ but you are perfectly right not doing so (in order to give a little little remaining operation).
Comment: $r=3$ is indeed a possible value, but your derivation forbids $r=-1$ (you have $r+1$ in the denominator) which is the other possible value for $r$.
Comment: @Jean Marie See please better my solution. I said about this point already.
Answer: If you happen to know eigenvalues/eigenvectors, your issue can be written :
$$\underbrace{\begin{pmatrix}0&1&1&1\\1&0&1&1\\1&1&0&1\\1&1&1&0\end{pmatrix}}_A\begin{pmatrix}a\\b\\c\\d\\\end{pmatrix}=r\begin{pmatrix}a\\b\\c\\d\\\end{pmatrix}$$
meaning that $r$ must be an eigenvalue of matrix $A$.
The eigenvalues of $A$ are $3$ and $-1$ ($-1$ being a
triple eigenvalue, but the text allows to take it only once) associated to resp. eigenvectors:
$$\begin{pmatrix}a\\b\\c\\d\\\end{pmatrix}=\begin{pmatrix}1\\1\\1\\1\\\end{pmatrix},\begin{pmatrix}1\\1\\1\\-3\\\end{pmatrix}$$
fulfilling the condition that neither $a$, nor $b,c,d$ are zero (being in the denominator of the initial equation)
Therefore the answer is $3+(-1)=2$.
Comment: Why that particular choice of $u$?
Comment: In fact, I didn't need an explicit expression for the other eigenvectors (see the modification I just made at the end).


ruby on rails rename nested resources

Question: I have following routes
resources :posts, path: :blog do
    resources :comments, path: :comments do
    end
  end

  devise_scope :user do
    resources :posts, path: :blog do
      resources :comments do

      end
    end
  end

this gives me
post_comments GET    /news/:post_id/comments(.:format)          comments#index
                  POST   /news/:post_id/comments(.:format)          comments#create
 new_post_comment GET    /news/:post_id/comments/new(.:format)      comments#new
edit_post_comment GET    /news/:post_id/comments/:id/edit(.:format) comments#edit
     post_comment GET    /news/:post_id/comments/:id(.:format)      comments#show
                  PATCH  /news/:post_id/comments/:id(.:format)      comments#update
                  PUT    /news/:post_id/comments/:id(.:format)      comments#update
                  DELETE /news/:post_id/comments/:id(.:format)      comments#destroy
            posts GET    /news(.:format)                            posts#index
                  POST   /news(.:format)                            posts#create
         new_post GET    /news/new(.:format)                        posts#new
        edit_post GET    /news/:id/edit(.:format)                   posts#edit
             post GET    /news/:id(.:format)                        posts#show
                  PATCH  /news/:id(.:format)                        posts#update
                  PUT    /news/:id(.:format)                        posts#update
                  DELETE /news/:id(.:format)                        posts#destroy
                  GET    /news/:post_id/comments(.:format)          comments#index
                  POST   /news/:post_id/comments(.:format)          comments#create
                  GET    /news/:post_id/comments/new(.:format)      comments#new
                  GET    /news/:post_id/comments/:id/edit(.:format) comments#edit
                  GET    /news/:post_id/comments/:id(.:format)      comments#show
                  PATCH  /news/:post_id/comments/:id(.:format)      comments#update
                  PUT    /news/:post_id/comments/:id(.:format)      comments#update
                  DELETE /news/:post_id/comments/:id(.:format)      comments#destroy
                  GET    /news(.:format)                            posts#index
                  POST   /news(.:format)                            posts#create
                  GET    /news/new(.:format)                        posts#new
                  GET    /news/:id/edit(.:format)                   posts#edit
                  GET    /news/:id(.:format)                        posts#show
                  PATCH  /news/:id(.:format)                        posts#update
                  PUT    /news/:id(.:format)                        posts#update
                  DELETE /news/:id(.:format)                        posts#destroy
             root GET    /                                          posts#index

why are there routes multiple routes that are exactly the same?
how do i rename for example the news/edit to news update inside a nested resource?

Thank you !
Answer: you are calling resources for posts, path, blog and comments multiple times, you are just changing the order, but the links will be the same.

ruby on rails rename nested resources


Scroll two columns but only one get stucked after the text is finished

Question: So basically, I would like to scroll images and text at the same time, but when the bottom of the text shows up, I would like it to stop, while I could keep scrolling images.
I tried to use sticky position on the text, but it scrolls only when I scroll all the images. I maybe used it the wrong way.
In this example, I've replaced images by color boxes.

body{
  display: flex;
  margin: 0;
}
nav{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #ffc3d9;
  height: 50px;
}
section, aside{
  margin-top: 50px;
  width: 50vw;

}
.block{
  display: block;
  width: 100%;
  height: 200px;
}
p{
  margin: 10px;
}

Cat ipsum dolor sit amet, really likes hummus but put butt in owner's face spend all night ensuring people don't sleep sleep all day proudly present butt to human. Behind the couch pooping rainbow while flying in a toasted bread costume in space poop in a handbag look delicious and drink the soapy mopping up water then puke giant foamy fur-balls for carefully drink from water glass and then spill it everywhere and proceed to lick the puddle meow. Disappear for four days and return home with an expensive injury; bite the vet i like frogs and 0 gravity why can't i catch that stupid red dot leave buried treasure in the sandbox for the toddlers so with tail in the air or catch mouse and gave it as a present.

Is it possible ? If yes, how ?
EDIT:
I tried again using sticky position, but no matter what I use (top or bottom, with a full height column or not) it doesn't work. Is there an another solution ? Maybe some JS ?
Comment: Can you try fixed position ??
Comment: I can't scroll if I put fixed on aside ([link](https://jsfiddle.net/0f5qLh8j/))
Answer: You can use position: sticky; and set a top value:

body{
  display: flex;
  margin: 0;
}
nav{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #ffc3d9;
  height: 50px;
}
section, aside{
  margin-top: 50px;
  width: 50vw;

}
.block{
  display: block;
  width: 100%;
  height: 200px;
}
p{
  margin: 10px;
  position: sticky;
  top:50px;
}

Cat ipsum dolor sit amet, really likes hummus but put butt in owner's face spend all night ensuring people don't sleep sleep all day proudly present butt to human. Behind the couch pooping rainbow while flying in a toasted bread costume in space poop in a handbag look delicious and drink the soapy mopping up water then puke giant foamy fur-balls for carefully drink from water glass and then spill it everywhere and proceed to lick the puddle meow. Disappear for four days and return home with an expensive injury; bite the vet i like frogs and 0 gravity why can't i catch that stupid red dot leave buried treasure in the sandbox for the toddlers so with tail in the air or catch mouse and gave it as a present.

Comment: It's not fluid, it stops in the middle as [here](https://jsfiddle.net/nveyj9q2/3/) (I put 0 to top because it waits to be scrolled by 50px before start scrolling with your code)
Answer: I finally used JS
if(window.innerWidth > 600){
  var element = document.getElementById("scroll-text");
  let toScroll = element.scrollHeight + element.offsetTop;
  if(toScroll > window.innerHeight){
      toScroll += 60;
      window.addEventListener("scroll", (e) => {
          let windowScroll = window.scrollY + window.innerHeight;
          if(windowScroll > toScroll){
              if(!element.classList.contains("fixed")){
                  element.classList.toggle("fixed");
              }
          }else{
              if(element.classList.contains("fixed")){
                  element.classList.toggle("fixed");
              }
          }
      });
  }else{
      element.classList.toggle("fixedtop");
  }
}

.fixed is fixed bottom 0,
.fixedtop is fixed top. It works quite well. It's probably not the best way to do it but w/e it works ahah.


How to make the Bass in SATB move more smoothly?

Question: While writing for SATB, I realise I have a few chords where the Bass part is moving down in intervals of 6ths or 7ths from one chord to the next. For example, I have a chord progression  iib in F major (Gm/Bb) going to V7 (C7). Thus, the chord progression is iib - V7. In this, the Bb of iib is falling down to C of the V7.

Would this make sense to do? Is it acceptable? If not, what other way could I rewrite the chords to make the Bass move smoothly?
I would like to keep the Bb of iib as is, so I would need suggestions for the other two chords, if any.
Edit: I have wrongly written the Roman numeral of the first chord in the image as ii7b. It should be iib, where "b" indicates the first inversion chord.
Comment: I think you mean `ii6`. You have `Bb D G`... no seventh. The 'b' sort of looks like a flat, but I think you mean `6` a numeral.
Comment: @MichaelCurtis I seem to remember this user using `a` `b` and `c` to denote root position, first inversion, and second inversion, respectively.
Comment: @Richard You're right. The "b" was to denote the first inversion here. Should have mentioned that.
Comment: @Grace, thanks for clarifying, just curious why don't you use `6/3`, `6/4,` etc. for inversions?
Comment: @MichaelCurtis Yes it isn't ii7, but just ii. That's a mistake on my part, will edit it.
Comment: @MichaelCurtis For the years that I've been learning music theory, I have mainly come across this notation in the books. Though I do know about the notation you're using...
Answer: As a bass singer in an amateur SATB choir I think this is acceptable. I haven't played the notes, but going from the 4th note on a scale to the 5th (only an octave lower) and back to the 1st note is not uncommon.
The key question is probably how well notes fit a given harmony in general and how well they fit the respective chords. Singing Bb C F in your arrangement is not very hard since they are the 5th note of Gm, the root of C7 and the root of F.
Answer: The bass just moves ^4 ^5 ^1 or FA SOL DO or Bb C F. I think the ideal thing is for ^4 ^5 to be an upward step rather than a descending 7th.
But, the upper voices need to be reviewed.
According to Piston's Harmony ii V (including ii6 V) is different than other descending fifth root progressions. Instead of the upper voices moving up by step to the next closest chord tones they jump down by thirds...

...Piston doesn't say, but I think the reason for this motion is to get the top part to move down to the leading tone and then up to the tonic (highlighted green.) That motion of a sixth Bb G to a third C E - or a chord of the sixth to a root position chord - is certainly a counterpoint fundamental.
If we add the 7 to V - and keep to 4 voices, we have to drop a tone. The chord's 5th is usually the one to omit. So, we drop the 5th of V, add the 7, and get V7...

It seems to me we could have not doubled the root of V and then used the 5th with the voicing from bass to soprano C Bb E G...

...that would result in the leading tone moving down to the dominant, the 5th of I. Apparently that 'frustrated' leading tone motion (highlighted red) was not ideal and is the reason for Piston's advice.
Piston didn't specifically address ii7. It seems to me the important thing is the 7 added to ii is the tonic! In terms of smooth voice leading ^1 ^7 ^1 seems the smoothest motion for the top line...

...leaving all the other tones in place we move the tenor from Bb to G in lieu of G no longer being in the soprano.
Because the main topic here is voice leading I thought it good to inventory the basic lines for each of the upper parts in the various examples. Of course the bass for all of them is ^4 ^5 ^1 or FA SOL DO. The upper parts are...

^2 ^7 ^1 or RE TI DO
^6 ^5 ^5 or LA SOL SOL
^4 ^2 ^3 or FA RE MI
^4 ^4 ^3 or FA FA MI
^1 ^7 ^1 or DO TI DO
^2 ^4 ^3 or RE FA MI

The various upper parts move in smooth steps or thirds that resolve by a step back in the opposite direction. And we have the tendency tones FA and TI moving respectively to MI and DO.
The upper voices should all work in various inversions and open positions, except for the 'frustrated' leading tone example which is normally only acceptable when it happens in an inner voice.
With the exception of the questionable 'frustrated' leading tone example I think the rest of this is solid.

...what other way could I rewrite the chords to make the Bass move smoothly?

Schoenberg gave the advice to "always follow the bass!"
His point being that the bass generates the harmony.
From that point of view, I suggest re-framing your question like "how do I write my upper voices to best harmonize with a good bass?"
In other words make sure your bass is good first, then harmonize the upper parts and change the upper parts as needed. Don't mess around with a good bass! Imagine a house metaphor. You can remodel the rooms of your house, but you really don't want to re-do the foundation!
Answer: By definition, playing a Gm7/B♭ chord means the bass voice must sing a B♭. If you want to modify the second chord so that the bass voice doesn't jump by a seventh, try bringing that B♭ down an octave (or raising everything else appropriately) so the B♭ resolves up to a C. That should sound much smoother. Alternatively, you could invert your V chord.
I wouldn't worry about leaping from the C to the F; that sounds pretty strong, but it's done all the time. If you want' you could change that to make it less forceful of a cadence.
Comment: @Grace That sounds right to me. Of course, that doesn't mean it can't be done, and the voicing of the V chord probably depends on what you want to achieve. A root position V chord usually sounds stronger than an inverted one, all else being equal.
Comment: Yeah, it was a wrong notation. Realised my mistake, and have corrected it.
Comment: Also, you mentioned about inverting the V chord. I have read that you generally do not use inversion chords at cadence points. Is this actually true?
Answer: If you want to maintain the same chords and also want the top/melody line to stay the same, I would just go with one of these:
Comment: But depending on the style, the top example may break a major rule: that a chordal seventh must always resolve down by step.
Comment: The second example has no errors, so between these two it's definitely the preferred option.
Comment: Again depending on the style, that could actually be two other errors: voice crossing and voice overlap.
Comment: @Richard Could you just switch the two bottom voices of the last chord then? Or would it be also a no go to have the tenor below the bass in the final chord?
Comment: @Grace Well, as always... there are actually no rules in music. If it sounds good to you and you want it like that, then stick with it. If you have a certain melody and want to stick with it and can't work around it, you have to fix it the one or other way. However, the two most common approaches would be probably iib - V - I or Ic - V - I.
Comment: @jjmusicnotes: I don't agree with that qualification (at least not universally), particularly when you have an outer voice on a dissonance that simply jumps away from that dissonance, rather than resolving it.  If one is trying to write good voice-leading, a voice should not leap away from a dissonance (again, it's especially bad in an outer voice).
Comment: @Richard So what would be your solution? - The second example? - Omitting the bottom F and double the C with the tenor? - Change the chords?
Comment: @Andy I want to know if it is usual to use chords in inversion at cadence points.
Comment: @Richard - not to get too particular here, but the qualifier to the rule you mention is *"unless the note is resolved in another voice"* in which case it is acceptable.
Answer: An obvious solution is to merely shift the first bass note down an octave.
But the V - I bass line is so strong, I don't really mind it being approached by such a large jump.
Not sure you'd better try that one in an elementary harmony exam though :-)


How to use Firebase Remote Config in multiple package id (same project) Android

Question: I have used Flavour in Android studio for deploy different version(Demo,Production) in one device, but I also use firebase remote config where I registered it to one package id.
is it possible to make firebase remote config works in multiple package id?, I want to use it in my Demo and Production app.
Comment: have you tried adding multiple packages in project settings?
Comment: that is the answer, thank you @Niraj
Comment: you're welcome. let me add an answer so others can see it.
Answer: The documented advice for working with multiple environments, such as development and production, is to have one project for each environment.  Your app will typically have a unique application ID for each environment, which lets it read remote config parameters for the project that it will access, which is easy to configure with Android build variants.
Answer: Here is my answer
Remote config can be setup for below conditions

Only for different projects : ex : amazon, flipkart
Same project with different productFlavors ex : amazonPay, amazonShopping
Same project with different buildTypes ex : amazon.dev, amazon.prod, amazon.experiment

Here is sample code to setup remoteConfig, it might help you/others
Make sure you setupRemoteConfig in onCreate of Application.java file
private void setupRemoteConfig() {
    final FirebaseRemoteConfig remoteConfig = FirebaseRemoteConfig.getInstance();
    remoteConfig.setDefaults(R.xml.remote_config_default);
    remoteConfig.fetch(300).addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
            remoteConfig.activateFetched();
        }
    });
}

Answer: You can add multiple application package names under project settings so that they all can use common firebase services. In this way, you can share single project resources among multiple applications.
Answer: You can create service accounts for every environment and you can use that, if its a database you can create two separate nodes for Production and Development.
Thank You for reading


How do I get the UID in user-profile.tpl.php?

Question: I'm trying to make a custom view mode for user profiles. In my user-profile--myviewmode.tpl.php, I want to get the UID for the user whose profile it is.
The help text for user-profile.tpl.php states:

$user_profile: An array of profile items. Use render() to print them.
  Field variables: for each field instance attached to the user a
  corresponding variable is defined; e.g., $account->field_example has a
  variable $field_example defined. When needing to access a field's raw
  values, developers/themers are strongly encouraged to use these
  variables. Otherwise they will have to explicitly specify the desired
  field language, e.g. $account->field_example['en'], thus overriding
  any language negotiation rule that was previously applied.

I used dpm() to print out the array $user_profile, but I couldn't find the UID anywhere.
Then I tried:
global $user;
$uid = $user->uid;

However, this doesn't work because when I use Views to render the view mode, it gives me the UID of the logged-in user, not the user whose profile is being rendered.
Is there a way to get the UID in user-profile.tpl.php?  I need to get the UID to build some custom links based on it.
Answer: I found the uid under the elements >> #account object:
$elements['#account']->uid;

Good luck!


finding probability density function $U=Y-X$

Question: suppose joint probability density function of $X,Y$ is $$f(x,y)=\frac{1}{2}\\ x>0 ,y>0,x+y<2$$how can i find  probability density function $U=Y-X$
Comment: Letting $W$ be an independent Bernoulli$(1/2)$ variable, set $(\xi,\eta)=(1-X/2,Y/2)W + (Y/2,1-X/2)(1-W)$. Geometrically--draw a picture--it is clear that $\xi$ and $\eta$ are independent and have uniform$[0,1]$ distributions, while $U$ has the same distribution as $2(\xi+\eta)-2$. Therefore $U$ is the sum of two independent uniform variates, scaled by $2$ and shifted by $-2$. The PDF of $Z_2=\xi+\eta$ appears in the first plot of the question at http://stats.stackexchange.com/questions/41467 and the answers to that question provide many different ways to obtain the distribution of $U$.
Comment: You need the self-study tag.
Answer: I will explain in words what you need to do as it seems a homework to me! Try to define another 1-1 transformation (say $V$) based on $X$ and $Y$. Then use the Jacobian theorem to find the joint density of $U$ and $V$. Finally, you can integrate this joint density to find the density function of $U$.
There is a similar example here that I suggest you to go over before doing this problem. Then this problem should a piece of cake for you to do!


Aggregating dates in SQL Server

Question: I have a 2-column table named Assignment. The table contains assignment of Person (nvarchar(20)) and Day (date), like here:
Person      Day
------------------
John    2011-05-23
John    2011-05-24
John    2011-05-25
John    2011-05-27
John    2011-05-28
John    2011-05-29
Anna    2011-05-02
Anna    2011-05-03
Anna    2011-05-06

I need to extract the date ranges when there is a sequence of adjacent days. The output should be a single string value for every row:
------------------
John    2011-05-23 - 2011-05-25
John    2011-05-27 - 2011-05-29
Anna    2011-05-02 - 2011-05-03
Anna    2011-05-06 - 2011-05-06

I tried grouping and then
   CAST(min(Day) AS VARCHAR) + ' - ' + CAST(max(Day) AS VARCHAR)

but it does not work correctly.
Any advice is welcome.
Thanks.
Comment: From the above mentioned answer... ;With Cte as(
select *, DATEDIFF(D, 0, A.Day) - ROW_NUMBER() OVER (PARTITION BY A.Person ORDER BY A.Day) Grp from Assignment A
)
Select Person, MIN(Day), MAX(Day) from Cte
group by Person, Grp
Comment: This answer can be adapted to fit your table. http://stackoverflow.com/questions/6099279/need-help-finding-the-correct-t-sql-query/6099433#6099433
Comment: @Mikael Eriksson Thank you that worked, please write your comment as an answer and i will accept it.
Answer: declare @T table(Person nvarchar(20), [Day] date)

insert into @T values
('John',    '2011-05-23'),
('John',    '2011-05-24'),
('John',    '2011-05-25'),
('John',    '2011-05-27'),
('John',    '2011-05-28'),
('John',    '2011-05-29'),
('Anna',    '2011-05-02'),
('Anna',    '2011-05-03'),
('Anna',    '2011-05-06')

;WITH cte AS
(
SELECT *,
        DATEDIFF(DAY,0,[Day])-
        ROW_NUMBER() OVER (PARTITION BY Person ORDER BY [Day]) AS Grp
FROM @T
)
SELECT Person,
       MIN([Day]) AS DateFrom,
       MAX([Day]) AS DateTo
FROM cte
GROUP BY Person, Grp

Comment: @daemon_x: From the page linked by Mikael: `Once a post is made community wiki […], that mode cannot be reversed.` Just wanted to highlight it for you to make sure you wouldn't overlook it. :)
Comment: +1; nice answer, anyway why I can see at this post above your name `community wiki` ?
Comment: @daemon_x – Community wiki post does not give reputation to the poster and since this answer is a direct copy of Martin's answer http://stackoverflow.com/questions/6099279/need-help-finding-the-correct-t-sql-query/6099433#6099433 I thought is was the right thing to do.
Comment: @Mikael - so you mark this anwser as a community wiki somehow ? I don't know about this magic. You flagged yourself ?
Comment: @daemon_x – Yes I did. It is a checkbox down to the right of the screen when you answer questions. http://stackoverflow.com/privileges/community-wiki
Comment: @Mikael - I see; I overlooked the check box even if it's directly in front of me :) Thanks for the info.

Aggregating dates in SQL Server


Update line item price

Question: So I have a product named "Store Credit" which is added to the cart when the user wishes to use points to get discount. The discount is always different depending on how many points the user enters. If the user enters 500 points, I want to create a line item with a price of -500$.
function switch_addtocart_cart_line_item_refresh($line_item, $order){

    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
    $line_item_wrapper->commerce_unit_price->amount = 150;
    commerce_line_item_rebase_unit_price($line_item_wrapper->value());
    commerce_line_item_save($line_item_wrapper->value());
    commerce_cart_order_refresh($order);
    dpm($line_item);

}

My dpm indicates the price has changed but the price in my cart and order review page is still the same? What am I doing wrong.
Comment: There is another question about this at [How to change the price ? (add_to_cart)](http://drupal.stackexchange.com/q/162097/6780). The key seems to be using the [`commerce_price_field_data_auto_creation`](http://www.drupalcontrib.org/api/drupal/contributions!commerce!modules!price!commerce_price.module/function/commerce_price_field_data_auto_creation/7) and [`commerce_line_item_rebase_unit_price`](http://www.drupalcontrib.org/api/drupal/contributions%21commerce%21modules%21line_item%21commerce_line_item.module/function/commerce_line_item_rebase_unit_price/7) functions.
Answer: Check your hook_name, I think thats the issue.
Default commerce hook is mentioned below.
hook_commerce_cart_line_item_refresh($line_item, $order_wrapper)

So, Your hook can be like (assuming switch_addtocart is your module name)
function switch_addtocart_commerce_cart_line_item_refresh($line_item, $order_wrapper) {

}
Please check and let us know.
Answer: You also need to change.
$line_item_wrapper->commerce_unit_price->data->components->price->amount

Comment: please include the original line of code in an answer like this so that the answer can easily be referenced back to the question - as it stands, I think I know what you're saying, but that's a guess. Try something like "instead of this {code}, try this {code}"

Update line item price


Using multiple linear regression instead of survival analysis to estimate time until event

Question: I have just started to read about survival analysis,
I have read in this interesting article about survival analysis, and why use it rather than the famous multiple linear regression to estimate the time of the event occurance. Mainly because linear regression cannot handle right censoring (i.e. if the event has not yet occured to some of objects of study after the study duration).
My question is, hypothetically, what if I have the data of heart disease patients, say 1M, 0.5M patients have had a heart attack, and 0.5M patients haven't had a heart attack, in a 10 year period. What if I use only the 0.5M patients that had a heart attack to build a regression model to estimate the time period it will take for a patient to have a heart attack?. Or, to make it more thorough, use both data to predict whether a patient will have a heart attack or not, and if so, estimate when the event will happen. This way, the problem with the right censoring issue will be eliminated.
Would there be any faulty/wrong thought process to this methodology? If there is, could you also show me how survival analysis (or perhaps another alternative method) tackles it?
I am trying to get a deeper understanding of the subject. Thank you, in advance.
Comment: If you use a specific criteria to separate the patients selected for the modeling, such as smoker / non-smoker for example, that could be applied to future patients to determine if the model you have created can be applied to patients outside the study group. If you select for modeling only the patients who have already had a heart attack with no other criteria, how could that model be applied to patients from outside the study group? And so this type of data selection does not provide a predictive model, even though it can be an informative analysis.
Answer: The problem won't be eliminated.
You will wind up telling some people that they won't have a heart attack and some that they will.  But this is false and misleading.  What you get from a logistic regression is a probability that they will have a heart attack. So, who goes in which group?
And your second analysis will only apply to people who meet certain criteria (figured out somehow) and won't be applicable to the others.
This is exactly the kind of problem survival analysis was intended to solve and it's the method you should use.


Prolog infinite loop issue

Question: I have the below functions.
When I call it with final_filter([(2, 2)], R), it prints a lot of "2 2" pairs. When I comment get_all_sums(S, _) it works fine, however if I test separately get_all_sums(4, R). I works also fine, what could be the problem?
get_all_sums_R(NR, IT, []):- IT > NR - 2.
get_all_sums_R(NR, IT, R):-
    A is IT,
    B is NR-IT,
    A >= B,
    NEXT_IT is IT + 1,
    get_all_sums_R(NR, NEXT_IT, R_NEXT),
    append([(A, B)], R_NEXT, R).
get_all_sums_R(NR, IT, R):-
    A is IT,
    B is NR-IT,
    A  X/2.
get_all_divisors(X, IT, R):-
    IT =< X/2,
    TMP_RES is mod(X, IT),
    TMP_RES =:= 0,
    NEXT_IT is IT + 1,
    get_all_divisors(X, NEXT_IT, R_NEXT),
    append([IT], R_NEXT, R).
get_all_divisors(X, IT, R):-
    IT =< X/2,
    NEXT_IT is IT + 1,
    get_all_divisors(X, NEXT_IT, R).

get_all_products_R([], _, []).
get_all_products_R([H|L], NR, R):-
    A is H,
    B is NR/H,
    A >= B,
    get_all_products_R(L, NR, NEXT_R),
    append([(A, B)], NEXT_R, R).
get_all_products_R([H|L], NR, R):-
    A is H,
    B is NR/H,
    A < B,
    get_all_products_R(L, NR, R).

get_all_products(NR, R):-
    get_all_divisors(NR, 2, R_LEFT),
    get_all_products_R(R_LEFT, NR, R).

single_element([_]).

final_filter([(A, B)|_], _):-
    write(A),
    P is A*B,
    S is A+B,
    get_all_products(P, PRODUCTS),
    get_all_sums(S, _),
    write(A),write(' '), write(B), write('\n'),
    not(single_element(PRODUCTS)).

Comment: What do you expect? `get_all_sums(S, _).` produces an instantiation error and `get_all_sums(4, R), false` does not terminate
Comment: I tried it % d:/newl compiled 0,00 sec, 14 clauses
1 ?- get_all_sums(4, R).
R = [ (2, 2)] .

2 ?- get_all_sums(4, _).
true .
Answer: The central misunderstanding here is what termination means in Prolog. That is, universal termination. The query of interest is the following:
?- get_all_sums(4,R).
   R = [(2,2)]█

Prolog's top-level shell offers you first a single answer. But you get more of them by entering ; or SPACE. So Prolog was not finished when showing you the first answer/solution. In fact:
?- get_all_sums(4,R).
   R = [(2,2)]
;  R = [(2,2),(3,1)]
;  R = [(2,2),(3,1),(4,0)]
;  R = [(2,2),(3,1),(4,0),(5,-1)]
;  R = [(2,2),(3,1),(4,0),(5,-1),(6,-2)]
;  R = [(2,2),(3,1),(4,0),(5,-1),(6,-2),(7,-3)]
;  R = [(2,2),(3,1),(4,0),(5,-1),(6,-2),(7,-3),(8,-4)]
;  R = [(2,2),(3,1),(4,0),(5,-1),(6,-2),(7,-3),(8,-4),(9,-5)]
; ... .

Do you really want to enumerate all negative sums? Looks infinite to me!
But let's concentrate on the non-termination property alone...
Maybe the system will stop after 8 solutions? Is there a better way to be
sure?  Simply "turn off" the display of solutions as follows:
?- get_all_sums(4,R), false.

Now we are no longer irritated by solutions/answers, and we can concentrate on the termination property alone.  I will further add such goals
false and more into your program, to localize the actual reason for non-termination.  The resulting program is called a failure-slice.  And no matter how I add false goals, it always holds that: If the failure-slice does not terminate, then the original program does not terminate either.  After a bit of trying, I get:

get_all_sums_R(NR, IT, []):- false, IT > NR - 2.
get_all_sums_R(NR, IT, R):- NR = 4,
    A is IT,
    B is NR-IT,
    A >= B,
    NEXT_IT is IT + 1,
    get_all_sums_R(NR, NEXT_IT, R_NEXT), false,
    append([(A, B)], R_NEXT, R).
get_all_sums_R(NR, IT, R):- false,
    A is IT,
    B is NR-IT,
    A < B,
    NEXT_IT is IT + 1,
    get_all_sums_R(NR, NEXT_IT, R).

get_all_sums(NR, R):-get_all_sums_R(NR, 2, R), false.

?- get_all_sums(4, R), false.

So this little remaining part is responsible for non-termination. In order to fix this, you will have to add some goals here.  To be sure: NR = 4, A increases by 1, B decreases by one.  And as long as A >= B, this loop will continue.
You might be tempted to add somewhere a cut, or a once/1. But this
will lead you only from one bug to the other.  Better address the problem above.

Prolog infinite loop issue


Discriminant of Quadratic Equation

Question: If I have a line $y=mx+c$ tangent to parabola $y^2=4ax$ and I want to find the value of c in the tangent line equation
As per my teacher, he first made the substitution $x=\frac{y^2}{4a}$ in the line equation and had the whole equation rearranged to obtain :
$$y^2-(\frac{4a}{m})y + (\frac{4a}{m})c=0$$
Then his next step was to equate the discriminant of this equation to 0 to obtain c
from which I got $c=\frac{1}{m}$
and the equation of the tangent line turned out to be $y=mx+\frac{1}{m}$
My question is why did he get me to equate the discriminant to 0?
What is the geometric interpretation of the discriminant of the quadratic equation?
I know that when the discriminant is zero the quadratic equation has two identical real roots.
Why is it imperative that the equation obtained have identical real roots?
Comment: That's exactly the definition of tangent: a line parallel to it and slightly displaced outwards has no intersection with the parabola ($\Delta<0$), a line parallel to it and slightly displaced inwards has two intersections with the parabola ($\Delta>0$). The tangent itself is the limiting case $\Delta=0$, having a single point in common with the parabola.
Comment: What definition of tangent line are you using?
Comment: tangent to a curve at a particular point is the line that touches the curve only at that one specific point
Answer: Suppose a parabola of the type P : $y^2=4ax$. Let an arbitrary line L be  $y=mx+c$.
Also,
$$y^2=m^2x^2+c^2+2mcx$$
$$4ax=m^2x^2+c^2+2mcx$$
$$m^2x^2+c^2+(2mc-4a)x=0\tag1$$
$$\Delta=(2mc-4a)^2-4m^2c^2=16a^2-16amc$$
Now for (1), you can interpret three cases, namely $(a)\Delta=0$ $(b)\Delta<0$ and $(c)\Delta>0$
Now to interpret geometrically based on the three cases of the discriminant $\Delta$.
case (a) $\Delta=0$, This implies that the quadratic equation posses a single root (or common root). This geometrically implies the two curves that were 'solved' by substituting into each other meet only once at an unique point. This is the condition you are to look for when in need for tangent as a tangent line meets a curve at one unique point only.
case (b) $\Delta>0$, This implies that the quadratic equation posses two real roots. This geometrically implies the two curves meet at two unique points as both curves solve to give two unique coordinates (for $x$ in this case). The line passes through the parabola at two different points (only).
case (c) $\Delta<0$, This implies that the quadratic equation posses complex roots. This geometrically implies the two curves meet at an "imaginary point", meaning the two curves lie on real plane and do not virtually posses an unique point of intersection.

Extras(1) - To complete form for the tangent equation you have derived
is $$\boxed{y=mx+\frac{a}{m}}$$
Extras(2) - The condition for a line $y=mx+c$ to be tangent to a
parabola $y^2=4ax$ is; $$\boxed{c=\frac{a}{m}}$$
Extras(3) - The point of contact is;
$$\boxed{\left(\frac{a}{m^2},\frac{2a}{m}\right)}$$

Note - A polynomial equation of degree $n$ can atmost have $n$ roots. A quadratic equation can have two real roots, 1 real root and no real roots or two complex roots, as complex roots occur in conjugate pairs.

Discriminant of Quadratic Equation


Failed to load resource - bootstrap error 403

Question: Everything appears as normal, however when I inspect element in my checkout page I get the following errors showing up in the console
https://maxcdn.bootstrapcdn.com/examples/navbar-static-top/navbar-static-top.css Failed to load resource: the server responded with a status of 403 (Forbidden)
https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/ie10-viewport-bug-workaround.js Failed to load resource: the server responded with a status of 403 (Forbidden)
My site has been set up for https, and I have tried the bootstrap links with and without the https: in the link.  I am new to this so it could be something silly, I would be grateful for any help.
Comment: I have changed it so all the css and js are held within my static files and I am now getting the following errors;                                                                    GET https://mywebsite.com/static/css/bootstrap.min.css/
(index):22 GET https://mywebsite.com/static/css/navbar-static-top.css/
(index):28 GET https://mywebsite.com/static/js/ie-emulation-modes-warning.js/
(index):603 GET https://mywebsite.com/static/js/jquery.min.js/
(index):605 GET https://mywebsite.com/static/js/bootstrap.min.js/
(index):607 GET https://mywebsite.com/static/js/ie10-viewport-bug-workaround.js
Answer: Here are the correct links, hope it helps
http://getbootstrap.com/examples/navbar-static-top/navbar-static-top.css
http://getbootstrap.com/assets/js/ie10-viewport-bug-workaround.js
Comment: @jameslewis if you liked the answer please upvote, if this is the definite answer mark it. thanks
Comment: This would usually work however my css and js has to be served ovver https and this was what was causing the problems to begin with.
Answer: If I were you, I would donwload the files and I would upload it to my site. If the CDN has problems... your web will have it too...
I advise you to do it.
In addition, when I try to access to the links, I can't see the files too... You should use the links which @Lightwalker posted
I hope my answer will help you!


Acrescentar ordem dos registros de acordo a data e id

Question: No R, eu tenho os seguintes dados:
 id      date
2380    10/30/12
2380    10/31/12
2380    11/1/12
2380    11/2/12
20103   10/30/12
20103   12/31/12

E eu quero acrescentar uma coluna com a ordem dos registros de acordo com a data e o id, por exemplo:
id      date       ordem
2380    10/30/12    1
2380    10/31/12    2
2380    11/1/12     3
2380    11/2/12     4
20103   10/30/12    1
20103   12/31/12    2
20100   10/05/12    2
20100   05/04/12    1
20100   11/1/12     3

Answer: Em R base, pode fazer o que a pergunta pede com a função ave. É preciso notar que a saída de ave é da mesma classe que o primeiro argumento, portanto deve-se passar a coluna date como um vetor numérico.
dados$date <- as.Date(dados$date, "%m/%d/%y")
dados$ordem2 <- ave(as.numeric(dados$date), dados$id, FUN = order)

dados
#     id       date ordem ordem2
#1  2380 2012-10-30     1      1
#2  2380 2012-10-31     2      2
#3  2380 2012-11-01     3      3
#4  2380 2012-11-02     4      4
#5 20103 2012-10-30     1      1
#6 20103 2012-12-31     2      2
#7 20100 2012-10-05     2      2
#8 20100 2012-05-04     1      1
#9 20100 2012-11-01     3      3

Dados.
dados <- read.table(text = "
id      date       ordem
2380    10/30/12    1
2380    10/31/12    2
2380    11/1/12     3
2380    11/2/12     4
20103   10/30/12    1
20103   12/31/12    2
20100   10/05/12    2
20100   05/04/12    1
20100   11/1/12     3
", header = TRUE)


Controlling a window that I did not start

Question: I am writing a simple install script with TestStack White so i can learn the framework (I didn't find a lot of info online).
I'm using league of legend install for this little experiment
after I fill the forms, and pressing the next buttons, there is a window that opens from the install program.
I want to know if there is a way to GET the window even if i wasn't the one who executing it.
this is the code i'm using to run the application, up to the moment the new window opens:
private void pressXButton(White.Core.UIItems.WindowItems.Window currentWindow, string buttonName)
    {
        var xButton = currentWindow.Get<White.Core.UIItems.Button>(White.Core.UIItems.Finders.SearchCriteria.ByText(buttonName));
        xButton.Click();
        currentWindow.WaitWhileBusy();
    }

    public void RunScript()
    {
        White.Core.Application application = White.Core.Application.Launch(filePath);
        White.Core.UIItems.WindowItems.Window window = application.GetWindow(windowTitle);
        window.WaitWhileBusy();

        pressXButton(window, NEXT_BUTTON_TEXT);

        var radioButtonAgree = window.Get<White.Core.UIItems.RadioButton>(White.Core.UIItems.Finders.SearchCriteria.ByText("I accept the terms in the License Agreement"));
        radioButtonAgree.Select();
        window.WaitWhileBusy();

        pressXButton(window, NEXT_BUTTON_TEXT);
        pressXButton(window, NEXT_BUTTON_TEXT);
        pressXButton(window, NEXT_BUTTON_TEXT);
        pressXButton(window, NEXT_BUTTON_TEXT);
        pressXButton(window, NEXT_BUTTON_TEXT);
        pressXButton(window, "Install");

//afther pressing the Install Button the program ask to install  Microsoft Visual C++ 2005 Redistributable Package and here is where im stcuk

    }

(sorry for my english)
Answer: You can use Desktop.Instance.Windows() to get at all the windows, not just the ones in the process you are testing.
Otherwise you have to use Application.Attach("processname") to get the process of the Microsoft Visual C++ 2005 Redistributable Package


Filter category taxonomy with tabs

Question: i have a node which is of content type "Album", they all have categories defined by terms , and i want the user to be able to choose which category he want to filter by but with tabs instead of a dropdown list.
Cant find anything on the internet so this is my last hope.
Thank you.
Answer: Have a look at the quicktabs module. You could use it to embed views in each tab, based on your required filter options there. For example, you can pass a contextual filter option to the quicktab for a single view display to show that content only.
Alternatively, the better_exposed_filters module may provide some options for you, such as a list of links, instead of a select box.
Comment: Method #1: How would you do that? the way i see quicktabs module, i gotta add each term as a tab manually?
Comment: You can pass view contextual filters for the term id to the view in the quicktabs configuration.

Filter category taxonomy with tabs