Regarding flattening a 3 variables experiment to conduct one-way repeated measures ANOVA

Question: I recently conducted an experiment where I had participants experience 8 conditions in a 2x2 manner (two variables and their combinations). This was primarily to give us an opportunity to observe how they work in different situations while under the same condition. My primary dependent variable is completion time. However, I am less interested in studying how completion time was moderated in the 2x2 case quantitatively (more so qualitatively). Instead, I am more broadly interested in whether completion time differed between the conditions (combining the scores from the 2x2 trials). Is it considered acceptable in such a scenario to conduct a one-way repeated measures ANOVA as opposed to studying the three-way interaction?
EDIT: to add a bit more context, upon conducting the three-way repeated measures there is a statistically signifiicant three-way interaction effect, as well as one statistically significant two-way interaction effect, and all three variables are statistically significant on their own.
Comment: You may want to search CV for `lsmeans` or `contrasts` which could clue you in on how you might approach this:  https://stats.stackexchange.com/tags/lsmeans/hot
Comment: Thanks for the suggestion, I will have a look!
Answer: This situation may be a little simpler than yours, but I hope it points the
way to some useful possibilities. Suppose two drugs A and B are under study
for treatment of a condition. One hundred subjects exhibiting the condition are
recruited and randomly assigned, 25 each, to four different 'treatments': A only, B only, both A & B, and neither: for short A, B, AB, and N.
Simulated data might be as follows:
set.seed(2020)
x1 = rnorm(25, 104, 10)
x2 = rnorm(25, 106, 10)
x3 = rnorm(25, 110, 10)
x4 = rnorm(25, 100, 10)
x = c(x1,x2,x3,x4);  gp = rep(1:4, each=25)
stripchart(x~gp, ylim=c(.7, 4.3), pch="|")

You could analyze this as a one-way ANOVA with treatment levels as the factor.
You would have the choice of a standard one-way ANOVA, assuming variances equal
in each of the four groups, or by using the procedure oneway.test in R. For my fake data, there are significant differences among the four group population means, as shown by
the P-value 0.0067.
Then you could use Welch two-sample t tests ad hoc to explore
differences of particular interest: for example, A vs. B, various treatments
using drugs vs. the placebo, and so on. If you are going to look at all six pairs
of the four levels, you should use some method (perhaps Bonferroni) to protect
against 'false discovery'.
oneway.test(x~gp)

        One-way analysis of means (not assuming equal variances)

data:  x and gp
F = 4.5322, num df = 3.000, denom df = 52.201, p-value = 0.006741

However, if it seems clear in advance that the four groups should have equal variances,
you could use a standard ANOVA that assumes equal variances.
lm.out = lm(x ~ as.factor(gp))
anova(lm.out)
Analysis of Variance Table

Response: x
              Df  Sum Sq Mean Sq F value  Pr(>F)
as.factor(gp)  3  1824.4  608.14  4.7253 0.00405 **
Residuals     96 12355.2  128.70
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Notice that you have three DF for Factor. As suggested in a comment by @StatStudentm you could look into contrasts. You could use "three pre-planned"
orthogonal contrasts, perhaps ones with coefficients $(1,-1,0,0)$ [to see if drug A is better than B],
$(0,0,1,-1)$ [to see if two drugs are better than none], and
$(1,1,-1,-1)$ [to see if one drug is better than two or none].
Alternatively, you could look at a two-way ANOVA, with factors Drug A (levels Yes and No) and Drug B (levels Yes and No). Then the first three lines of the ANOVA table
would be for Drug A, Drug B, and Interaction. These three would have one DF each, with an F-test for each. [In the one-way ANOVA, you could find three orthogonal contrasts
that correspond to these three lines of the two-way table: $c(1,-1,1-1),$
$(-1,1,1,-1),$ $(-1,-1,1,1),$ respectively.]
A comparison of the standard one-way ANOVA (with contrasts for A, B, and Interaction)
and the standard two-way ANOVA (in which these comparisons are lines in the table). shows that you can 'flatten' a two-way ANOVA to a one-way ANOVA without losing options for comparisons. In many cases, it is simpler to do the two-way ANOVA, especially
if the comparisons of interest correspond to the effects.
If there is concern about unequal group variances, then it seems better to use oneway.test to adjust for unequal variances, and then do ad hoc Welch t tests.
(As far as I know, the Satterthwaite correction used by one-way.test and Welch t tests has not yet been implemented for two and more factors.)
Comment: Thank you for the detailed response! This is very helpful.


Evaluating Difficult Monte Carlo Integration in R

Question: I recently posted a simple version here (Simple Monte Carlo Integration).
I was able to verify that the answer was indeed close to 1/3 when I wrote the following R code, and got a mean of X of ~1/3:
U = runif(10000,0,1)
X = U^2
mean(X)
I am applying a more difficult Monte Carlo Integration now for two reasons. First, the integration is between 0 and infinity. Second, I believe the integration leads to gamma functions. What is the simplest way to approach the following problem, especially using a simple simulation as I did above (generating 10,000 uniform values and simulating in R):
$$\displaystyle \int_0^\infty \dfrac 34 x^4e^{-x^{3/4}}\,dx$$
I do not even know what value to expect (like I did in my previous post, where I knew my simulation should approximate 1/3). Even if I did, I do not know where I would use the 10000 uniform samples between 0 and 1, as this problem is now between 0 and infinity.
Comment: For smooth curves integrated over finite intervals, you can usually get better accuracy for a given amount of computer time doing Riemann integration (approximation by narrow rectangles). By contrast, MC integration is often more accurate/efficient  in higher dimensions.
Comment: Perhaps see `http://math.stackexchange.com/questions/1635250/` for more on Monte Carlo integration.
Answer: We are trying to use Monte Carlo Simulation to find:
$$\displaystyle \int_0^\infty \dfrac 34 x^4e^{-x^{3/4}}\,dx$$
As you have discovered, the infinite limits are problematic. We can do several things to overcome this
Approach 1: A naive approach is to plot the function given that it has a decaying exponential which tends to zero very quickly. If we plot this function, we see:

So, lets try to approximate it as:
$$\displaystyle \int_0^{50} \dfrac 34 x^4e^{-x^{3/4}}\,dx$$
Using your approach (recall, now your code needs to change to generate random numbers $(a, b)$ and with the function of interest) with $n = 10000$, we get:
$$I = 387.256$$
If we calculate the exact integral we get:
$$I = \Gamma \left(\frac{20}{3}\right) \approx 389.035$$
Approach 2: In this approach we will make a change in variables so as to map an infinite range of integration into a finite one.
A good example that works for functions that decrease towards infinity faster than $\frac{1}{x^2}$ is to use:
$$\displaystyle \int_a^b f(x)~dx = \int_{\frac{1}{a}}^{\frac{1}{b}} \dfrac{1}{t^2}f\left(\dfrac{1}{t}\right)~dt$$
With this altered approach, we can now do integrals when one of the limits is infinite
and the other limit is of the same sign. If you need to integrate say something that has $a = 0$, what you do is break the integral into two parts and use Monte Carlo on each one.
If we have infinite limits for both limits, we could split the integral into three or more parts. So, for this problem, we have to split it into two pieces as:
$$\displaystyle \int_0^\infty \dfrac 34 x^4e^{-x^{3/4}}\,dx = \int_0^1 \dfrac 34 x^4e^{-x^{3/4}}\,dx + \int_0^1 \dfrac{1}{t^2} \left(\dfrac 34\right) \left(\dfrac 1t \right)^4 e^{{-(\frac 1t)}^{\frac 34}}~dt$$
Using the Monte Carlo for the first part, we get $I_1 = 0.0647226$ and for the second part, we get $I_2 = 387.551$, which yields:
$$ \displaystyle \int_0^\infty \dfrac 34 x^4e^{-x^{3/4}}\,dx = 387.616$$
Compare that to our previous and the exact result.
Approach 3: In this approach we will make a change in variables so as to map an infinite range of integration into a finite one. This time, we will transform variables using $u = \frac{1}{1+x}$, yielding:
$$\displaystyle \int_0^\infty \dfrac 34 x^4e^{-x^{3/4}}\,dx = \int_0^1 \frac{3 e^{-\left(\frac{1-u}{u}\right)^{3/4}} (1-u)^4}{4 u^6} ~ du$$
Running the Monte Carlo simulation with $n = 10000$ yields:
$$I = 390.18704821709946$$
Comment: Like a complete and concrete source!
Answer: One approach is to not sample uniformly on anything. This approach is nice because you can continue to get improved accuracy without having to restart the calculation to change the interval size.
The idea is importance sampling. Here there is a fairly easy importance sampling approach: you want something that has a factor of $e^{-x^{3/4}}$ and is also easy to integrate. If you had to analytically integrate something with a factor of $e^{-x^{3/4}}$, you would want a factor of $x^{-1/4}$ to serve as your "$du$". To this end, you can write your integral as
$$\frac{3C}{4} \int_0^\infty x^{17/4} \frac{e^{-x^{3/4}} x^{-1/4}}{C} dx$$
where $C=\int_0^\infty e^{-x^{3/4}} x^{-1/4} dx = \frac{4}{3}$. Having written this, we conclude that if $\xi$ has the density $\frac{e^{-x^{3/4}} x^{-1/4}}{C}$ then your integral is $\frac{3C}{4} \mathbb{E} \left [\xi^{17/4} \right ]=\mathbb{E}[\xi^{17/4}]$. Next the CDF of $\xi$ is just $e^{-x^{3/4}}$ for $x \geq 0$. Hence the quantile function (on the relevant range) is $Q(x)=\ln(1/x)^{4/3}$. Hence your integral is $\mathbb{E}[\ln(1/U)^{17/3}]$ where $U$ is uniformly distributed on $(0,1)$. (Note that this way of rewriting it has also exposed how to get the exact solution: $\ln(1/U)$ is Exp(1) distributed, so this is actually telling you that your original integral was $\Gamma(20/3)$.)
Notably this approach generates a lot of samples near $0$, where $x^{17/4}$ is small, but it should still work.
Also, given the $3/4$ in the original integral, I suspect that this approach was the one anticipated by the author of the question (since it cancels nicely with the normalization constant in this formulation).
Answer: Another approach is compute the integral by Gauss-Laguerre numerical integration, which is very suitable in this case:
$$\int_{0}^{\infty}\frac{3}{4}x^4e^{-x^{3/4}}dx = \int_{0}^{\infty}\frac{3}{4}x^4e^{(-x^{3/4}+x)}e^{-x}dx$$
Considering the generalized Gauss-Laguerre quadrature:
$$\int_{0}^{\infty} x^{\alpha}f(x)e^{-x}dx$$
$$\begin{align}\alpha &= 4, & f(x) = \frac{3}{4}e^{(-x^{3/4}+x)}\end{align}$$
Results:
$\Gamma(\frac{20}{3})$ = 389.034926246
Gauss Laguerre (20 points) = 389.03475968
Gauss Laguerre (50 points) = 389.034926232


Mean value weighed by inverse distance

Question: I want to estimate the value $Z$ for some point $(X, Y)$. I know the values for some points. The situation is illustrated in the following image.

I know the $Z$ values for points $p_1...p_4$, and I want to estimate $Z$ value for $p$. The value would be calculated as a weighed mean of the four known values. So the value would be
<code>Z = (w1 * z1 + w2 * z2 + w3 * z3 + w4 * z4) / 4
</code>
I want weights to be inversely proportional to the distance ( w1 ~ 1 / d1, w2 ~ 1 / d2 and so on). This means, that the points closest to p will influence the value of Z the most.
Could someone help me to come up with the formula (or weights)?
Answer: A working formula seems to be
$$Z = \frac{\frac{1}{d_1} \cdot z_1 + \frac{1}{d_2} \cdot  z_2 + \frac{1}{d_3} \cdot z_3 + \frac{1}{d_4} \cdot z_4}{\frac{1}{d_1} + \frac{1}{d_2} + \frac{1}{d_3} + \frac{1}{d_4}}$$
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).

Mean value weighed by inverse distance


Eixos de um plano cartesiano mudando de acordo com o zoom HTML5(canvas) + JAVASCRIPT

Question: Galera é o seguinte, estou fazendo com js + html5 e canvas um programa para plotar gráficos:

Gostaria de implementar um zoom + e -, como na imagem, e voltar ao zoom original ao clicar em '='.
A minha dificuldade esta no seguinte: após dar o zoom, os eixos cartesianos 'x' e 'y' tem que mudar os seus valores não é ?
Exemplo: http://jsxgraph.uni-bayreuth.de/wp/examples/, após apertar o botão de '+' os valores dos eixos mudam, outro exemplo é o gráfico do google, após dar o zoom os valores do eixos mudam.
Eu queria mais ou menos isso, queria a idéia de como fazer isso, mudar os valores dos eixos de acordo com o zoom, ou exemplos já prontos, ou alguma solução parecida!!!
Comment: Estava vendo a documentação do `canvas` quando me deparei com a propriedade `ctx.scale(2, 2)`, acredito que pode trabalhar com ela
Comment: Aqui uma resposta pra sua pergunta: http://pt.stackoverflow.com/a/61161/14262
Comment: @MarceloBonifazio, nao é isso que eu quero, acho que voce entendeu errado, esse efeito de zoom e scale eu ja tenho, esta funcionando perfeitamente, o que eu quero é, que apos aumentar o zoom ou scale (tanto faz) os valores dos eixos mudem, como no exemplo aqui: http://prntscr.com/7wh9dt apos dar o zoom os eixos ficaram mudaram o valor http://prntscr.com/7wh9jt, e assim vai mudando o valor a cada click, o que eu quero é isso.
Comment: Acho que não há necessidade de fazer isso, mas você pode usar o valor da escala pra aplicar a cada x e y dessa forma: `novoX = valorDaEscala + x`  ; `novoY = valorDaEscala + y`
Comment: Nao sei se aplicaria muito bem isso, porque a minha escala ja começa com 50, como ficaria? E a cada click a scale é acrestado + 25, ou seja, começa com 50, depois 75 depois 100 depois 125...(considerando o que estou clicando no '+'. Nao entendi muito bem o que voce quis dizer; Lemrando que, o que é modificado a cada click é a escala, nao o zoom, o zoom é sempre fixo,
Comment: Descarte meu ultimo comentario! Nao entendi como ficaria as modificações dos eixos de acordo com o click, pq a minha escala inicial é 1, ou seja, ctx.scale(1,1), é fixo esse valor, nunca muda. O que eu mudo a cada click, é a escala da 'linha' da função, somente a 'linha' da função é mudada a sua escala, nao a tela toda.  http://www.w3schools.com/tags/canvas_scale.asp ): perceba que quando aumenta a escala, a borda da linha tmb muda, entao ficaria muito 'escroto' aumentar a scale da tela toda, entao eu tenho uma variavel scale, que determina a scale somente da linha da minha função
Answer: Código adaptado de: http://jsfiddle.net/ndYdk/7/
Com o fator da escala você aplica somente ao desenho de dentro(aos pontos do interior do canvas) sem se preocupar com o tamanho do canvas.

function desenhar(escala, posicao){
  var canvas = document.getElementById("myCanvas");
  var context = canvas.getContext("2d");

  context.clearRect(0, 0, canvas.width, canvas.height);

  context.save();
  context.translate(posicao.x, posicao.y);
  context.scale(escala, escala);
  context.beginPath();
  context.moveTo(80, 50);
  context.bezierCurveTo(20,-100, -139, -80, -30, 50);
  context.closePath();

  context.fillStyle = 'blue';
  context.fill();

  context.stroke();
  context.restore();
}

var iniciar = (function(){
  var canvas = document.getElementById("myCanvas");

  var posicao = {
    x: canvas.width / 2,
    y: canvas.height / 2
  };

  var escala = 1.0;
  var fatorMultiplicacao = 0.8;

  document.getElementById("plus").addEventListener("click", function(){
    escala /= fatorMultiplicacao;
    desenhar(escala, posicao);
  }, false);

  document.getElementById("minus").addEventListener("click", function(){
    escala *= fatorMultiplicacao;
    desenhar(escala, posicao);
  }, false);

  desenhar(escala, posicao);
}());
<canvas id="myCanvas" style="width: 300px;"></canvas>
<input type="button" id="plus" value="+">
<input type="button" id="minus" value="-">
Comment: Entendi marcelo, mas a minha dúvida nao é essa, o meu grafico ele ta zoom, com esse mesmo exemplo que vc postou, a minha dúvida é essa, a cada click no '+', aqueles numeros mudarem de valor, como no exemplo acima, a cada click no '+' (no grafico do google) os numeros dos eixos mudam, eu quero isso, que eles mudem, o meu grafico da o zoom, ele cresce tranquilo, so que os numeros dos eixos cartesianos nao acompanham o crescimento, eles ficam 'parado', exe: http://prntscr.com/7wmchd, depois de 3 clicks no '+' > http://prntscr.com/7wmcza. Percebeu que os numeros dos eixos 'y' nao mudaram ?
Comment: Eu queria que o valor '1' que esta na primeira imagem, acompanhasse o crescimento, ou seja, a cada click o '1' fosse subindo junto com o grafico
Comment: Sim entendi, poste o código da sua função
Comment: http://pastebin.com/izNpcGPV, o codigo esta meio 'tosco' até pq estou apgando ele muito, mas irei deixar 'certo'. A função showAxes(context), é que plota os eixos 'x' e 'y' tem 2 laços de repetição, um para cada eixo, para plotar tambem os numeros. qualquer coisa me adiciona skype. fillipe.santos6
Comment: Tem como criar um http://jsfiddle.net/ ja com o HTML minimo embutido? ficaria bem mais fácil editar
Comment: Estou tendo dificuldade para colocar lá, sao uns 4 arquivos js's e css


Disabling a button if an immutable list contains empty value

Question: If a user enters a blank value in a textbox, the button should be disabled.
I'm doing this check  using the following filter.But this does not work.Please advice.
                   <ALink href='javascript:void(0);'
                    className='button primary default-size' id='globalParametersCancel'
                    content={localeHelper.translate('iaSampling.iaGlobalConfiguration.reset')}
                    isDisabled={(!this.globalParameterChanged) && (!this.gaparameterlist?.find(x => x.value == ' '))}
                    onClick={this.reset} />

Comment: Why did you put `space` in  `' '`?
Comment: Do you use any js framework to rerender ? Is it reactjs or what?
Comment: @NghiNguyen i just set the state again by calling a method.
Comment: A bit hard to find the context of problem you're facing now? I don't know ALink is component is support isDisable or not? And how event effect to  this.globalParameterChanged and this.gaparameterlist state here ? Could you show more detail of your code ?
Answer: If you are using React you could do something like this, imagine you had an input field with an onChange. You can set the state in the change handler equal to e.target.value. When the state has changed, the useEffect() callback is called and will check if the input is valid. If the input is valid (you could do any validation you like, for example date, number, regular expression...), you set valid (setValid(true)).
// callback after setting text
useEffect(() => {
  // do validation
  if (text) {
    setValid(true);
  } else {
    setValid(false);
  }
}, [text]);

const handleChange = (e) => {
  e.preventDefault(); // prevent default action
  setText(e.target.value); // set text
};

Then, according to the valid boolean state value, you could render what you want, in this case a button, if not valid => display a message or whatever you like.
const validDisplay = valid ? (
  <button onClick={handleClick}>submit</button>
) : (
  Not valid!
);

This is what your final return could look like.
return (

    <input value={text} onChange={handleChange}></input>

      {validDisplay} {text}

);

I made a sandbox, you can try it out here


Proof of $|x^{\alpha} - y^{\alpha}| \le \alpha^{\alpha} |x-y|$ for $\alpha \ge 1, x,y\in [0,1]$

Question: I want to prove
$$
 |x^{\alpha} - y^{\alpha}| \le \alpha^{\alpha} |x-y|
$$
for $\alpha \ge 1$ and $x,y \in [0,1]$. For $\alpha \in \mathbb N$ I already got the proof by using the formulae
$$
 (x^n - y^n) = (x-y)(x^{n-1} + x^{n-2}y + \ldots + xy^{n-2} + y^{n-1})
$$
but I have no idea how to generalize to arbitrary $\alpha \ge 0$, any hints?
Answer: Hint:
$$(x^{\alpha} - \alpha^{\alpha} x)' = \alpha(x^{\alpha-1} - \alpha^{\alpha-1}) < 0.$$
Comment: got solution by some algebra with you hint, thx.
Answer: Let $f(t)= \alpha^{-\alpha}t^\alpha=\left(\frac{t}{\alpha}\right)^\alpha$.
Then $f''(t) = \alpha^{-\alpha +1}(\alpha -1)t^{\alpha-2} \geq 0$ whenever $0<t<1$.
Thus $f$ is convex over $[0,1]$.
For $x \neq y$ let
$$F(x,y)= \frac{f(x) - f(y) }{x-y}.
$$
Show that $\left|F(x,y)\right|\leq 1$ over the region of interest using the convexity of $f$. This will imply your inequality.
Comment: got solution by mean value theorem with you hint, thx.


D7 Field template syntax

Question: My D7 content type has a field for an MP3 file. I want the field to display as an image which the user can then right click to download the file ie like this. My field template file looks like this:

<?php
$link = 'http://www.desertcow.co.uk/pirates.mp4'; // url link?>
<a href="<?php print $link;?>">

<a href="<?php print render($items); ?>">

<a href="<?php print render($items); ?>

The result is here and you can see that the syntax for the pink and red boxes is not correct.
Can anyone please tell me the correct syntax or is there some reason that this approach is not going to work?
Thanks...
Answer: This is because you're rendering the full item when all you want is the url as a string, if you add this line of code in the template you will be able to see where the url is held in the $items array.
<?php var_dump($items); ?>

then you can find the part of the array where the url string is so your final markup would be something like this.

<a href="<?php echo $items['url']; ?>">

Comment: @ Daniel thank you. I am nearly there but I think I am not supposed to ask a further question here so I posted a new question. http://drupal.stackexchange.com/questions/77075/d7-syntax-in-field-template

D7 Field template syntax


Why doesn't my code for extracting the first principal component work?

Question: Following the Wikipedia article on PCA, I extract the weights of the first principal component by calculating
$$\textbf{w}_1 = \mathrm{\arg\ max} \left\{ \frac{\textbf{w}^\intercal \textbf{X}^\intercal \textbf{X} \textbf{w}}{\textbf{w}^\intercal \textbf{w}} \right\}.$$
However, my R code for doing so with doesn't seem to correspond with the output of R's prcomp() function.
# Set seed
set.seed(1)

# Initialize and scale data
X = diag(10)
X = scale(X)

# Define objective function
objec = function(w){ (t(w)%*%t(X)%*%X%*%w)/(t(w)%*%w) }

# Run optimization with Nelder--Mead method
o = optim(c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0), objec,
          control=list(maxit=10000, fnscale=-1), method="Nelder-Mead")

# Check output
print(o)

# Print out output of optimization
o$par

# Print out output of prcomp()'s first principal component
prcomp(X)$rotation[, 1]

What's going on?
Comment: Given that this has a good (& software-neutral) answer, I think it could stay open here.
Comment: This vector `X` has *nine* "first" principal components!  The eigenspace for the largest eigenvalue has nine dimensions.  It would be a miracle if any two different--but fully correct--algorithms were to produce the same bases for them.  Try a random symmetric matrix instead.  BTW, here's a simpler algorithm. The last line finds the eigenvalue. `w <- rnorm(dim(X)[1]);
v <- abs(w) + 1;
while(crossprod(v-w) > 1e-16) {
  v <- w;
  w <- X %*% w;
  w <- w / sqrt(sum(w*w))
};
(w);
(X %*% w) / w`
Comment: Be aware that code-check (& exclusively software usage) questions are off topic here. In light of that, you would do best to suplement or re-write your code using mathematical notation or pseudocode.
Comment: @whuber Yes! That is the true issue here. +1.
Comment: As I wrote in a comment below my answer "Yeah, not being an R guy, i didn't pay attention to the particular value of X until after I posted my answer, but even for a "joe average" X (in the best case), everything I wrote applies."
Answer: What you're using is an absolutely horrid and unreliable method for computing the eigenvector corresponding to the largest eigenvalue of $X^TX$. Both in formulation and in choice of optimization algorithms (Nelder-Mead? Seriously? This is the 21st century.)
Your optimization may not have converged, and if it did, it, it may have converged to the wrong answer.
If it did converge to the solution of the problem as input to the optimizer, it is only unique to within a scale factor applied to the solution w.  This lack of uniqueness is one of only several things complicating your optimization.  If you divide each component of your "optimal" w by $\sqrt{(w^Tw)}$, then it will have unit norm, as does the output of prcomp(X)$rotation[, 1], and is unique to within a scale factor of +/-1, and it is "arbitrary" which of these (+/-1) is chosen.
So in short, if your solution w, divided by $\sqrt{(w^Tw)}$ matches the output of prcomp(X)$rotation[, 1], or the negative of this output, then you have obtained agreement.  If it doesn't, then your solution is wrong.
If you provide the (+ or -) unit norm eigenvector corresponding to the largest eigenvalue of $X^TX$ as a starting value to your optimizer, hopefully it will "converge" to the correct solution, i.e., stay roughly where it started.  As your starting point moves further from the solution, the optimizer will have more difficulty converging to the correct solution.  I don't know what starting point your optimization is using, but note that w equal to the vector of zeros, which is the most common default value of starting point, could be problematic given your objective function.
Did you run optim with highest (most detailed) level of information output?  If not, you should. What does it say? Not that I would trust much coming from Nelder-Mead regarding convergence.
The point of your whole exercise should be only pedagogical, i.e., to illustrate why this is not a good approach, and you should use ready made, purpose-built algorithms (at least at the eigenvector or preferably singular vector level, if not principal component) for actual computation in which you want to reliably get the answer.
Comment: @MatthewDrury Indeed. Stimulated by this eloquent answer, I opened the [Wikipedia page](https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method) on Nelder-Mead and saw it starting with "The Nelder–Mead method or downhill simplex method or amoeba method"... Amoeba method!
Comment: I knew it was @MarkLStone from the first line.
Comment: Having said that, I strongly suspect that the quality of Nelder-Mead algorithm has *nothing* to do with the issue at hand. See whuber's comment to OP for what is probably the real issue here.
Comment: @Matthew Drury  There's no shortage of bad numerical methods. I still remember my 10th grade Algebra II teacher (RIP) telling us that computers solve systems of linear equations using Cramer's rule (determinants), because they're not smart enough to do elimination. Yeah, maybe when he programmed the computers. In the interest of fairness (A --> B does not imply B --> A), maybe when a post starts as this one does, it must be mine, but many of my posts, even those related to numerical methods or optimization, do not start in such a fashion at all.
Comment: Thank you for the detailed and clarifying answer. I'm embarrassed by the fact that I used `diag(10)` as a testing matrix, but did indeed run into similar problems with matrices that didn't have any multiplicities in the eigenvalues. I'll certainly take a look at how some more advanced optimization methods perform.
Comment: Yeah, not being an R guy, i didn't pay attention to the particular value of X until after I posted my answer, but even for a "joe average" X (in the best case), everything I wrote applies.


Probability mass function of a random walk process

Question: Let $Y_n$ be a random walk process defined as
$Y_n = Y_{n-1} + X_n$; $n = 1,2\ldots$ and $Y_0 = 0$,
where $X_k = +1$ with probability $p$ and $-1$ with probability $1-p$. Write down the pmf for $Y_n$, and
$E[Y_n]$ and $\operatorname{Var}[Y_n]$.
Comment: For pmf, let $z=(n+y)/2$.  So $z$ steps forward, $n-z$ steps back, $z$ heads, $n-z$ tails. For $E(Y_n)$, the pmf is less pleasant than just writing down the answer. For variance, don't use pmf, use expectation of a sum fact.
Answer: HINTS: $Y_1 = Y_0 + X_1 = X_1$, $Y_2=Y_1+X_2 = X_1+X_2$, $Y_3 = Y_2 + X_3 = X_1+X_2+X_3$, $\ldots$
Each $X_k = 2 U_k - 1$, where $U_k$ is Bernoulli rv, with $\mathbb{P}(U_k = 1) = p$.
The sum of $n$ i.i.d. Bernoulli random variables follows the well-known distribution.
Comment: I tried something similar, but was stuck at the Xk=2Uk-1. Initially couldnt figure out why Xk takes the form 2Uk-1, but now i do.Thanks a ton.
Comment: @CZR: if you liked the answer (which I guess from your comment) - don't forget to upvote it (by clicking on up-arrow to the left of the answer) and accept it if you think the answer by Sasha is complete


Botões não animam corretamente e página fica pequena em dispositivos móveis

Question: Nessa página possuo dois problemas:

Os botões de dentro da body não esmaecem como os que estão dentro do footer.
A página não se adapta ao dispositivo que está sendo exibida.

Mas o principal problema mesmo é o 1º.
Não entendo praticamente nada de html e criei essa página do zero. Quem puder me ajudar ficarei imensamente grato! :)

html {
    font-family: 'Exo 2', sans-serif;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    list-style-type: none;
    background: #DAE1E9;
}

body, header {
    margin: 50px;
}

footer {
    margin: 25px;
}

h3 {
    color: #D76018;
    transition: 0.5s;
}

p {
    color: #D76018;
    font-size: 11px;
    transition: 0.5s;
}

.botoes-principais {
    font-size: 18px;
    padding: 18px;
    color: #DAE1E9;
    text-decoration: none;
    border: none;
    border-radius: 256px;
    display: list-item;
    margin: 10px;
    position: relative;
    box-sizing: border-box;
    transition: 0.5s;
}

.botoes-secundarios {
    font-size: 16px;
    padding: 5px 2.5%;
    color: #DAE1E9;
    text-decoration: none;
    border: none;
    border-radius: 256px;
    display: list-item;
    margin: 10px;
    position: relative;
    box-sizing: border-box;
    transition: 0.5s;
}

.botao-wpp {
    background: linear-gradient(75deg, rgba(0, 154, 68) 0%, rgba(0, 132, 61) 100%);
}

.botao-wpp:hover {
    background: rgba(0,0,0,0) 0%;
    color: rgba(0,154,68,1);
    box-shadow: inset 0 0 0 2px rgba(0,154,68,1);
}

.botao-ig {
    background: linear-gradient(75deg, rgba(255,208,64,1) 0%, rgba(215,96,24,1) 100%);
}

.botao-ig:hover {
    background: rgba(0,0,0,0) 0%;
    color: rgba(215,96,24,1);
    box-shadow: inset 0 0 0 2px rgba(215,96,24,1);
}

.botao-fb {
    background: linear-gradient(75deg, rgba(14,155,216,1) 0%, rgba(3,88,124,1) 100%);
}

.botao-fb:hover {
    background: rgba(0,0,0,0) 0%;
    color: rgba(3,88,124,1);
    box-shadow: inset 0 0 0 2px rgba(3,88,124,1);
}

.avaliacao {
    background: rgba(215,96,24,1);
}

.avaliacao:hover {
    background: rgba(0,0,0,0) 0%;
    color: rgba(215,96,24,1);
    box-shadow: inset 0 0 0 2px rgba(215,96,24,1);
}

.botao-email {
    font-size: 16px;
    padding: 10px;
    text-decoration: none;
    border-radius: 256px;
    display: list-item;
    margin: 10px;
    position: relative;
    box-sizing: border-box;
    background: rgba(0,0,0,0) 0%;
    color: rgba(3,88,124,1);
    width: 312px;
    box-shadow: inset 0 0 0 2px rgba(3,88,124,1);
    transition: 0.5s;
}

.botao-email:hover {
    background: rgba(3,88,124,1) 100%;
    color: #DAE1E9;
    box-shadow: inset 0 0 0 0px rgba(3,88,124,1);
}
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel='stylesheet' type='text/css' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.css'>
    <link rel='stylesheet' type='text/css' href='https://fonts.googleapis.com/css?family=Exo%202'>
    <meta charset="UTF-8" name="viewport>

    <a

Redes sociais

     whatsapp
     instagram
     facebook

    avalie a gente no
    avalie a gente no

      email@example.com

Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: A tag header está antes da tag body e o footer depois, o que não pode acontecer, pois a tag body é o corpo do documento, e só será mostrado o que tiver dentro dessa tag.
Dentro de head temos a
<meta name="viewport" content="width=device-width, initial-scale=1">

que define o nível de zoom inicial quando o usuário visita a página e o viewport com a largura do dispositivo.
Estrutura correta:
<!DOCTYPE html>

      <meta name="viewport" content="width=device-width, initial-scale=1">
      <meta charset="UTF-8">

No CSS, os botões do footer são diferentes na transição, pois, as suas cores são fixas, não tendo degrades entre 2 cores como os botões de WhatsApp, Facebook e Instagram.
Comment: Muito obrigado mesmo!!! :D


Display online NSE (National Stock Exchange) data in php web application

Question: I want to display online NSE (National Stock Exchange) data in my php web application. Please help me how to do this.
Comment: Can you clarify what the problem is or are you having problems starting all together?
Comment: Hi Ashok, I am also working on a similar project. Can you please answer finally what method you have implemented for your application ? If your application is live can you provide the URL. Thanks.
Answer: You can use google api .. they provide real time data for NSE.
but the catch is google finance api is available for java only it was not available for c# last time i checked.
Not sure about whether finance api are there for PHP.
Answer: Find out if NSX has a web service that exposes the stock charts. If so, this will likely be a REST or a SOAP endpoint that can be queried for specific stocks.
Create a PHP component that makes a request to that endpoint, and caches the results for a certain period of time (so that your site visitors don't have to wait for the roundtrip every time a page is loaded).
Answer: NSE don't have any web service AFAIK, the only thing they export is previous day data. You might have to do some sort of data parsing on the NSE webpages.
Answer: If you want to take historical data from NSE website, you can always do that.
for example, following is the url to retrieve nifty index data.
[http://www.nseindia.com/content/indices/histdata/S&P%20CNX%20NIFTY01-02-2010-04-02-2010.csv]
observe date pattern in the url, it is from 01 FEB 2010 to 04 FEB 2010.
change dates as you need, call the url from your server. It is csv format, so any language can process it.
Regards.
http://www.kakup.com


Show that $P$ lies inside an even number of triangles with vertices among $A_1 , . . . , A _{2m}$

Question:
Assume a convex $2m$-gon $A_1 , . . . , A _{2m}$ . In its interior we choose a point $P$ , which
does not lie on any diagonal. Show that $P$ lies inside an even number of triangles
with vertices among $A_1 , . . . , A _{2m}.$

This is from Problem solving strategies, Invariance chapter. I tried to find the invariance, but couldn't get one till now.
Any hints would be helpful.
Comment: Draw *all* the diagonals in that picture (you're missing $AF$). Imagine your point moving across exactly one of those diagonals. Show that the number of triangles it is in changes by an even number.
Comment: Your image is a convex 7-gon, not a convex 8-gon.
Comment: @GerryMyerson oops! i forgot that, but that doesn't effect, i think?
Comment: Not to intrude, but how did you obtain Engel in India? I thought it was too costly to obtain from abroad
Answer: Let the point be outside. In this case, it lies inside even number of triangles i.e., zero.
Now move that point through every region in such a way its locus does not cross any intersection point. Suppose that point crosses $A_iA_j$ then it goes out of all triangles of form $A_iA_jA_k$ and moves inside all triangles of form $A_iA_jA_m$ where $k$ and $m$ are on opposite sides of $A_iA_j$. As the polygon has even number of vertices, parity of number of triangles on each side is same, so no change in parity of number of triangles that have that point inside them. As initially it was even, it will always remain even.


Deploying an Angular cli application on to Azure Service fabric

Question: I have created a new Angular 4 application using Angular-cli and tried to deploy it on to Azure Service Fabric. I have used Visual Studio code to develop the application. I am able to create the bundles using ng build  but couldnt able to deploy  it on to Azure Service Fabric
Comment: What happens when you try to deploy? Error message? How do you deploy?
Comment: My question is how to deploy. I didn't find a tutorial to do it .
Comment: do you manage to deploy an angular cli app to service fabric?
Answer: Ng build got nothing to do with Service Fabric stuff.
If you want to host AngularJS app on Service Fabric then I guess all you need is a .Net Core project to serve static files and include all your AngularJS files in that project.
Comment: When I build my angular app in vs code, I get one index.html and 5 js files, which I have to deploy to service fabric


Show $T:\mathbb{R}^n\to \mathbb{R}^m$ injective, surjective then $n\leq m$,$n\geq m$ respectively

Question: I want to show that if there is an injective linear transformation from $\mathbb{R}^n$ to $\mathbb{R}^m$ then $n \leq m$. I approached it as follows. $T$ is injective implies that the standard matrix has nullity $0$ and so rank $n$. Hence, the standard matrix has $n$ linearly independent columns, which means that $T(e_1),T(e_2),\dots,T(e_n)$ are linearly independent vectors in $\mathbb{R}^m$. Since we can have at most $m$ linearly independent vectors in $\mathbb{R}^m$, $n \leq m$. Similarly I argue that if $T$ is surjective then the standard matrix $[T]$ has rank $m$ and so it has $m$ linearly independent columns. But the total number of columns is $n$, so $n\geq m$.
Comment: Looks good to me.
Answer: Your proof is perfectly fine. It can be proven for any $T: V \to U $ linear spaces of finite dimension,  and thus if $T $ is bijective, the dimensions of $V $ and $U$ are the same.
Or, there is only a bijective linear transformation between two linear spaces if they have the same dimension. In that case, you can pick two bases and say that the image of one of the basis is the other and your $T$ is defined.


Em Java teria como uma variável receber uma função assim como no JavaScript?

Question: Exemplo:
var x = function (a, b) {
           return a * b
        };

Teria como? Ou é uma característica do JavaScript?
Answer: Em Java 8 pode usar a sintaxe de lambda. Antes disso só criando functors, que não é exatamente a mesma coisa, mas dá resultado parecido.
BiFunction<Integer, Integer, Integer> x = (a, b) -> a * b;

Coloquei no GitHub para referência futura.
Claro que difere na questão de que tudo é tipado, mas é simples assim.
Tem outras formas de declarar conforme a necessidade e número de argumentos. Sem um contexto maior não sei se esta é a melhor forma para o caso. Veja mais opções.
Não sei te dizer se em Java 15 ou 16 pode usar var no lugar do tipo (acho que não, precisa pesquisar).
Comment: Esta é a forma para 2 argumentos. Tem para um e deve ter para mais, mas em Java eu não conheço os mecanismo exatos, precisaria pesquisar. Não é eficiência, pelo contrário, isto é menos eficiente porque tem [indireção](https://pt.stackoverflow.com/q/181032/101) extra. Isto é usado para parametrizar ações em códigos que você sabe quase tudo o que fazer, mas tem um ponto que o consumidor é que deve definir o que executar. É igual ao JS.
Comment: Para funções com 2 argumentos somente.
Comment: Legal! Isso no java poderia ser eficiente em qual contexto Maniero ?
Comment: Só um exemplo, por favor.
Comment: Muito Obrigado Maniero!!!
Answer: Não... o mais próximo seria:
metodoTeste(new Runnable() {
    @Override
    public void run() {
        System.out.println("Hello");
    }
});

ou
metodoTeste(() -> System.out.println("Hello"));


How to rewrite url path in Nestjs?

Question: I want to rewrite url like '/api/example' to '/example'
I've tried code below, but it does not work
import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
export class RewriteApiEndpointMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    req.originalUrl = req.originalUrl.replace(/^\/api/, '');
    next();
  }
}

Answer: I have found the solution
Step 1:
consumer
  .apply(RewriteApiEndpointMiddleware)
  .forRoutes('/') // <--- not the .forRoutes('*')

Step 2:
import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
export class RewriteApiEndpointMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    req.url = req.url.replace(/^\/api/, ''); // <--- not the .originalUrl
    next();
  }
}

Now it works as expected
Comment: Not sure how you got this to work, req.url is read only.

How to rewrite url path in Nestjs?


Calculating Expected Range of Scores

Question: I have a clinical test that 35 healthy people took twice. Each test consisted of 6 trials. We measure a subject's perception of vertical. I am trying to calculate the test/retest reliability for this clinical test, but due to the nature of the test the average is not a useful measure. The test uses positive and negative numbers, they have biological importance. 0 is "normal", so a person scoring -6,+6 will look as normal as someone scoring -1,+1. An absolute average removes data as side matters-- someone answering -6,+6 will then look the same as someone scoring +6,+6 (much more consistent). Someone answering +6 multiple times, while way off traditional vertical, is fundamentally different from someone answering +6 then -6 (their perception is not constant). I would like to calculate, regardless of the average score, the expected variation in response in a healthy individual, so I can say someone who scores 0+/-6 is abnormal compared to someone who scores 0+/-1, for example. Does anyone have any idea how to go about this?
I have each trial for each subject and overall averages / standard deviations for all 6 trials for both tests for each subject.
Answer: It seems like you want to test a hypothesis on the distance between responses $d$ being abnormal vs. normal. The idea being if the distance is larger, it is more likely they are abnormal and vice versa.
Without any prior information on the distribution of abnormal people though this isn't completely solvable without making assumptions. However we can just take the uninformative prior for this which would be equal probabilities for each number, so we want to form a hypothesis on the difference $d$ where $d$ is the difference between two discrete uniform $ U(0,12)$. This distribution is some triangular distribution, so if you want a p-value of 0.05 just find the cut-off values for $95$% of this distribution and whenever your subject is outside this bound you cannot the reject the null that they are abnormal (akin to just scoring a number at random).

Calculating Expected Range of Scores


Run Javascript in certain file using Java

Question: I am trying to trigger an event in JavaScript using a Java class.
How can I send javascript code (either direct input or from a file) in a Java class to a specified destination file which is already opened in the browser (Firefox)?
Currently I'm using the ScriptEngineManager to run my JavaScript code, but the code is executed in my Java environment and I don't know how to trigger an event in this way (as I cannot use e.g. window.postMessage("hi", "*");)
Any suggestions how to solve this? Work-arounds are also appreciated (preferably without extensions, plugins, ...).
Best regards.
Answer: When executing from java you have no access to window events - because there is no browser.
I don't really understand the use case here but you could load the destination file into an iframe and then do a meta refresh - once you update the files contents then the updated results will be displayed on the next refesh.
In any case you can only return results from the inputted javascript functions back to java - not call events.
You could pass a javascript function (a call that simulates the event)  back to the browser and then execute it.
How you would pass this back to the client depends on the situation :

It could be on the response of the request to upload the javascript
You could use the meta-refresh mechanism
You could look into an ajax style way with client polling (if you didn't want to refresh manually each time).

EDIT
The server has no link to the browser between requests. To asynchronously receive a server event in a browser you could have a look at:

WebSockets
Comet

So the browser would receive notification when the task is complete and then it would be able to react - for instance prompt for the tab to close.
Comment: Use case: I have to close Firefox when the Java class is executed. I thought I could trigger an event that would close the current window?

As the web page has to be displayed continually meta-refresh seems not to be a solution.
Comment: Thanks! Do you have any recommendations or are there native (plugin-free) solutions for this?


The Search API module shows a two-words taxonomy term as two separated words, in its widget

Question: I am using taxonomy terms to classify my content, and the Search API and Facets modules for searching.
I have some nodes that are tagged with "Asian Cuisine" term; after indexing the content, "Asian Cuisine" is handled as two separated words.

Is there a way to avoid it happens?
Comment: Did you apply the "tokenizer" filter to the field?
Comment: Can you post a screenshot of your search index field settings? I've honestly never seen that happen, and I used Search API quite a bit.
Comment: thanks @KyleTaylored . here are the links .

https://www.dropbox.com/s/cbq0egjbsk5gaaf/pic1.jpg
https://www.dropbox.com/s/xxm3lfhvyfyyh2f/pic2.jpg
Comment: @arrubiu, thanks for the tip. I turned it on at my taxonomy field and it worked. but also i changed the setting of my Taxonomy field to "String" instead of "FullText". So some of it worked.
Answer: Based on your screenshots, consider using the "Taxonomy Term" type for the field indexes. This should remedy your issue.
By using Full Text, you're breaking up the taxonomy term names into searchable words. Use either the default taxonomy term value, or try using the "All Parent Terms" field.
Comment: For both the facets and fulltext search work, you need to index the fields separately. The Facets will work properly when using the Taxonomy Term type, and then you can index the Term Names using the Fulltext type that should then should show up when using the search box.
Comment: @KyleTaylored, I'm having the same issue but I'm using the address field. So I can not change it to a Taxonomy Term. What should I do in this case ?
Comment: thanks @KyleTaylored. but does this has to do any thing with the below screen .

https://www.dropbox.com/s/87npj9k7y558ndy/test_recep%20%20%20Site%20Install_.png

Can't i just use one search box to search any thing ?
Comment: What can be done when the facet field is a text field ?


Nomenclature of diminished chords within diatonic harmony

Question: I am currently writing a guide to use of diminished chords as linking chords in a diatonic progression in the key of G major.
I have used the progression "Gmaj7 - G#dim - Am7 - A#dim - Bm7".
It occurs to me that one could equally write the above progression with the enharmonic equivalents "Gmaj7 - Abdim - Am7 - Bbdim - Bm7".
Could somebody please tell me which of these is more correct and why?
EDIT: Thanks for your responses so far. I also go on to use an example of descending chromatic links using dominant chords, eg "Bm7 - Bb7 - Am7 - Ab7 - Gmaj7". Would you agree that is better to name them as such when used in a descending example?
Thanks!
Comment: Funnily enough I was going to ask the same question, having come across the same dim chord named two ways in different parts of the same piece. And also, dim chords named, e.g. C#dim, but written in the dots with a Db. Let's hope someone can explain, or maybe it's just poor writing...  You could even have used Bo, Do or Fo in place of G#o.
Comment: Corollary question - is it preferable/necessary to use the quoted note as the lowest (root) when playing? And, how about keeping the names to the actual diatonic names from the current key?
Answer: I always recommend naming/labeling chords to show how they function.
In this case, the G♯ diminished chord is best understood as tonicizing the next A chord. Since the G♯ chord is functioning as vii°7/A, I think it's best to spell this chord as G♯ (the seventh scale degree of A) to make that clear; spelling it as A♭, B, D, or F makes this connection much less obvious.
Similarly, the A♯ diminished chord is really functioning as vii°7/B, so it's best to spell it as A♯ instead of B♭ or anything else.
And there's an added bonus here: spelling the chords this way makes it clear the ascending chromatic line of the roots G-G♯-A-A♯-B.
Comment: Yes, I'm inclined to agree- I suppose I'd spell it as Bb if I were using it in a descending chord progression of some sort.
Comment: Definitely agree with Richard here. As an aside, these chords are also known as "secondary leading-tone chords". The only examples where accidentals might take precedence over showing function might be: there is no harmonic function present (not applicable to your example), player readability (avoiding awkward intervals), or perhaps to indicate longer-range voice-leading, showing linear motion / direction of either voices within a texture and /or voices in other instruments.
Answer: I'd say the version with G#dim and A#dim is more correct, as each diminished chord is easily interpreted as a secondary dominant (the first of the Am7 that follows it, the second of the Bm7 that follows it). G# is the leading tone of A and A# is the leading tone of B, so they fit.


Predicting Ingredients amount for getting color

Question: I have a dataset of different colors and the ingredients (with amount in grams) that was used to make that color
My intention is to build an ML model that would take the color values (eg. RGB/LAB) as input and gives me the amount of each ingredients that would be needed to mix and get that color. Some of the ingredients can have 0 values indicating that they were not used to make that color. My input (L, A and B) are the only features I have for now and there are about 2,000 observations. Example dataset is below:

I am a beginner and finding my way into machine learning. Please suggest what algorithm would best fit my purpose.
Comment: How many observations do you have? You're showing 4 rows, so do you only have 4 observations?
Comment: I have about 2,000 observations
Comment: Edit that into your question.
Answer: A simple way to begin is treat each of the dependent variables (DVs, or ingredients, in this case) as a separate problem. So then you have six modeling problems (or five, if the sum of the ingredients is fixed) with three predictors apiece. For each DV, compute the SD, compare it to the cross-validated root mean square error (RMSE) of ordinary linear regression with the three predictors, and if that RMSE isn't good enough, look into fancier models like decision trees.


Birthday problem: why not: combinations without/with replacement??

Question: My first intuition on the birthday problem was:

The number of ways $k$ people have different birthdays is the combinations $\binom{365}{k}$
The number of ways $k$ people can have birthdays is the combinations with replacement.

So the probability that all $k$ people have birthdays on different days is
$$ P = \frac{\binom{365}{k}}{\binom{365+k-1}{k}}$$
What is wrong with this logic?
Answer: You're considering as the sample space the set of all combinations with replacement of $k$ picks from the $365$ days. Why is your calculation wrong? Because
$$P(A)=\frac{\#A}{\#\Omega}$$
is only valid when the sample space $\#\Omega$ is equiprobable, and this one is not.
This is because you're considering combinations instead of variations. For instance, take $k=2$: the case in which everybody (that is, both people) have it's birthday on January 1st only happens with probability $$\left(\frac1{365}\right)\cdot \left(\frac1{365}\right),$$
while the case when one person does so and the other on January 2nd has probability
$$\left(\frac1{365}\right)\cdot \left(\frac1{365}\right)+\left(\frac1{365}\right)\cdot \left(\frac1{365}\right),$$
since it can be the case that one person (say person A) has it's birthday on the 1st and person B on the 2nd, or person A on the 2nd and person B on the first. Any of these correspond to the result ''one person has birthday on 1/1 and the other on the 2/1'.
To have an equiprobable space you should take as different situations that one in which 'A' has birthday on 1/1 and 'B'on 2/1 and that one in which 'A' has birthday on 2/1 and 'B'on 1/1.
Answer: The calculation $\binom{365}{k}$ only chooses $k$ days; it does not assign particular days to the people. So your first statement is incorrect.  I am not sure where your second formula comes from, but you're probably making a similar error.


How can I find m using the discriminant?

Question: There is a curve $$y=2x^2-4x+8$$ and a line $$y=mx$$.
I have to find the values of m for which the line is tangent to the curve.
I made them equal, then put everything to one side:
$$2x^2-4x+8-mx=0$$
$$2x^2-(4x-mx)+8=0$$
Now, a tangent only touches the curve at one point, so I used the $$b^2-4ac=0$$ discriminant equation, but then here is where I'm stuck. I got:
$$-(4x-mx)^2-4*2*8=0 \tag1 $$
$$-(4x-mx)^2-64=0$$
But then I will get 2 variables again, and $x^2$ and $m^2$ so I don't know how to solve it from here.
Comment: $b=4-m$. The $x$ simply should't be there. Besides that, your approach is correct and I am sure you can complete the exercise
Comment: Ahh yeah, thank you....
Answer: $x$ need be there in 1) once again. Else ok as it leads to a quadratic in $m$.
Comment: There are other mistakes too.
Comment: Indeed so. Assumed that when he reworks afresh he would be more attentive/ careful overall.
Answer: So $2x^2−4x+8−mx=0$
Then you need to organize it as
$$2x^2−(4+m)x+8=0$$
Notice that $b = -(4+m)$, but not $-(4x + mx)$ as you listed in your question.
$$b^2 - 4ac=[-(4+m)]^2 -4 \times 2 \times 8 = 0$$
So there is only $m$, no $x$. And you get the point $x$ once you solve $m$ such that the quadratic function about $x$ only have one solution.
Answer: You have made a couple mistakes:

Mistake 1:
$$2x^2-4x+8-mx=0 \not\Rightarrow 2x^2-(4x-mx)+8=0$$
However, it is correct that:
$$2x^2-4x+8-mx=0 \implies 2x^2-(4x\color{red}{+}mx)+8=0 \tag{1}$$

Mistake 2:
If the form of the quadratic is $ax^2+bx+c=0$ where $a,b$ and $c$ are real constants, then the discriminant $\Delta$ is equal to:
$$\Delta=b^2-4ac$$
Therefore, your $b$ should not contain any $x$ terms!
To avoid this issue, factorize equation $(1)$ like this:
$$2x^2-(4+m)x+8=0$$
Therefore, we can clearly see that $b=-(4+m)$ and thus $b^2=(-1)^2\cdot (4+m)^2=(4+m)^2$.

The correction:
Putting this all together, you should be solving:
$$(4+m)^2-4\cdot 2\cdot 8=0$$
Solving for $m$ gives the two values of $m$ for which the line is tangent to the curve.

To intuitively verify your answer, you can move the slider for $m$ on this Desmos Graph.
Comment: Thank you, now it's clear :)


Como formatar corretamente um valor monetário?

Question: Possuo um valor que vem do formulário dessa maneira:
R$ 1.500,95

Preciso que ele fique assim:
R$ 1500,95

Como fazer ele ficar transformado que nem na 2ª maneira? Preciso que ele fique totalmente igual à maneira a qual foi citada.
Answer: Faça a remoção do ponto e do R$.
<?php

$moeda = "R$ 1.500,95";

// Com str_replace (Remove a string 'R$ ' e '.'
$valor = str_replace( array('R$ ', '.'),  '', $moeda);
echo $valor; //1550,95

// Com preg_replace (Remove tudo que for diferente de dígito e vírgula)
$valor = preg_replace( '/([^\d,])/',  '', $moeda);
$valor = preg_replace('/[,]+/', ',', $valor); // Fix para caso seja passado mais de 1 ","
echo $valor; //1550,95

?>

Comment: Atualizei o código para fazer de duas formas, com preg_replace ou str_replace e também coloquei um comentário para ter uma compreensão melhor.
Comment: Utilizar o `\d,` você aceita vários `,`, ou seja o `1550,,,,,95` seria retornado exatamente como está, não seria removido os `,` adicionais.
Comment: @Inkeliz, certíssimo, adicionei a linha $valor = preg_replace('/[,]+/', ',', $valor) para comportar este caso, assim o valor ficará da forma correta.
Answer: Uma outra solução seria remover somente manter os números inteiros e divido-los por 100.
$moeda = 'R$ 1.550,52';

$valor = preg_replace('/[^0-9]/', '', $moeda);
$valor = bcdiv($valor, 100, 2);
$valor = strtr($valor, '.', ',');

echo $valor;

Resultado:

1550,52

Dessa forma, isso se tornaria:
string : 0e100 => 1,00
double : 0e100 => 0,00
string : 0x98 => 0,98
integer : 0x98 => 1,52
string : R$ 100.00 => 100,00
integer : 10000 => 100,00
double : 100.00 => 1,00
integer : 12345 => 123,45
string : 123.45 => 123,45
double : 123.45 => 123,45
string : 1a2b3c4d5e => 123,45
string : 123,45 => 123,45
string : R$ 123,45 => 123,45
string : 1 => 0,01
integer : 1 => 0,01

double : 9.0E+99 => 8999999999999999948859130765266355329578537025198862586562510896759102769772101980841694466750283776,00
integer : 9223372036854775807 => 92233720368547758,07

Teste isto.
Esta função, do jeito que está, tem "problemas" com float, não recomendo que utilize para float/double. O float de 100.00 será 1,00 e 100.01 vai se tornar 100,01, ou seja o 100.00 não vai para 100,00, o que pode não ser esperado.
Obviamente é preciso que representação contenha os centavos, caso seja apenas R$ 1.550 irá passar para 15,50. Porém, informar 1.550,00 não terá problema, assim como 155000 ou até mesmo 1a550b00.
Caso encontre algum outro problema comentem, porque realmente não consigo imaginar algum, fora os mencionados.
Answer: Você pode usar a função preg_replace ou str_replace, veja abaixo com preg_replace:
echo preg_replace('/^[0-9,]/', '', $valor);
// Saída: 1500,95

Comment: A saída desse comando sobre a string "1.500,95" resulta em ".500,95". Você está removendo tudo que começa com digitos de 0 a 9 ou vírgulo.


Idea behind the factorization of the matrix $\operatorname{diag}(a,a^{-1})$ in algebraic K-Theory

Question: If $a \in S$ is some invertible element in a ring $S$, then a computation shows
$$\pmatrix{a & 0 \\ 0 & a^{-1}} = \pmatrix{1 & a \\ 0 & 1} \pmatrix{1 & 0 \\ -a^{-1} & 1} \pmatrix{1 & a \\ 0 & 1} \pmatrix{0 & -1 \\ 1 & 0}.$$
If $R \to S$ is a surjective homomorphism, we see that this invertible matrix over $S$ may be lifted to some invertible matrix over $R$. This observation is important in algebraic K-Theory; for example it is used in the exactness of the relative $K_0$-sequence (see Rosenberg's book, 1.5.4 -  1.5.5).
Questions. What is the idea behind this factorization? Of course it makes no problem to verify this identity, but how can you come up with such a nontrivial factorization? Does it have a geometric interpretation? Who was the first one to find and use this identity?
PS: Isn't it sad that only few textbooks and papers offer explanations of the important insights, rather than only proof verifications?
Answer: I have no answer about the history or geometric interpretation, but this is how I would come up with a similar identity in a more or less algorithmic fashion. The goal is to express
$$\left(\begin{array}{cc}a&0\\0&a^{-1}\end{array}\right)$$
as a product of elementary matrices. To do this it suffices to "reduce it to $I$ elementary row and column operations". I can do that as follows:

Add $a$ times column 2 to column 1, getting
$$\left(\begin{array}{cc}a&0\\1&a^{-1}\end{array}\right).$$
Add $1-a^{-1}$ times column 1 to column 2, getting
$$\left(\begin{array}{cc}a&a-1\\1&1\end{array}\right).$$
Subtract column 2 from column 1, getting
$$\left(\begin{array}{cc}1&a-1\\0&1\end{array}\right).$$
Subtract $a-1$ times column 1 from column 2, getting $I$.

Working backwords, I find the factorisation
$$\left(\begin{array}{cc}a&0\\0&a^{-1}\end{array}\right) = \left(\begin{array}{cc}1&a-1\\0&1\end{array}\right)\left(\begin{array}{cc}1&0\\1&1\end{array}\right)\left(\begin{array}{cc}1&a^{-1}-1\\0&1\end{array}\right)\left(\begin{array}{cc}1&0\\-a&1\end{array}\right).$$
Unless I completely misunderstood the motivation, I think this factorisation is just as useful.
Comment: All I'm doing is messing around in the bottom row to create a 1, and then use that 1 to destroy everything else in the bottom row, and then basically I'm done.


How to overcome from overlapping of html elements?

Question:
I am trying practicing to make like above figure. Anyone can help me on this, how to overcome from this type of overlapping , I think that z-index will solve this type of problem but I don't understand how?
But till now I am able to make this figure…

Here's my code:

 * {
    margin: 0;
    background:#222730;
  }
  .a{
    max-width:100%;
    height:150px;
    margin-top:4.69em;
    background:#4CAAB3;
  }
  .b{
    width:250px;
    height:250px;
    margin-top:-12.5em;
    transform: rotate(45deg);
    margin-left:auto;
    margin-right:auto;

    background:#222730;
  }
  .c{
    width:150px;
    height:150px;
    margin-top:-12.5em;
    transform: rotate(45deg);
    margin-left:auto;
    margin-right:auto;
    background:#4CAAB3;
  }
   .d{
    background:white;
    margin-left:auto;
    margin-right:auto;
    width:50px;
    height:50px;
    z-index:;
    margin-top:-8em;

  }

Comment: For a `z-index` to work, the position must not be `static`.
Answer: If the dot is div.d, than just add position: relative; to show it above (and other styles like background, border-radius, etc.).

 * {
    margin: 0;
    background:#222730;
  }
  .a{
    max-width:100%;
    height:150px;
    margin-top:4.69em;
    background:#4CAAB3;
  }
  .b{
    width:250px;
    height:250px;
    margin-top:-12.5em;
    transform: rotate(45deg);
    margin-left:auto;
    margin-right:auto;

    background:#222730;
  }
  .c{
    width:150px;
    height:150px;
    margin-top:-12.5em;
    transform: rotate(45deg);
    margin-left:auto;
    margin-right:auto;
    background:#4CAAB3;
  }
   .d{
    background:white;
    margin-left:auto;
    margin-right:auto;
    width:50px;
    height:50px;
    z-index:;
    margin-top:-8em;
    position: relative;

  }

Z-index works with only position != static (relative, absolute, etc.). Here position: relative and default z-index: auto is fine because .d is the last element in HTML markup (.a-c elements has z-index: auto too, but they are higher in your markup).
Comment: the default value of z-index is not 1 (and not 0). it's `auto`
Comment: @TemaniAfif: yes, my mistake... It changes nothing on the rest of my post, in OP CSS was no z-indexes specified, all elements have default value (and it doesn't matter if auto or 1). But thanks.


Celery worker doesn't launch from Python

Question: We have Python 3.6.1 set up with Django, Celery, and Rabbitmq on Ubuntu 14.04. Right now, I'm using the Django debug server (for dev and Apache isn't working). My current problem is that the celery workers get launched from Python and immediately die -- processes show as defunct. If I use the same command in a terminal window, the worker gets created and picks up the task if there is one waiting in the queue.
Here's the command:
celery worker --app=myapp --loglevel=info --concurrency=1 --maxtasksperchild=20 -n celery_1 -Q celery

The same functionality occurs for whichever queues are being set up.
In the terminal, we see the output myapp.settings - INFO - Loading... followed by output that describes the queue and lists the tasks. When running from Python, the last thing we see is the Loading...
In the code, we do have a check to be sure we are not running the celery command as root.
These are the Celery settings from our settings.py file:
CELERY_ACCEPT_CONTENT = ['json','pickle']
CELERY_TASK_SERIALIZER = 'pickle'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_IMPORTS = ('api.tasks',)
CELERYD_PREFETCH_MULTIPLIER = 1
CELERYD_CONCURRENCY = 1
BROKER_POOL_LIMIT = 120  # Note: I tried this set to None but it didn't seem to make any difference
CELERYD_LOG_COLOR = False
CELERY_LOG_FORMAT = '%)asctime)s - $(processName)s - %(levelname)s - %(message)s'
CELERYD_HIJACK_ROOT_LOGGER = False
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(psconf.BASE_DIR, 'myapp_static/')
BROKER_URL = psconf.MQ_URI
CELERY_RESULT_BACKEND = 'rpc'
CELERY_RESULT_PERSISTENT = True
CELERY_ROUTES = {}
for entry in os.scandir(psconf.PLUGIN_PATH):
    if not entry.is_dir() or entry.name == '__pycache__':
        continue
    plugin_dir = entry.name
    settings_file = f'{plugin_dir}.settings'
    try:
        plugin_tasks = importlib.import_module(settings_file)
        queue_name = plugin_tasks.QUEUENAME
    except ModuleNotFoundError as e:
        logging.warning(e)
    except AttributeError:
        logging.debug(f'The plugin {plugin_dir} will use the general worker queue.')
    else:
        CELERY_ROUTES[f'{plugin_dir}.tasks.run'] = {'queue': queue_name}
        logging.debug(f'The plugin {plugin_dir} will use the {queue_name} queue.')

Here is the part that kicks off the worker:
    class CeleryWorker(BackgroundProcess):
      def __init__(self, n, q):
        self.name = n
        self.worker_queue = q
        cmd = f'celery worker --app=myapp --loglevel=info --concurrency=1 --maxtasksperchild=20 -n {self.name" -Q {self.worker_queue}'
        super().__init__(cmd, cwd=str(psconf.BASE_DIR))

    class BackgroundProcess(subprocess.Popen):
      def __init__(self, args, **kwargs):
        super().__init__(args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, **kwargs)

Any suggestions as to how to get this working from Python are appreciated. I'm new to Rabbitmq/Celery.
Comment: You mentioned `the celery workers get launched from Python and immediately die`... But I don't see any Python code that is actually launching the celery worker. Could you please include that or describe this in more detail?
Comment: @sytech - I've edited the post to include code snippets that show how the worker is being launched.
Comment: And where and how is this "CeleryWorker" used ? But anyway: there's no reason your django code should launch celery workers, and given how both the builtin dev server AND wsgi connectors tend to launch and stop Django subprocesses there are pretty good reasons you DONT want your django to launch celery workers.
Comment: We have a Manager GUI that kicks off the workers on startup. We take the stdout and stderr and display them in the GUI. This all works like a charm under Windows 10. I'm trying to get it all to behave in Linux and that is where the pain started.
Answer: Just in case someone else needs this...It turns out that the problem was that the shell script which kicks off this whole app is now being launched with sudo and, even though I thought I was checking so we wouldn't launch the celery worker with sudo, I'd missed something and we were trying to launch as root. That is a no-no. I'm now explicitly using 'sudo -u ' and the workers are starting properly.


How to swallow crash report when using Win32::CreateProcess

Question: In a unittest sequence I'm testing if a data corruption error is caught or not (deliberately feeding corrupt data).
In order to treat a program crash (e.g. corrupt data + poor buffer management) as a regular fail-condition I run the program in a child process with CreateProcess. My problem is that if it crashes I get a crash report dialog from Windows and I have to close it for the test-sequence to carry on.
Is there any way of using CreateProcess so that I can swallow the crash report from Windows?
Answer: You cannot do this with CreateProcess(), the child program has to take care of it itself.  Two basic ways:

use the <code>__try/__except</code> keywords to catch and handle the SEH exception
register a callback with SetUnhandledExceptionFilter()

Try to do as little as possible in either case, you have no idea what state the program is in when it suffered the heart attack.  Best thing to do is to SetEvent() a named event and have your main process terminate the process.
Comment: SetUnhandledExceptionFilter is the way we do it. That way it won't even get to the "windows error reporting" stage and you can just make it do what you like.
Answer: Probably the best plan is to turn off Windows Error Reporting (Microsoft Error Reporting on XP and earlier) on your test machine, at least for the duration of the test. The exact steps depend on your Windows version, but it's under Control Panel.
Comment: Thanks for the tip. However, as I failed to specify in the question, the solution must be suitable for environments whith limited or no administration interface. E.g. automated testservers. This is actually why the test sequence needs to proceed unattended.


Erro ao tentar instalar o Router Flux

Question: Me deparei com um erro bem chato ao tentar instalar o Router Flux na pasta do meu app6 alguma sugestão:
Observação: já instalei duas bibliotecas:

npm install --save eslint-config-rallycoding npm install --save
react-native-router-flux

codigo: index.android.js
import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import { Router, Scene } from 'react-native-router-flux';

import Principal from './src/components/Principal';
import SobreJogo from './src/components/SobreJogo';
import OutrosJogos from './src/components/OutrosJogos';

export default class app extends Component {
  render() {
    return (
      <Router sceneStyle={{ paddingTop: 50 }}>
        <Scene key='principal' component={Principal} initil title="Cara ou coroa" />
        <Scene key='sobrejogo' component={SobreJogo} title="Sobre o Jogo" />
        <Scene key='outrosjogos' component={OutrosJogos} title="Outros Jogos" />
      </Router>
    );
  }
}

AppRegistry.registerComponent('app', () => app);

PRINCIPAL
import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Image,
  TouchableHighlight
} from 'react-native';

import { Actions } from 'react-native-router-flux';

const logo = require('../imgs/logo.png');
const btnJogar = require('../imgs/botao_jogar.png');
const btnSobreJogo = require('../imgs/sobre_jogo.png');
const btnOutrosJogos = require('../imgs/outros_jogos.png');

export default class Principal extends Component {
  render() {
    return (
      <View style={styles.cenaPrincipal}>

        <View style={styles.apresentacaoJogo}>
          <Image source={logo} />
          <Image source={btnJogar} />
        </View>

        <View style={styles.rodape}>
          <TouchableHighlight
            onPress={() => { Actions.sobrejogo(); }}
          >
            <Image source={btnSobreJogo} />
          </TouchableHighlight>

          <TouchableHighlight
            onPress={() => { Actions.outrosjogos(); }}
          >
            <Image source={btnOutrosJogos} />
          </TouchableHighlight>
        </View>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  cenaPrincipal: {
    flex: 1,
    backgroundColor: '#61BD8C'
  },
  apresentacaoJogo: {
    flex: 10,
    justifyContent: 'center',
    alignItems: 'center'
  },
  rodape: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between'
  }
});

CODIGO SOBRE JOGO
import React, { Component } from 'react';
import { Text } from 'react-native';

export default class SobreJogo extends Component {
    render() {
        return (
            <Text style={{ flex: 1, backgroundColor: '#61BD8C' }}>
                Aqui podem ser apresentadas informações sobre o jogo
            </Text>
        );
    }
}

CODIGO OutrosJogos
import React, { Component } from 'react';
import { Text } from 'react-native';

export default class OutrosJogos extends Component {
    render() {
        return (
            <Text style={{ flex: 1, backgroundColor: '#61BD8C' }}>
                Aqui podem ser apresentadas informações sobre outros jogos do desenvolvedor
            </Text>
        );
    }
}

BAIXAR CODIGO NO GITHUB
Comment: Para mim o erro não parece ter haver com o roteador. Já tentou eliminar partes do código uma por uma até encontrar a parte que dá problema? Também parece ter um erro de JSON. Você está usando isso em algum lugar? E só uma dica, você deve usar `--save-dev` para o `eslint-config-rallycoding`, porquê o mesmo não é necessário para produção, somente desenvolvimento ("DEVelopment").
Answer: Na verdade não é um erro da lib.
A nova versão do router-flux modificou um pouco a estrutura para montar o sistema de rotas dele.
A boa notícia é que é bem tranquilo resolver esse problema.
Basta encapsular os componentes Scene dentro de uma outra Scene sem o atributo component, vide exemplo abaixo:
<Router>
     <Scene key='app'>
          <Scene key='principal' component={Principal} title='Cara ou Coroa?' titleStyle={styles.nav} />
          <Scene key='sobrejogo' component={SobreJogo} title='Sobre o Jogo' titleStyle={styles.nav} />
         <Scene key='outrosjogos' component={OutrosJogos} title='Outros Jogos' titleStyle={styles.nav} />
         <Scene key='resultado' component={Resultado} title='Resultado' titleStyle={styles.nav} />
    </Scene>
</Router>

Espero ter ajudado.
Att,
Júlio Falbo
Answer: Esse é um problema com a última versão do Router Flux. Desinstale e use a versão firstname.lastname@example.com  até eles consertarem.

Erro ao tentar instalar o Router Flux


How to simplify power series?

Question: My textbook was simplifying a power series. I was able to follow their work until the last line.
Where did the "$-2$" come from?
Why were they able to cancel out one of the $(n+r)'s$, $C_n$'s, and $x^{n+r-1}$'s?
$\underline{\textrm{Image from textbook}}$
Answer: Hint: We have
$$3(n+r)\cdot (n+r-1)+(n+r)$$
Now we factor out $(n+r)$:
$$(n+r)\cdot (3\cdot (n+r-1)+1)=(n+r)\cdot (3n+3r\underbrace{-3+1}_{-2})=(n+r)\cdot (3n+3r-2)$$
Answer: They didn't show some simplification. In the line above the last line, look at the first two terms. You can factor out the entire second term and get:
$$3(n+r-1) + 1$$

How to simplify power series?


Is NoSQL worth in my case

Question: I have to design a database in order to make reporting. Data is varied (from accounts to logs or social media posts). The volume is about 1 million lines per day.
In my mind :
SQL pros :

The main goal for user is to make this kind of request : Number of user having a skype account and more than 4Go of storage. It involves a lot of joins and structural database is more coherent in this case.
SQL database is enough powerfull for this volume
To store identity linked to account, I think SQL structure is more suitable.

NoSQL pros :

JSON format is an asset because data source are provided by multivalued document and some fields can be removed/added easily.
The database is "open", so new service can be added to the database. It involves more volume, not known data.(nosql scalability)
Some tools (like kibana / elastic search) seems to be compliant with nosql technologies.

It is difficult to me to decide, on one hand it seems to be difficult to put all identity (+ account + orders + other informations ) in one document, on the other once this problem is solved it seems powerful and interesting (Json, scalability...).
I'll take any advice ;)
Comment: Answers to such a question will tend to reflect personal preference.  Even if there would be a clear "that one", such a decision could not be made without *a lot* more details (e.g.: how exactly does "Number of user having a skype account and more than 4Go of storage" will be done on a dataset containing data "from accounts to logs or social media posts"). Additionally, "NoSQL" is very unspecific - there's a wide range of NoSQL products, some of which can be used like a normal relational database, including integrity, joins and even acid, while MySQL can use json too (at least to some degree).
Comment: Elasticsearch can load data from JDBC data sources too. That's not a reason to use NoSQL (whatever that means).
Answer: This is a big topic
However my 2 cents here to consider the following:

Database Integrity: If you have to guarantee db integrity at all times, then consider SQL
Resources: If you're entending to make use of cloud wide distrubuted computing and storage, then consider NoSQL

Afterall, it does not have to be one or the other. You can also consider an architecture which has a mix of both. Order processing/accounting/e-commerce tend to fit to SQL. While blogs and social media posts fit NoSQL
Your specific "main goal" can be acheived using SQL and NoSQL with proper choice of tools and design
NoSQL has many flavours too, and not as standardized as SQL. If you're considering NoSQL, you have another deep research to do - which best fits your business scenarios
Further, consider your organization's capabilities, and stratigic direction!

Is NoSQL worth in my case


Use existing crystal Report with a new dataset

Question: I am trying to bind my crystal report that is already created meaning  I have the .rpt file.  Now I am adding this to my application using Add- reports - existing item.  This report is created based on a  oracle table view.  in my program I have created a dynamic dataset that has all the fields required for this report.  now I need to find a way to use this existing .rpt file and parse my data from dataset to create a report in pdf format.
 I know how to export the report into pdf.  But I don't know how to use this .rpt file and parse my dataset data through it.
Here is the code I have so far
using System;
using  System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Oracle.DataAccess.Client;
using System.Data;
using CrystalDecisions.CrystalReports.Engine;

namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string connetionString = null;
        OracleConnection connection;
        OracleDataAdapter OracleAdapter;
        DataSet ds = new DataSet();
        string firstSql = null;
       // string secondSql = null;

        connetionString = "blah blah
        firstSql = "select * from STATEMENT_DomESTIC";
       // secondSql = "Select * from DOM_DETAILS";
        connection = new OracleConnection(connetionString);
        try
        {
            connection.Open();
            OracleAdapter = new OracleDataAdapter(firstSql, connection);
            OracleAdapter.Fill(ds, "domestic_header");
            OracleAdapter.SelectCommand.CommandText = secondSql;
            OracleAdapter.Fill(ds, "domestic_detail");
            OracleAdapter.Dispose();
            connection.Close();

           // GridView1.DataSource = ds;
           // GridView1.DataBind();

        }

        catch (Exception ex)
        {

        }
    }
}
}

I Did research on this but, was unable to find a good example where this can be done.
Answer: You need to use the ReportDocument object supplied by Crystal. For example...
ReportDocument reportDoc = new ReportDocument();
reportDoc.Load("YourReportName");  //or path to your report
reportDoc.SetDataSource(ds);

Does this do what you are looking for?
Comment: This got me started. Thanks Ill let you know how it turns out.
Comment: Sure, I have been working with the Crystal .NET API a lot lately myself. Definitely has been a learning process. Let me know if you need anything else.
Comment: I did what you said and than added export option to export the report to pdf.  but I am not getting anywhere with it. I get error stating database logon failed.  but I am not using database as a source.   the  reportDoc.SetDataSource(ds);  changes the datasoruce to dataset?  am I correct ? if so  it should not throw an error of not connecting to database


Executar um SELECT JOIN com condição para diferentes tabelas

Question: Estou fazendo um sistema de ticket onde possuo a tabela de mensagens de cada ticket. Essa mensagem pode ser enviada tanto por um administrador como pelo usuário que abriu o ticket.
Com isso, estou com o problema na hora de obter o nome do usuário, seja ele um administrador ou o usuário que abriu o ticket, pois seus registros estão em tabelas diferentes (tabela_admin, tabela_usuario).

A primeira opção que tentei utilizar foi a seguinte:
//Estrutura da tabela ticket_mensagem
id  |  ticket_id  |  usuario_id  |  usuario_tipo  |  data_criado

//outro sql obtêm os dados gerais do ticket
SELECT a.*, b.nome
FROM ticket_mensagem a
LEFT JOIN tabela_admin   b ON a.usuario_id = b.id AND a.usuario_tipo = 1
LEFT JOIN tabela_usuario b ON a.usuario_id = b.id AND a.usuario_tipo = 2
WHERE a.ticket_id = '$ticket_id'

Obviamente ele não funcionou, mas a ideia é que eu selecione o nome ou da tabela tabela_admin ou tabela_empresa de acordo com o usuario_tipo.

A segunda opção, seria salvar na tabela ticket_mensagem ou o id do admin ou da empresa, deixando o outro como null, segue exemplo:
//Estrutura da tabela ticket_mensagem
id  |  ticket_id  |  admin_id  |  usuario_id  |  data_criado
1   |      1      |    NULL    |     2        |   .....
2   |      1      |    4       |     NULL     |   .....

//outro sql obtêm os dados gerais do ticket
SELECT a.*, b.nome, c.nome
FROM chamado_msg a
LEFT JOIN tabela_admin   b ON a.admin_id = b.id
LEFT JOIN tabela_usuario c ON a.usuario_id = c.id
WHERE a.id_ticket = '$id_ticket'

O problema é que nenhuma das opções está funcionando e, como essa não é muito minha área, não sei mais como proceder ou decidir qual das opções é a melhor para obter esse resultado e corrigi-las.
Se houver outro meio, algo mais simples ou outro método que seja o correto, não tem problema em alterar. O importante é obter o resultado final, que seria obter o nome do respectivo "usuário", seja ele administrador ou usuário.
Comment: Qual BD está usando?
Comment: @Ricardo Estou usando mysql
Comment: Editei minha resposta e coloquei um link para o [fiddler](http://sqlfiddle.com/#!9/ece81f/3/0) funcionando com IF.
Answer: Para MySql você poderia fazer um IF no Select:
IF(ISNULL(b.nome), c.nome, b.nome) as nome

Não tenho certeza absoluta sobre a sintaxe, mas o IF no select pode resolver de maneira fácil.
ATUALIZANDO.
Troquei o sql acima para ISNULL().
Aqui tem um exemplo funcionando: Fiddler
CREATE TABLE cliente (id INT NOT NULL AUTO_INCREMENT,
                      nome varchar(20) default null,
                      PRIMARY KEY (id)
                      );

CREATE TABLE administrador (id INT NOT NULL AUTO_INCREMENT,
                      nome varchar(20) default null,
                      PRIMARY KEY (id)
                      );

INSERT INTO cliente(id, nome) values (1, null);
INSERT INTO cliente(id, nome) values  (2, "Ricardo");

INSERT INTO administrador(id, nome) values (1, "Daniel");
INSERT INTO administrador(id, nome) values  (2, null);

select
IF(ISNULL(c.nome), a.nome, c.nome) as nome
from cliente c,
administrador a
where c.id = a.id
and c.id = 1

Comment: Mas o nome deles nunca vai ser nulo. Acho que você não compreendeu. Eu preciso pegar o nome do usuário dependendo de quem inseriu aquela resposta ao ticket. Ex.: Se foi um usuario do tipo 1 (adm) eu obtenho da tabela `tabela_admin` e se for do tipo 2 (usuario cliente) eu obtenho da `tabela_usuario`. Mas não obter um ou outro se algum for nulo.
Comment: Em vez de testar a coluna nome testa a coluna tipo na tabela de mensagem: `IF(m.tipo = 1, a.nome, c.nome) as nome`
Answer: Faça um CASE:
SELECT ticket_mensagem.*,
       CASE WHEN ticket_mensagem.usuario_tipo = 1
            THEN tabela_admin.nome
            ELSE tabela_usuario.nome
       END  AS nome
FROM ticket_mensagem
LEFT JOIN tabela_admin   ON tabela_admin.id = ticket_mensagem.usuario_id
                         AND ticket_mensagem.usuario_tipo = 1
LEFT JOIN tabela_usuario ON tabela_usuario.id = ticket_mensagem.usuario_id
                         AND ticket_mensagem.usuario_tipo = 2
WHERE ticket_mensagem.ticket_id = '$ticket_id'

Comment: O seu código está quase funcionando. Estava com alguns erros de syntax e uma lógica. Mudei para isso: `SELECT *, CASE WHEN ticket_mensagem.usuario_tipo = 1` e está obtendo os dados respectivos corretamente. Porém, ele não obtém somente o nome, ele está pegando TODOS os dados da tabela `tabela_admin` ou `tabela_usuario` (dependendo da verificação). Ex.: o admin vem o nome, email, telefone, etc.. E o usuario também vem com nome, cpf, endereço, etc.. Como prevenir isso e obter somente o nome?
Answer: Após alguns testes e algumas tentativas com base nas 2 primeiras respostas, já que nenhuma resolveu o problema diretamente, apenas me guiaram para o resultado final, este foi o código final que utilizei e acabou resolvendo o meu problema:
SELECT
    a.*,
    IF(a.tp_usuario = 1,  b.nome, c.nome) as 'nome'
FROM ticket_mensagem a, tabela_admin b, tabela_empresa c
WHERE a.id_ticket = '$id_ticket'

O problema do uso do CASE é que ele retornava TODOS os dados das tabelas *_adminou *_empresa, enquanto que eu só precisava do nome.
Já o problema na resposta com o uso do if é que ele não pegava o nome admin ou o nome empresa. Ele pegava somente o nome admin ou o nome empresa, mas somente se o nome admin fosse nulo.
Não era essa a verificação que eu queria.
Eu precisava pegar o nome admin se o tp_usuario fosse 1, ou pegar o nome empresa se o tp_usuario fosse 2. Portanto a minha resposta final está funcionando dentro desses requisitos.


What is a light-weight OS X server?

Question: After writing foo.html with some CSS and some JavaScript, I test it on Safari, Firefox, and Chrome, and see that all is well.
I'd now like to debug the files on iOS and Android.
What is the lightest weight server I can launch from the command line? I would like to run in the Terminal:
> runserver .

to be able subsequently to point browsers to, say, http://192.168.5.2/foo.html on either an Android or an iOS device on the local network, and see the file.
Answer: On OSX, Python's SimpleHTTPServer is probably your best bet.
https://docs.python.org/2/library/simplehttpserver.html
python -m SimpleHTTPServer 8000

will serve the current directory at http://localhost:8000/
Comment: @Calaf http://stackoverflow.com/questions/13322485/how-to-i-get-the-primary-ip-address-of-the-local-machine-on-linux-and-os-x
Comment: Perfect, yet somehow incomplete! I can look at what `netstat` says and figure out the IP to connect to from other machines/devices on the network. If you know of a command-line statement that will produce just the IP needed, please share it.
Comment: This is great. It should be in everyone's ~/.bash_profile. I'm puzzled by the downvotes. I wish they would state their objections. Is stackoverflow a better fit than serverfault for this kind of question?
Comment: Neither one's really a fit. Both consider your question off-topic.
Comment: ... the 150+ upvotes on the answer you kindly shared notwithstanding, that is :)

What is a light-weight OS X server?


Understanding which categorical variable has a bigger influence on continuous dependent

Question: I am running a linear regression for Explanatory purposes. Y is continuous and all the explanatory variables are categorical. I understand that the regression coefficient of these variables is the difference in mean of that variable and the mean of the reference for that categorical. My model is as follows:
$Rates = 0.92 + 0.2 \mathrm{Comapny_{STK}} + 0.1 \mathrm{Company_{FLR}} + 0.2\mathrm{Location_{ATL}} - 0.8 \mathrm{Location_{NYC}} + 0.5 \mathrm{Location_{SA}} + \ldots + w_n x_n$
However, is there another method I could use so that the interpretation of the coefficients is similar to that when one runs a linear regression with just continuous explanatory variables, and I could then see the relative effect of each explanatory on $Rates$? I essentially want to see which among $Company$ and $Location$ has the biggest influence on $Rates$. To my understanding, two-way ANOVA's would not be able to answer which of the categoricals has a bigger influence. So I'm not too sure what sort of correlation measure or otherwise to use here.
Answer: Remove the constant from the RHS and take all categories for each categorical value as dummy.
For example, say you have two categorical variables $X, Y$ and one continuous dependent variable $Z$. Assume each of the categorical variables have two categories: $1, 2$
You can model it in two ways
One (seemingly what you have done):
$$E(Z |X, Y)=\beta_0 + \beta_1 D_x + \beta_2 D_y$$
Here $D_x=1$ if $X=x_2$ and $0$ otherwise. Similarly for $D_y$
From this, we have that $$\beta_0 = E(Z | X = x_1, Y=y_1)$$
Alternatively, you can model like this:
$$E(Z |X, Y)= \alpha_1 D_{x_1} + \alpha_2 D_{y_1} + \beta_1 D_{x_2} + \beta_2 D_{y_2}$$
Now each coefficient tells you what is the conditional mean of $Z$ in presence of your categorical variable.
Comment: In method 1, one dummy is less. Say you have not put a dummy for location $X$ and company $Y$. So $\beta_0$ is the mean value of rates when location is X and company is Y. Interpretation of $\beta_1$, which is coefficient of NYC's dummy, is that how much does the mean of rates (when location is NYC and company is Y) different from mean of the rates (when location is X and company is Y). In method two, coefficient of NYC dummy tells you how much is the average rates when location is NYC, regardless of what company is.
Comment: Thank you, this confirms what I was thinking
Comment: In first method, $\beta_1$ is the change in $E(Z|X=x_1)$. What you want is change in $E(Z)$. In first method you get this by $\beta_0 + \beta_1$. In second method you get from $\beta_1$ directly the change in $E(Z)$. To you second question: No there won't be multicollinearity issue here as you have removed the constant term. Think in terms of the $X$ matrix. Only when the first column is $1$ and including separate dummies for all levels of the categorical variables, will the matrix become singular.
Comment: Strictly speaking the above argument on $\beta_1$ is true when there is only one categorical value. But it conveys the idea.
Comment: In second method adding more variables won't change anything. It's still good. And yes making the constant zero does the job. To make this more clear, substitute $D_{x_1}=1-D_{x_2}$. Same for $y$. You'll get back first model with a constant. Second model is just the first model written differently to achieve a simpler desirable interpretation of coefficients.
Comment: Yes. As long as there are dummies for each level
Comment: Thanks. Im still a bit confused: 1) For the first method, wouldn't the $\beta$ values still be having the interpretation that they are the difference in mean of that dummy and the mean of the reference dummy for that categorical? 2) And with the second method, isn't there a potential for multicollinearity issues, given that both dummies for each categorical is being regressed?
Comment: This helps. As the comment right above is based on only one categorical value, when there is more than one categorical variable, is $\beta_1$ just the change in $E(Z)$ while holding the other categoricals constant or how does the interpretation change? And to confirm, to get the influence of different categoricals on a continuous dependent, all one has to do is to set the constant to 0? Thank you
Comment: Thanks. And, again just so that I fully understand, the 2nd model coefficients would have the same interpretation, even in a scenario where a categorical has more than 2 categories?
Comment: Thanks.I understood method 2 but want to understand method 1 better. Looking at [this answer](https://stats.stackexchange.com/questions/120030/interpretation-of-betas-when-there-are-multiple-categorical-variables) Im a bit confused. It suggests $\beta_0+\beta_1$ gives the $E(Rates)$ when $D_x=1$ and $D_y=0$, so in my example it would be $E(Rates)$ when $Company = STK$ and $Location = NYC$ for example, where $NYC$ is the reference for $Location$. Here, I dont see a direct interpretation of $STK$'s effect on $Rates$? Would it be possible to write in words what the interpretation is? Thanks a lot


Added a new user to group www-data and to sudoers, still not sure why user creates new directories as root

Question: I'm new to Linux systems administration (dealing with users and groups) but I do have a lot of command line experience as a developer.  Right now, i'm trying to make sure that three users I've added to my Debian server under the group www-data have the appropriate and expected permissions.  The goal is to have all the directories in /var/www/html/ as www-data:www-data (I think that's what I want at least...I'm doing this so i don't have mixed permissions between things created under root and www-data).
I added my three new users to the sudoers file with the ALL option (the same as root).
I don't know how to think of the users now though and I need some guidance in this.
For instance, when I login as developer1 and issue the command mkdir it tells me I don't have the appropriate permission to do this.  So I sudo and type in the password for my user and then mkdir test...and it shows as a dir with root as the owner and root as the group.
How can I make developer1 a user that can create directories with www-data as owner and group?  Is this the right way to approach this?
thanks.
Answer: The reason why your sudo-created directories are owned by root:root is because sudo literally lets you run commands as a different user, in this case as root (since you did not specify a different username).
Put developer1 into the group www-data, then make sure the directory you want this user to create files/directories in is owned by the group www-data and is writable by said group.
Now developer1 can create files and directories in there, because his group memberships let him do this.
But you'll then notice that these new directories/files are owned by developer1:developer1 (or, alternatively, developer1:users or something like that). To fix this, you can make developer1's primary group www-data, in which case everything he creates will be owned by the www-data group.
If your goal is to have this user create files elsewhere in a different group (e.g. users or developers), but create them as www-data in e.g. /var/www, well, that's one thing I've not yet figured out. So far, I've been stuck with one of two (well, three, really: the third is to just live with it) workarounds:

Have the user(s) manually chgrp files and directories when they are created. Can be done recursively and/or in a batch, so you can e.g. upload a huge number of files and then chgrp them all at once.
Set up a cron job that runs every so often (e.g. every 5-10 minutes) and recursively chgrps everything under your web root (or whatever it is you're trying to control) to www-data. Alternatively, you can use this cron job to chown -R www-data:www-data /var/www to ensure that the files/directories all belong to the www-data user as well as the www-data group.

I realize neither of these is ideal, although once a file is created it will retain its ownership no matter who edits it.
Comment: With regards to your last goal, if the filesystem is local, you should look into using ACLs, which permit setting default groups for files created inside specific directories. The ACL syntax is unfortunately complex, but take a look at `setfacl(1)`.
Comment: You may not want your web root writable by www-data.  This allows anyone who cracks your web server to deface your site, or add malware to it.
Answer: This should work:
# chown -R www-data.www-data /var/www/html
# find /var/www/html -type d -print0 | xargs -0 chmod g+s
# useradd developer1 -G www-data
# useradd developer2 -G www-data

What's happening is setgid and groups. Setgid allows all files and directories created under /var/www/html to be owned by the current group (in this case www-data). By adding the developer accounts to the www-data group, you're ensuring they have write permission.
You may run into further issues if developers are copying files into the directory without group write permissions but those can be fixed manually with chmod by the owner.
Comment: ACLs will also handle default permissions for files created inside those directories.
Comment: For newly created files, default ACLs work great. I've found POSIX default ACLs work for all but one case: If a file that does not have group write set is copied into the directory, the ACL mask will make the effective permissions "r-x" for group


Views argument to match single date with date range field

Question: My content type has a date field with an end date. So an example node has a date range, say from 2011-01-01 to 2011-01-30.
In my view, I want to add an argument/contextual filter that shows any nodes covering a specific day. So if the argument value is 2011-01-15, the node shows (it falls within its range). If the argument value is 2011-02-01, the node doesn't show.
In the Date (node) argument settings, I've played around with selecting both from and to date fields and the OR/AND settings, but can't find a way to do this?
Answer: It's a known bug, please see Multi-day events don't show up on day view of spanned days.
Comment: Thanks - I think I see what you mean. That discussion is about calendar views (I'm using a list view) but it seems that the argument is flawed, regardless of display used in the view. Just so I'm clear... in the argument settings it says "Select one or more date fields to filter with this argument. Do not select both the 'From date' and 'To date' for date fields, only one of them is needed." But whatever field you select (from or to) it doesn't take the whole date span into account?
Comment: Correct. The bug was discovered because of a calendar view, but the query is the same.