how many solutions to non-linear simultaneous equations

Question: I'm doing a Lagrange multiplier optimization problem, and I wound up with the following simultaneous equations:
$2x + 1 -2\lambda x = 0$
$4y-2 \lambda y = 0$
$6z-2 \lambda z = 0$
$-x^2 - y^2 - z^2 + 1 = 0$
I am asked to find ALL solutions, and I managed to find 2 solutions (had to assume that y and z were both zero so equation 2 and 3 would make sense) :
$\lambda_1 = \frac{1}{2}, x_1 = -1$
$\lambda_2 = \frac{3}{2}, x_2 = 1$
But how do I know that these two are ALL the solutions? Is there any way to tell how many solutions I should be able to get, or maybe suggest how to get more solutions?
Thanks.
Comment: You should pretty much try every option you can: If you have $ab=0$, then you must consider $a=0$ and $b=0$ as separate cases. Which means that if you've got $n$ equations like that, you'll end up with $2^n$ cases to consider. (You've got $n=2$ here, so it's not too bad.)
Comment: How are you concluding that both $y$ and $z$ must be zero? At least one must vanish, but both together need not.
Comment: I didn't say that was ALWAYS the case, just one case I found to be solvable...This is why I brought up my original question: How do I know when to stop messing with these equations/ when have I found them all?
Comment: Okay, that helps out. I did what you said took turns making only = 0 and only z = 0 and got a total of 6 solutions. Hopefully that completes the list of solutions.
Comment: That seems correct. I'd suggest submitting your work as an answer to your own question. That way, you can get some rep, we can give you feedback, and anyone who has similar issues may make use of it in the future.
Comment: As a supplement to that last comment: ["Can I answer my own question?"](http://math.stackexchange.com/help/self-answer)
Answer: Since the 2nd and 3rd equation are contradictory when both y and z are not zero, I must try several scenarios where just y, just z, and both y and z are equal to 0. For the y=z=0 case:
Solve equation 1 for x:
$x = \frac{-1}{2-2\lambda}$
plug into equation 4, solve for lambda:
$\lambda = \frac{8 \pm \sqrt{64-48}}{8}$
For each of these two answers, plug back into the x equation for 2 solutions:
$
 x_1 = -1,
 y_1 = 0,
 z_1 = 0,
 \lambda_1 = \frac{1}{2}$
$
 x_2 = 1 ,
 y_2 = 0 ,
 z_2 = 0 ,
 \lambda_2 = \frac{3}{2}
$
Now take the case where z = 0,
Solve equation 2 for lambda:
$\lambda = 2$
Into equation 1:
$x = \frac{1}{2}$
both of these into equation 4:
$y = \pm \sqrt{\frac{3}{4}}$
Giving two more solutions of:
$x_3 = \frac{1}{2}, y_3 = \sqrt{\frac{3}{4}}, z_3 = 0, \lambda_3 = 2$
$x_4 = \frac{1}{2}, y_4 = -\sqrt{\frac{3}{4}}, z_4 = 0, \lambda_4 = 2$
Taking the case where y = 0:
Solve equation 3 for lambda:
$\lambda = 3$
Into equation 1:
$x = \frac{1}{4}$
both into equation 4:
$z = \pm \sqrt{\frac{15}{16}}$
Giving the final two solutions of:
$x_5 = \frac{1}{4}, y_5 = 0, z_5 = \sqrt{\frac{15}{16}}, \lambda_5 = 3$
$x_6 = \frac{1}{4}, y_6 = 0, z_6 = -\sqrt{\frac{15}{16}}, \lambda_6 = 3$
I can't think of any other possibility that would be mathematically legal. If I assume x=0, the first equation becomes $1=0$ which can't happen. Similarly, if I assume lambda = 0, then the 4th equation will eventually become impossible.
Answer: Here is a somewhat different way to organize solving the equations. Observe that the three equations may be expressed as
$$2x(\lambda-1)=1,\quad 2y(\lambda-2)=0,\quad 2z(\lambda-3)=0.$$ The last two equations imply three cases:

$\boxed{\lambda\neq 2,3}\quad$ We require $y=z=0$, and then the constraint $x^2+y^2+z^2=1$ yields $\hspace{2.25cm}$ $x=\pm 1$. The first equation then gives $\lambda=1\mp\frac12=\frac12,\frac32$.
$\boxed{\lambda=2}\quad$ Solving the first and third equations yields $(x,z)=
(\frac12,0)$. The constraint then $\hspace{1.8cm}$ gives $y=\pm \frac{\sqrt{3}}{2}$.
$\boxed{\lambda=3}\quad$ Solving the first and second equations yields $(x,y)=
(\frac14,0)$. The constraint then $\hspace{1.8cm}$ gives $z=\pm \frac{\sqrt{15}}{4}$.

This gives a total of six solutions. As a check, the objective function for this problem is $F(x)=x^2+x+2y^2+3z^2=(x+\frac{1}{2})^2+2y^2+3z^2$ i.e. level sets of ellipses centered at $(-\frac12,0,0)$. It's worth visualizing that to confirm that six solutions are the expected number.


How to determine this solutions?

Question: (a) Determine all positive rational solutions of $x^y=y^x$
(b) Determine all positive rational solutions of $x^{x+y}=(x+y)^y$
Comment: For (a), I found that $(x,y) = (1,1)$ and $(x,y) = (2,2)$ are solutions. For (b), I found that $(x,y) = (2,2)$ is a solution. I don't have a proof that they're the only ones, though.
Answer: a)Here is some of my work.
If $x = y$, then we get $x = y= 1$. Now WLOG, suppose $y > x$.
Let $x = \frac{a}b, y = \frac{c}d$ and suppose that both fractions are reduced.
This gives
$\left( \frac{a}b \right)^{c/d} = \left( \frac{c}d \right)^{a/b}$.
Let $\gcd(a,c) = k$ so $a = pk, c = qk, \gcd(p,q) = 1$.
This gives
$(pk)^{cb}d^{ad} = (qk)^{ad}b^{cb}$.
Which rearranges to
$k^{cb-ad} d^{ad} = q^{ad} \left( \frac{b}{p} \right)^{cb}$.
By assumption, the LHS is an integer. Furthermore, since $\gcd(p,q) = 1$, we must have $p|b$. However, since $\gcd(a,b) = 1$, $p = 1$. If we divide $q$ over, we have two cases. $q|d \implies q = 1$ or $q|k \implies k = qm$.
In the first case, we can reduce our equation to $d^{kd}k^{kb} = b^{kb}k^{kd}$ which implies $d = b$ from taking modulo $d$ and $b$. The solution from this is just $(1,1)$.
Otherwise, $k = qm$.
I think the only solution from this case is $(2,4)$ although I have not verified it since I must now go eat dinner. However, I have verified that these are the only solutions in integers.
Answer:
$(a)$ Determine all positive rational solutions of $x^y=y^x$

$x=\bigg(1+\dfrac1n\bigg)^n$ and $y=\bigg(1+\dfrac1n\bigg)^{n+1}$ For $n=1$ we have the only natural solution, $2^4=4^2$.
Comment: Are those all the positive rational solution? why?
Comment: [Yes](http://en.wikipedia.org/wiki/Wikipedia:Reference_desk/Archives/Mathematics/2013_August_24#Rational_solutions_of_x.5Ey_.3D_y.5Ex).

How to determine this solutions?


Como evitar repetição do código html?

Question: Boa noite, Pessoal. É o o seguinte, estou usando o bootstrap e gostaria de saber como eu evito de repetir os mesmos códigos em todas as paginas, pois o header e o footer são os mesmos, isso deixaria o código mais legivel, andei pesquisando e vi que se deveria usar o Include do PHP, mas não sei como usar, me ajudem, por favor. Grato ;)
Answer: A primeira coisa a se fazer é separar seu website em 3 arquivos.

header.html
conteudo.php
footer.html

Como pode perceber no header terá o cabeçalho e no footer o rodapé.
Então no conteudo.php você fará os includes, o header.html no início do código e footer.html no fim, segue exemplo:
<?php include 'header.html'; ?>

Nome da pagina

<?php  include 'footer.html'; ?>

E assim para todas páginas que queira reaproveitar o cabeçalho e rodapé.
obs. Os arquivos que irão ser incluídos não necessariamente precisam ser PHP, somente onde se quer incluir é necessário PHP.
Comment: Caso você não queira utilizar arquivos .php no seu site, dá  para fazer isso utilizando jQuery.
Comment: Perfeito @Ricardo
Comment: Fiz como vc falou, mas ainda não funciona, tipo, eu coloquei todo o html na pagina, certinho, ai eu tiro todo o código da Navbar e jogo num documento separado, quando eu dou o include ele n mostra a navbar.
Comment: Consegui resolver, eu não havia colocado a extensão da pagina index como php.
Comment: @TiagoSilveira muito bom :) Lembrando que você pode ter quantos includes quiser, por exemplo também separar um menu lateral
Answer: Basta salvar a header e o footer em arquivos separados por ex header.php e footer.php
depois disso na sua pagina principal no lugar do header e do footer vc faz um include
<?php include("header.php"); ?>

faz a mesma coisa no lugar do footer
<?php include("footer.php"); ?>

Answer: Você pode salvar em arquivos diferentes. Isso deixa o código mais limpo, legível e mais rápido em caso de posteriores edições, claro que se usado de maneira correta. Um belo exemplo é se todas as paginas possuem o mesmo rodapé e você precisa alterar uma informação que esta presente nele, sem separar os arquivos você teria que editar em todos, dando mais trabalho.
Segue abaixo um exemplo de um index, fragmentado em vários arquivos:
 <!DOCTYPE html>
<?php
include("inclusoes/cabecalho.php");
if(isset($_GET['sair']) && $_GET['sair']== true){
    unset($_SESSION['usuario']);
    }
 ?>

<?php include_once("inclusoes/menu.php");?>

<?php
if(!isset($categoria)|| $categoria==""){
 include_once("inclusoes/inicio.php");
}
else if(isset($categoria) && $categoria!=""){
    if(file_exists("inclusoes/$categoria.php")){
     include_once("inclusoes/$categoria.php");
    }
    else{
         include_once("404.php");
        }
    }
 ?>
<?php include_once("inclusoes/rodape.php");?>

Espero que isso lhe ajude a compreender.
Lembrando que o include_once tem a garantia que o arquivo não será incluído novamente se ele já foi incluído antes.
Comment: Mas e ai como deve ser a estrutura dos aquivos que estarão separados? muda alguma coisa devido ao fato de eu uso o bootstrap?
Comment: não compreendi sua dúvida...  Mas se eu entendi, não muda nao, porque com os includes no final o arquivo vai ser o mesmo, ele só esta dividido. Como no meu exemplo ali, no meu cabeçalho estao todos os meus links do bootstrap, css, js e outros... Ele esta separado somente, mas com o include, quando a pagina for carregada se torna somente um, compreende?

Como evitar repetição do código html?


Proper way to notate a half measure rest in between sections

Question: I'm working on a score in 4/4 and would like to insert a half-measure rest in between sections. What would be the most appropriate/readable way to do this?
Switch to 2/4 and back, like this:

Or just add two beats to the measure, like this:
Answer: Well, both of them are readable by someone who knows notation, but the second one is technically wrong, since the bar is now 6/4 and not 4/4. So, you could either change the time signature to 6/4 in your second example (just for the first bar) or use the first example.
Comment: THanks for the answer! Yeah, that's what I thought too. I've seen the second one used though, but maybe it was a mistake.
Comment: The 2/4 bar is a better option, as it will be used as a break bar rather than the end of the previous part.
Answer: I would prefer the first example, because the 2nd one is, as already answered, technically wrong. I would suggest a fermata-symbol after the last quarter note.
Comment: A fermata wouldn't work, as its duration is undetermined. There may be something else playing on those two beats which needs exactly a minimum timing. Although not so in this case.
Comment: Thanks for the answer! Why the fermata-symbol exactly? I wouldn't want any notes wavering into the rest, i.e. I prefer a hard stop.
Comment: Not a fermata, unless you want the last note prolonged.  If the exact duration of the break is important and the beat continues, write the 2/4 bar.  If you want a less determined 'breathing point' a caesura symbol ('tramlines') might be an alternative.
Comment: You can add a fermata to a break. dont know why you downvote my answer - so the player can play the break as long as he wishes.


Distribution of population size $n$ given binomial sampled quantity $k$ and selection probability $\pi$

Question: Given a drawn (without replacement) sample size $k$ from a binomial distribution with known probability parameter $\pi$, is there a function which gives distribution of likely population size $n$ from which these $k$ were sampled?  For instance, let's say we have $k=315$ items randomly selected with known probability $\pi=0.34$ from a population of $n$ items.  Here most likely value is $\hat{n}=926$ but what is probability distribution for $n$. Is there a distribution which gives $p(n)$?
I know that $p(\pi | k,n)$ is given by the beta distribution and that $p(k |\pi, n)$ is the binomial distribution.  I'm looking for that third creature, $p(n |\pi, k)$, properly normalized of course such that $\sum_{n=k}^{\infty} p(n)=1$
first "attempt" at this, given the normal approximation to binomial distribution is $p(k|\pi, n)=\mathcal{N}(k/\pi,k\pi(1-\pi))$, is that $p(n|\pi,k)\approx\mathcal{N}(k/\pi,k\pi(1-\pi))$?
Comment: Since the population appears to be finite, we need to know how the sample was taken: was it with or without replacement?
Comment: Please add this new information as an edit to the post, not only as a comment! Not everybody reads comments ... Also, sampling without replacement from a finite population leads to hypergeometric, not binomial, distribution. See also https://stats.stackexchange.com/questions/123367/estimating-parameters-for-a-binomial/123748#123748
Comment: @whuber, thank you for question. samples taken without replacement.
Comment: $$p(n|\pi , k) = \frac{p(k|\pi, n) p(n|\pi)}{p(k|\pi)}$$ are you looking for a reasonable prior $p(n|\pi)$? (When $\pi$ is the parameter, instead of $n$, we often use a beta distribution)
Comment: @kjetilbhalvorsen added to text of original question ... will try to rewrite for greater clarity ... any thoughts on answer to question aside from this replacement vs not distinction ... i'd be open to an answer for either/or case actually
Answer: Let's start with this equation.
$\sum_{n=k}^{\infty}{{n \choose k}\pi^k(1-\pi)^{n-k}} $
Hopefully this is self-explanatory, but as just an intuition you can see this as a brute-force way of calculating your distribution by finding the probability that n pulls came from each possible binomial function. You would then need to divide by some constant $C$ such that: $\sum_{n=k}^{\infty}{\frac{{n \choose k}\pi^k(1-\pi)^{n-k}}{C}} = 1 $ to get a PMF. So if we can figure out what C is, we've got our distribution (even if we don't know the (EV or Varience).
The internet (wolframalpha) seems to be suggesting to me that C is equal to $1/\pi$. Feel free to confirm, but I'm sure that's correct. With that constant, the model simplifies to:
${n \choose k}\pi^{k+1}(1-\pi)^{n-k} $
I ran a simulation with this equation where we have observed n=1 with a probability of .5.
<code>> pmf<-function(n,k,pi){
+   choose(n,k)*pi^(k+1)*(1-pi)^(n-k)
+ }
>
>
> graph<-1:100
> for(i in 1:100){
+ graph[i]<-pmf(i,1,.5)
+ }
>
> plot(graph)
> sum(graph)
[1] 1
</code>

Hopefully this distribution "rings true." 25% of the time we observe 1 success with 50% chance of success, it was after n=1, 25% it was n=2, and then it trails of exponentially from then. The expected value of our distribution is given by:
$\sum_{n=k}^{\infty}{n{n \choose k}\pi^k(1-\pi)^{n-k}} $
and variance:
$ E((X-E(n)^{2}) $
Unfortunately I don't currently have the time to solve those, but I challenge someone here to do so.
Edit: others have suggested a Bayesian solution for this problem. My bone to pick with those is that they assume that n HAS a distribution. Your question seems to assume that N is only distributed in as far as it is dependent on the binomial distribution(s) of $\pi$.
Comment: All the code I used is there, I just ran it for the situation where there was 1 observed event with a known probability pi of .5. It sums to one.
Comment: Right, this is R. I pasted directly from the console, so all of the ">" and "+" a the beggining of the lines aren't code, they are just an artifact of the code being run.
Comment: thank you ... what simulation platform did you use above?
Comment: which software package is this
Answer: Bayes' theorem tells us:
$$
p(n \mid k, \pi) = \frac{p(k \mid n, \pi) p(n \mid \pi)}{\sum_{m=k}^\infty p(k \mid m, \pi) p(m \mid \pi)}
$$
We know $p(k \mid n, \pi)$. That's the Binomial distribution. However, we don't know the form of the prior, $p(n \mid \pi).$ But any possible prior for $n$ can give you an answer to the question. Therefore this question is underspecified. You would get a different answer if $n$ was Poisson distributed (with different parameters), or Negative Binomial distributed, or even distributed from a different Binomial distribution. But regardless, if you knew the distribution you would simply calculate the above expression.
As to your comment that we have $p(\pi \mid k,n)$ in the form of the Beta distribution, that has a similar issue to $n$. That is, we require a prior over $\pi$ to determine a posterior distribution for $\pi.$ For example, a uniform distribution prior gives a posterior of $\text{Beta}(k+1, n-k+1)$ with an expected value $(k+1)/(n+2)$. But a frequentist would estimate $\pi$ as having an EV of $k/n.$ Neither of them are "wrong", it just depends on your assumptions.
$k$ is different from $n$ or $\pi$ in that knowing the other two quantities gives you the information you need to know the distribution over $k$ exactly. The same is not true for either $n$ or $\pi.$

If you want to try an example for an assumed prior of $n$, let's suppose $n$ is Poisson distributed with mean $\lambda.$ Just keep in mind that this is an example, but the above answer still holds; that there's no definite answer to your question, it depends on the prior distribution of $n$.
If $n$ is distributed as $\text{Poisson}(\lambda)$ then the evidence function (the denominator) is,
$$
\begin{split}
p(k) &= \sum_{m=k}^\infty {m \choose k} \pi^k (1-\pi)^{m-k} \frac{\lambda^m e^{-\lambda}}{m!} & \\
&= \frac{ \left( \pi \lambda \right)^k } {k!} e^{- \lambda} \sum_{m=k}^\infty \frac{ \left[ \lambda (1-\pi) \right]^{m-k} } {(m-k)!} \\
&= \frac{ \left( \pi \lambda \right)^k } {k!} e^{-\lambda} e^{\lambda (1-\pi)}\\
&= \frac{ \left( \pi \lambda \right)^k } {k!} e^{-\lambda \pi}.
\end{split}
$$
It's interesting to note that the evidence function, i.e. $p(k)$ is the Poisson distribution with mean $\lambda \pi.$ This seems intuitively obvious when you think about it.
The numerator would simply be the summand of the first line of the above expression, with $n$ replacing $m$. Taking that and dividing the evidence, we get,
$$
p(n \mid k, \pi) = \frac{ \left[ \lambda (1-\pi) \right]^{n-k} } {(n-k)!} e^{-\lambda (1-\pi)}.
$$
Thus $n$ would be distributed such that $n-k$ is Poisson distributed with mean $\lambda (1 - \pi).$


Feature Selection using (low) MCC

Question: I have approximately 1200 input parameters that I am trying to whittle down with the following rough process:
1) Fit rbf SVM with n = 1200 parameters and calculate Matthews Correlation Coefficient(cross validation with 10 partitions)
2) Fit linear SVM, find the lowest weight (absolute value) parameter
3) Fit rbf SVM with n-1 parameters, compare the average MCC and delete the parameter IF my MCC is the same or better
Unfortunately, I didn't have high predictive power in the first place. With all 1200 parameters, the MCC of the rbf SVM was around 0.018. And deleting just one parameter significantly lowered the MCC, sometimes to 0.0.
I'd like some help interpreting these two things:
1) Why should there be a significant difference in predictive power when I use 1200 parameters versus 1200-1 parameters?
2) What does an MCC of around 0.018 mean? Is it all noise? So there is no true predictive power?
And as a last question: Is comparing the MCC not the best approach? Perhaps I can use ROC, but I don't know why one would be preferred over the other. What else would you suggest and why? Any other comments about my procedure would be appreciated!
Answer: Based on my own experience, albeit with a smaller number of inputs than you are using, here are some comments & suggestions that I hope might be helpful to you:
A) Matthews correlation coefficient is generally a good, unbiased metric. I had a very similar problem with zero values of MCC sometimes occurring incorrectly. If you are using python, as i am, then your problem may be the same as mine was, as follows. In calculating MCC, the denominator term involves taking the square root of (TP+FP)(TP+FN)(TN+FP)*(TN+FN), all parts of which are >= 0. In the code, there should be a "> 0" test before evaluating the square root. With TP, FP, TN, FN all being integers, the true value for the denominator of MCC may be a very large number and, although python itself can handle integers of any size, numpy cannot and gives overflow errors in int32. As a result, the denominator calculation for MCC is sometimes an overflow and an apparent negative result, which will then give a zero value for MCC. There are several different solutions to this but effectively they all correspond to forcing TP, FP, TN, FN to "float" in the MCC calculation. For me, this worked fine and removed the erroneous "zero MCC" problem.
B) Using ROC is fine and, from the ROC chart of TPR vs FPR, the difference TPR-FPR is in fact equal to Informedness, a measure of the distance-from-random, which you are obviously seeking to maximize. If you display unit-slope iso-quality lines on your ROC chart, you may find this to be a useful visual display tool  to help you.
C) The other good unbiased metric to complement Informedness is Markedness, which is in fact an unbiased version of Precision and is defined as Markednes = TP/(TP+FP) - FN/(TN+FN).
D) The MCC, which you are already using, is just the geometric mean of Informedness & Markedness, so basically you can either use MCC as a single metric, or both Informedness & Markedness together. Whichever you choose, these 3 metrics are generally better than other alternatives such as F1 score because they give a measure of the quality of your ML itself, without the problem of results being biased by changes in input data.
E) Although using MCC as a single metric may be convenient, you can probably gain more insight into what is happening if you look at your ROC chart and values of Informedness & Markedness.
Best wishes.
Comment: Thanks! I am indeed using python. Will look into this overflow issue.
Comment: I am wondering if your specific application is related to financial markets. If you would like to explain a bit about your application, I may be able to assist you with some more comments about the likely causes & "meaning" of the low MCC results.
Comment: No I'm not doing anything with financial markets, although the problem is similarly (if not more so) random.
Answer: Just as a record for future readers. ROCR package in R makes calculating MCCs much easier. In the beginning I was manually calculating MCC for each threshold alone and I could not have a good grip on defining the plot points. MCC calculation through ROCR is straightforward. All you have to do is read in your data. Then measure the predictions,0 and 1 can be used to label the predictions as T and F. Then measure the performance before proceeding to plot the performance estimation.
So in ROCR you only have to call two lines to do all of that.
<code>target_cm_table_pred<-prediction(data_item_col, T_or_F_col)
target_cm_table_perf<-performance(target_cm_table_pred,"mat")
</code>

Feature Selection using (low) MCC


Porque o onBlur não está sendo executado?

Question: Estava querendo executar uma função no Javascript quando o dropdown perdesse o foco.
Estou fazendo dessa maneira, utilizando onBlur, e não está dando certo:
function DesabilitaFiltro() {
   alert("ok");
}

   @Html.DropDownList("Severidade", (IEnumerable<SelectListItem>)ViewBag.Severidades, "Severidade", new { @class = "ui fluid search dropdown", style = "width: 100%", multiple = "", onchange = "Filtro()", onBlur="DesabilitaFiltro()" })

   <select class="ui fluid search dropdown" id="Severidade" multiple="" name="Severidade" onBlur="DesabilitaFiltro()" onchange="Filtro()" style="width: 100%"><option value="">Severidade</option>
      <option>MEDIA</option>
      <option>ALTA</option>
      <option>BAIXA</option>
      <option>CRITICA</option>
   </select>

Se alguém souber porque não está dando certo, me ajude...
Comment: Como fica o HTML disso?
Comment: ja tentou alterar o `onBlur` para `onblur`? http://www.w3schools.com/jsref/event_onblur.asp
Comment: Ja pensou em usar outro evento? tipo um onclick no elemento da frente? Como o @CiganoMorrisonMendez disse ai, poste o html deste bicho ai para analisarmos melhor.
Comment: Postei o HTML...
Comment: Já tentei os dois jeitos @GuilhermeLautert.
Comment: Pq não roda no onchange?
Comment: @Italo aqui esta rodando de boa, apareceu o alert assim que o elemento perdeu o foco.
Answer: Não existe nada errado com seu código. Pode ser apenas a ordem ou o momento que você está chamando o mesmo.

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo by randrade</title>

   <select class="ui fluid search dropdown" id="Severidade" multiple="" name="Severidade" onblur="DesabilitaFiltro()" onchange="Filtro()" style="width: 100%"><option value="">Severidade</option>
      <option>MEDIA</option>
      <option>ALTA</option>
      <option>BAIXA</option>
      <option>CRITICA</option>
   </select>

Apenas um exemplo utilizando jQuery:

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo by randrade</title>

   <select class="ui fluid search dropdown" id="Severidade" multiple="" name="Severidade" onchange="Filtro()" style="width: 100%"><option value="">Severidade</option>
      <option>MEDIA</option>
      <option>ALTA</option>
      <option>BAIXA</option>
      <option>CRITICA</option>
   </select>

Apenas verifique o momento que sua função está sendo "carregada" no navegador, isso pode estar ocasionando problemas.
Fiddle - JavaScript
Fiddle - jQuery
Comment: Por incrível que pareça no IE funciona, já no Firefox e Chrome não.
Comment: @Italo A minha resposta ou quando você adiciona em seu código?
Comment: Quando eu rodo o meu código @Randrade.
Comment: Isso é algo com o seu código. Aparece algum erro no console do navegador?
Comment: Parece não, e fui debbugando no F12 e não aparece nenhum erro.
Comment: @Italo Adicione a ordem de seus imports juntamente com o `@section Scripts{}`
Comment: coloquei section e não resolveu o problema.
Comment: @Italo adicione como está seu código na pergunta
Answer: Seu código está funcionando sem problemas. Acredito que o comportamento que você esperar não é o que o método faz. Como sugestão, você pode rodar no onchange os dois metódos. Veja:

function DesabilitaFiltro() {
  alert("ok");
}

  <select class="ui fluid search dropdown" id="Severidade" multiple="" name="Severidade" onchange="DesabilitaFiltro();Filtro();" style="width: 100%">
    <option value="">Severidade</option>
    <option>MEDIA</option>
    <option>ALTA</option>
    <option>BAIXA</option>
    <option>CRITICA</option>
  </select>

Answer: Italo, sempre separe comportamento do HTML.
Ao passo que você começar a fazer isso, verá que dúvidas no estilo "Porque XXXX não está executando" irão diminuir naturalmente.
No seu exemplo:
Inclua uma tag script no final do html e faça algo como:

var el = document.querySelector('#Severidade');
el.addEventListener('change', function alterouFiltro() {
  console.log('alterado');
}, false);

el.addEventListener('blur', function focoFiltro() {
  console.log('perdeu o foco');
}, false);
<select id="Severidade">
  <option>Opção 1</option>
  <option>Opção 2</option>
  <option>Opção 3</option>
</select>
Comment: Eu colocaria dentro de uma $(document).ready(function ()?
Comment: Sim, também pode ser.


Bundler::RubyVersionMismatch after running tests

Question: Rails test case was not working.
When I ran my test, it showed the following error.
validate_ruby!': Your Ruby version is 2.3.3,
 but your Gemfile specified 2.4.2 (Bundler::RubyVersionMismatch)

Comment: You'll need to either upgrade your Ruby version, or specify the version you have, as stated in the error message
Comment: how to update my Ruby version?
Comment: acutually my ruby version is 2.4.2
Answer: Add/replace the ruby version as ruby "2.3.3" in your Gemfile
Comment: again i got this error : -  block in materialize': Could not find rake-12.3.1 in any of the sources (Bundler::GemNotFound)
Comment: Your Ruby version is 2.4.2, but your Gemfile specified 2.3.3
Comment: You should remove `ruby "2.4.2" `. You do one thing just try `ruby -v` and check what is your ruby version. If you  using rvm check what is the version in that `rvm list`. Then set the proper version in the Gemfile.
Comment: My version is ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin17]
Comment: Remove the `Gemfile.lock` from  and do the `bundle install`


How to represent the point-wise devision in mathematical symbols?

Question: For example, I want to represent the following Matlab script in formal mathematical symbols.
<code>1./(1+exp(-X*beta))
</code>
Answer: $$
\left\{X_{ij}\right\}_{nm} \rightarrow \forall i < n \quad \forall j < m
$$
$$
Z_{ij} = \frac{1}{1+e^{-\beta X_{ij}}}
$$


Fancybox gallery

Question: I have one button in node body called 'Gallery' and I need to show fancybox with thumbnails when button is clicked.
What is the simplest way to do that?
Comment: Have you looked at the fancboxy module?

https://drupal.org/project/fancybox
Comment: yes, I already install module, problem is how to use it like I describe above...
Answer: I create gallery using Views. I create block and insert that block in node's body using Insert Block module.
My first image in gallery is button because I need to show full gallery only when button is clicked, I use this solution to hide other images (but to view that images in fancyBox)...

Fancybox gallery


Is there any library to Convert flash to a represent png file?

Question: I want to generate thumbnail image from a flash file,
Is there any library to do this?
Many thanks
Answer: The Flash authoring tool lets you do that. You can export about any part of your flash movie to a png file through the command File/Export.
If you want to do that automatically from an swf file, several tools have gone some way through this function, though with varied results. The point is, a flash movie is a complex program with time, animation, user interaction, so... generating a thumbnail is not always as simple as just taking the first frame and exporting the pixels to an image. Very strictly speaking, a flash file being a program that displays graphics and animations, it can't be written to a simple image in a generic way.
However, you can do more restricted things, like write the output of the first frame of the swf for example. There are tools doing those kind of things, each with its limitations, each with its functionalities. They usually work best under linux or some other unix, and some of them have a windows version too. Check the following :
swftools
swfdec
pyswfdec
Gnash
Now if your "flash file" is an flv file rather than an swf file, you can export it as another type of video, including a sequence of png images, with mplayer.
In another way of thinking about it, the standard way to generate a thumbnail for an swf file is just to run it in your browser and take a screencap. If you only have a few files to go, it might be the simplest way to go.


Is there a more pythonic way of exploding a list over a function's arguments?

Question: def foo(a, b, c):
 print a+b+c

i = [1,2,3]

Is there a way to call foo(i) without explicit indexing on i?
Trying to avoid foo(i[0], i[1], i[2])
Comment: Used in function definition many times, so why not use it when calling... Thanks for reverting my python head guys.
Answer: Yes, use foo(*i):
>>> foo(*i)
6

You can also use * in function definition:
def foo(*vargs) puts all non-keyword arguments into a tuple called vargs.
and the use of **, for eg., def foo(**kargs), will put all keyword arguments into a dictionary called kargs:
>>> def foo(*vargs, **kargs):
        print vargs
        print kargs

>>> foo(1, 2, 3, a="A", b="B")
(1, 2, 3)
{'a': 'A', 'b': 'B'}

Answer: It's called argument unpacking and there's an operator for it.
foo(*i)

By the way, it works with any iterable, not just with lists.
Comment: +1 for dropping the name of the game. actually this what helps to google this thing for any language. Thanks a lot.
Answer: Yes, Python supports that:
foo(*i)

See the documentation on Unpacking Argument Lists. Works with anything iterable. With two stars ** it works for dicts and named arguments.
def bar(a, b, c):
    return a * b * c
j = {'a': 5, 'b': 3, 'c': 2}

bar(**j)


Intervals specified according to column values in PostgreSQL

Question: My Data is like this
wavelength    reflectance
341.6         2.48
343.6         2.58
347.6         4.51
351.1         8.51
359.2         9.56
362.2         11.2
364.2         25.3
365.3         58.2
366.6         58.2
368.9         24.2
373.6         28.2

I wish to take 10 intervals of wavelength and the reflectance intervals in between them is taken average then the output will be
I want output like this
wavelength    reflectnce
341.6         2.48
351.1         5.20
362.2         10.38
373.6         32.35

Comment: Er, what? I'm not sure how you're getting from the input to the output.
Comment: can you describe what is the relation between your table and your result?
Comment: the relation is that if i give 10 intervals. the output will be displayed according to shown above, If you seen the data, the interval if i provide 10 it is taking the interval values according to wavelength, and then the corresponding reflectance values of the wavelength[inteval size is varied for every 10 ]
Comment: In your sample output the wavelengths are not exactly 10 apart. The intervals are 9.5, 11.1, 11.4. Do you mean each wavelength should be "the next one which is closest to 10 greater than the previous one"?
Comment: yes each wavelength should be selected or before one which is closest to 10
Answer: In SQL Server you can do it like this:
;WITH CTE AS(
SELECT ROW_NUMBER() OVER(PARTITION BY CAST(wavelength AS INT)-CAST(wavelength AS INT)%10 ORDER BY wavelength) AS ROW_ID,wavelength,reflectance FROM Your_Table
)

SELECT wavelength,reflectance FROM CTE WHERE ROW_ID=1

Hope it would help.
Comment: Suraj thanks, it is very related to me, but it showing some intervals not according to 10, if u want i will send the data to u...
Comment: Could you please share the scenario in which it is not working as expected.
Comment: 341.6;2.66
349.5;2.45
360.5;2.48
369.9;2.50
380.8;2.53
390.1;2.75
401.0;2.95
410.2;3.33
420.9;3.71
430.1;4.00
440.8;4.06
449.9;4.30
460.5;4.34
469.6;4.55
480.1;4.56
490.7;4.61
499.6;5.02
510.1;5.77
520.5;7.21
530.9;8.87
539.8;9.69
550.1;9.88
560.4;10.01
570.6;9.58
580.9;8.59
589.6;8.07
599.7;7.82
609.8;7.71
619.8;7.28
629.8;6.93
639.7;6.63
649.6;6.28
660.8;6.06
670.6;5.87
680.3;6.39
689.9;8.14
699.5;11.71
710.4;17.73
719.9;23.12
730.6;28.74
739.9;32.48
Comment: Got the following result with your data;

wavelength reflectance
341.6 2.66
360.5 2.48
380.8 2.53
390.1 2.75
401 2.95
410.2 3.33
420.9 3.71
430.1 4
440.8 4.06
460.5 4.34
480.1 4.56
490.7 4.61
510.1 5.77
520.5 7.21
530.9 8.87
550.1 9.88
560.4 10.01
570.6 9.58
580.9 8.59
599.7 7.82
609.8 7.71
619.8 7.28
629.8 6.93
639.7 6.63
649.6 6.28
660.8 6.06
670.6 5.87
680.3 6.39
699.5 11.71
710.4 17.73
730.6 28.74
Comment: Now the code you provided is correct, then i want to mean the reflectance values of the intermediate rows and the mean should be placed as the next reflectance value


The Swan of Tuonela: Sibelius, Wagner, and Smetana

Question: I was very much impressed by the clarity of expression and romantic beauty of Jean Sibelius' 1893 The Swan of Tuonela as performed by the Gothenburg Symphony under Neeme Järvi and as featured on France Musique's Venez quand vous voulez the other day (it starts approx. 90' into the podcast).
Presenter Denisa Kerschova described it as something "between Wagner and Smetana" (if my French serves well enough). I can certainly hear a kinship to Wagner: the whole atmosphere, the dynamism of the orchestra, etc. (The piece reminds me even stronger of Gottfried Huppertz score for Fritz Lang's 1924 Die Nibelungen, so there you have another link to Wagner.)
But then I am not familiar enough with Smetana to judge on that side. Is it likely that Kerschova just wanted to point out that both Sibelius and (her Czech compatriot) Smetana were important catalysts for national movements in their two home countries in the 19th century, or is there a deeper links in terms of art and music? And if so, where would I have to start with Smetana's work to find something of similar quality?
Answer: The two best-known and oft-performed works by Smetana:

My Country (cz: Má Vlast): it is really a suite of tone poems which can themselves be performed independently. Of these, the most well-known is The Moldau, which is a pictorial description of the Moldau river (cz: Vltava) that runs through Prague. The only other of them with which I have familiarity is Tábor, because it contains the ancient Hussite hymn: "Ye Who Are Warriors of God". This is also a hymn used by 20th c. composer Karel Husa in the final movement of his Music for Prague 1968. If a loose confederation of symphonic poems sounds strange, think of Holst, The Planets, which similarly can have individual "planets" broken out into standalone works.
His opera, The Bartered Bride: it only occasionally sees performance in the US as a fully staged opera, but frequently has some purely orchestral movements performed in lighter, pops-esque performances. Dover actually sells a volume that gets most of this music into one package.

After listening to these works, I'd be interested to hear what connections you make. I find it a bit of a stretch to say that a 19th-20th c. Finnish composer "the last true Romantic composer" as Sir Thomas Beecham called him, straddles in any way the mid-19th c. German arch-progressive Wagner and 19th c. arch-Czech-nationalist Smetana. To my ear, they inhabit three severely different sound worlds. Their approach to orchestration, harmony, and melody? Sure, there are smaller connections, but one of Smetana's goals was to avoid sounding like a poor man's imitation of German music, to create something that is authentically Czech. Likewise with Sibelius and Finland, although perhaps not to that degree. I might call him the last of the nationalists or perhaps a post-nationalist, in the sense in which it is discussed in the context of its origins in the 19th century.
I understand and greatly appreciate radio broadcasts that try to help make basic connections for listeners, but this seems like more than just a little bit of a stretch, but again, I'm interested to see what connections you make.
Comment: Thanks for your reply. I will try to get hold of these works (am somewhat familiar with *The Moldau*, but will relisten), and try to report back here. BTW, I should explain that I registered a kinship between *The Swan of Tounela* and Wagner's instrumental work, i.e. his operas minus the heavy voices. Perhaps that's no way to do him real justice, but I'm very fond of his music (and think of him as an truly path-breaking genius) but never enjoy listening to his heros' voices, which I find quite straining.
Comment: I've now listened to Smetana's *The Moldau* again. I think he does use a similar overall approach to Sibelius' in the *The Swan of Tuonela*: with  rapidly oscillating strings (reminding us of nordic winds and the Moldau's waves respectively, I suppose, and to my ear and across another century also a bit similar to Philip Glass' abstract minimalistic style) on top of which main themes are deployed. In terms of atmosphere the pieces seem different, and I personally far prefer the Sibelius (e.g. don't like how Smetana adds folksy tunes as e.g. also Mahler did in his time).


c# print the power of a number using recursion

Question: I am learning about recursion and I am required to multiply and do the power of two given numbers. When I run my code it doesn't work (meaning nothing shows on the console)
Methods:
 static int multiply (int x, int y)
    {
    if ( y == 1 )
        return   x ;
   else
        return (x + multiply(x, y - 1));
     }

    static int power(int x,int y)
    {
        if (y == 0)
            return 0;
        else
            return (x * power(x, y - 1));
    }

Main method:
static void Main(string[] args)
    {
        multiply(2, 4);
        power(2, 5);
        Console.ReadLine();
    }

Anybody have any ideas? I have a feeling im doing something obviously stupid.
Comment: `if (y == 0) return 0;` here should be `return 1`
Comment: You're never outputting anything..
Comment: Why do you expect something to show on the console?
Comment: for multiplication
if ( y == 0 )
        return  0 ;
   else
if ( y == 1 )
        return  x  ;
   else ...
Answer: Output your code to console:
Console.WriteLine(multiply(2, 4));
Console.WriteLine(power(2, 5));

You may also need to fix the bug on power:
if (y == 0) return 1; // x⁰ = 1

Comment: Oh yes, how stupid of me. Completely overlooked those two bits. Thanks
Answer: Currently, you are not outputting any data to the console so you can see it. The function Console.WriteLine() will write to the console. Console.ReadLine() on the other hand, will continually wait for input from the console, this is to prevent the program from exiting immediately. Your Main method should look more like this:
static void Main(string[] args)
{
    int z = multiply(2, 4);
    int p = power(2, 5);
    Console.WriteLine("z : " + z);
    Console.WriteLine("p : " + p);
    Console.ReadLine();
}

You will notice a bug in your power function, but I'll let you debug that once you can see the output.
Answer: Try this:
static void Main(string[] args)
    {
        Console.WriteLine("2*4=" + multiply(2, 4));
        Console.WriteLine("2^5=" + power(2, 5));
        Console.ReadLine();
    }


Diff EQ. Problem (Eigenvector issue)

Question: Find the general solution of $\textbf{x}^{'}=\begin{pmatrix} -1&-4\\1&-1\end{pmatrix}\textbf{x}$.
The eigenvalues I found are $-1 \pm 2i $ and I chose $-1-2i$ to be my eigenvector and found it to be $e_1=\begin{pmatrix} 2i\\-1 \end{pmatrix}$ Now plugging this in to the formula we have $$e^{-t}\begin{pmatrix} 2i \\-1 \end{pmatrix}(\cos 2t-i\sin2t)=c_1e^{-t}\begin{pmatrix}  2\sin 2t\\-\cos 2t \end{pmatrix} + c_2e^{-t}\begin{pmatrix} 2 \cos 2t\\ \sin 2t \end{pmatrix}$$ The book however has: $c_1e^{-t}\begin{pmatrix} - 2\sin 2t\\\cos 2t \end{pmatrix} + c_2e^{-t}\begin{pmatrix} 2 \cos 2t\\ \sin 2t \end{pmatrix}$. How did the signs get switched because I tried to do this with $e_2=\begin{pmatrix} -2i\\-1 \end{pmatrix}$ and all that happens is the right side becomes negative which still doesn't explain how the signs are switched.
Comment: Since the constants are arbitrary until you use initial conditions to solve for them, it is fine. It is a similar trick as to how you got all the $i$ terms to drop out by being absorbed into $c_2$.
Comment: Your $c_1$ is the negative of the book's $c_1$.
Comment: but how did that happen is this correct?
Comment: Thanks I understand that part, but what I dont understand is why they would do something random and factor out a negative 1. I understand that $\dfrac{1}{\sqrt{3}}=\dfrac{\sqrt{3}}{3}$ because we dont want radicals in the denominator. Now why factor out a $-1$?
Answer: Both answers are correct. To expand on John Habert's comment, since the coefficient $c_1$ is arbitrary, your $c_1$ is the negative of the book's $c_1$. To see what I mean, replace your $c_1$ with $-c_1$: you'll get the book's answer.
Comment: Is there any particular reason why they factor out a $-1$? I just think that can be confusing to do random things like that.
Comment: There is no good reason for it. Whoever worked out the solution did so in a slightly different way than you did and the final *form* of the answers was different, though they are the same answer.
Comment: If this is an initial value problem, then it is possible this choice of signs makes finding $c_1,c_2$ a little easier.
Comment: Ahhh okok I got it.

Diff EQ. Problem (Eigenvector issue)


Geolocalização não funciona Google Chrome

Question: Alguém com problema de geolocalização não funciona Google Chrome.
Funciona normalmente nos outros navegadores, no chrome não funciona, acompanhe no link abaixo.
http://wernercoiffeur.net/oferta-2016/
Answer: Conforme o log informa:

[Deprecation] getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS.
  (anonymous) @ index.php:80

Ou seja getCurrentPosition e watchPosition não podem ser usadas se sua página não for em HTTPS, isto provavelmente foi inativado em HTTP para evitar que interceptações no meio do caminho obtenham os dados de localização do usuário.
Mais detalhes em: https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins
Soluções alternativas
No entanto se deseja pegar a latitude e longitude atual (não tem precisão garantida) pode usar algo como desta resposta no SOen, em JavaScript ficaria algo como:
getGEO(function (lat, long) {
    //Aqui você pode setar a latitude e longitude no seu mapa
    console.log(lat, long);
}, function(msg, details) {
    console.log("Erro", msg, details);
});

function getGEO(done, fail){
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://ipinfo.io/geo", true);

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var err;

            if (xhr.status >= 200 && xhr.status < 300) {
                try {
                    alert(1);
                    var parsed = JSON.parse(xhr.responseText);
                    var ll = parsed.loc.split(",");
                    done(ll[0], ll[1]);
                } catch (ee) {
                    fail('Parse error', ee);
                }
            } else {
                fail('Request error', xhr.status);
            }
        }
    };

    xhr.send(null);
}


Python Matpolotlib error while using contourf

Question: I am trying to execute the following program and the I am receiving the warning at the end of the result. Please educate me regarding the error.
"/usr/lib/pymodules/python2.7/matplotlib/collections.py:548: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  if self._edgecolors == 'face':"
<code>        import numpy as np
        import matplotlib.pyplot as plt

        colorinterpolation = 50
        colourMap = plt.cm.jet

        x =  input('Number of nodes in the vertical axis: ')
        y =  input('Number of nodes in the horizontal axis: ')
        TI = input('Initial tempertature: ')
        TN = input('Northern boundary temperature: ')
        TS = input('Southern boundary temperature: ')
        TE = input('Eastern boundary temperature: ')
        TW = input('Western boundary temperature: ')
        t  = input('Number of time steps needed: ')
        C1 = input('Courant number in x direction: ')
        C2 = input('Courant number in y direction: ')
        C3 = 1 - (2*C1) - (2*C2)

        T = np.zeros((x, y))
        T.fill(TI)
        print 'Time step 0'
        print T
        for timestep in range(1, t+1):
            T[:1, :] = TN
            T[x-1:, :] = TS
            T[:, :1] = TW
            T[:, y-1:] = TE
            print 'Time step', timestep
            for j in range(1, y-1, 1):
                for i in range(1, x-1, 1):
                    T[i, j] = T[i, j]*C3 + C1*(T[i+1,j] + T[i-1, j]) + C2*(T[i, j+1] + T[i, j-1])
            print T

       plt.contourf(np.flipud(T), colorinterpolation, cmap=colourMap)
       plt.title('2-D transient heat conduction')
       plt.colorbar()
       plt.show()
</code>
Answer: Mind that this is not actually an error, just a warning. So you can ignore it, if otherwise everything works as expected. It could be caused by some mismatch in between versions, see e.g. here
You may consider updating numpy and matplotlib if you really aim at getting rid of this warning.


Give an explicit example of a probability measure $\mathbb{P}$ on $\mathcal{F}_1$.

Question: Let $\Omega = \{(i, j)|i, j \in \{-1, 1\}\}$.
The first part of the question is to give an example of two event spaces $\mathcal{F}_1$ and $\mathcal{F}_2$ of subsets of $\Omega$, such that $\mathcal{F}_1 \cup \mathcal{F}_2$ is also an event space. For this I have $\mathcal{F}_1 = \{(-1, -1), \Omega, \emptyset, \{(-1, 1), (1, -1), (1, 1)\} \}$ and $\mathcal{F}_2 = \{\{(1, 1), (1, -1)\}, \Omega, \emptyset, \{(-1, 1), (-1, -1)\} \}$, and this works because the complement of $\{(-1, -1)\} \cup \{(1, 1), (1, -1)\}$ is not contained in $\mathcal{F}_1 \cup \mathcal{F}_2$. My definition of an event space has been included below.
The second part of the question is as follows:
give an explicit example of a probability measure $\mathbb{P}$ on $\mathcal{F}_1$. How would I go about answering this? My definition of a probability measure has been included below.
Event space definition:
let $\Omega$ be the sample space and $\mathcal{F}$ be a collection of subsets of $\Omega$. $\mathcal{F}$ is an event space (also called $\sigma$-algebra) if it satisfies
(i) $\Omega \in \mathcal{F}$; (ii) if $A \subseteq \Omega, A \in \mathcal{F} \Rightarrow A^c \in \mathcal{F}$ ($\mathcal{F}$ is closed under complements); (iii) if {$A_n: n \in \mathbb{N}$} is such that $A_n \in \mathcal{F} \ \forall n$ then $$\bigcup_{n=1}^{\infty} A_n \in \mathcal{F}$$ ($\mathcal{F}$ is closed under countable unions.)
Probability measure definition:
given a sample space $\Omega$ and an event space $\mathcal{F}$, a function $\mathbb{P}: \mathcal{F} \rightarrow \mathbb{R}$ is called a probability measure if it satisfies
(i) $\mathbb{P}(B) \in [0, 1]$ for every $B \in \mathcal{F}$; (ii) $\mathbb{P}(\Omega) = 1$; (iii) (Countable additivity) For every $A_n \in \mathcal{F}, n \ge 1$ disjoint events (i.e. for all $m, n \geq$ such that $m \neq n, A_m \cap A_n = \emptyset$, $$\mathbb{P}(\bigcup_{n=1}^{\infty} A_n) = \sum_{n=1}^{\infty}\mathbb{P}(A_n) $$
Answer: Essentially, the event space $\mathcal{F}_1$ can be rewritten as $\mathcal{F}_1 = \{\Omega, \emptyset, A, A^c\}$, where $A = (-1, -1)$. Thus, in order to get a probability measure $\mathbb{P}$ on $\mathcal{F}_1$, we assign as follows
$$
    \mathbb{P}(\Omega) = 1, \mathbb{P}(\emptyset) =0, \mathbb{P}(A) = p, \mathbb{P}(A^c) = 1-p
$$
for some $p \in [0, 1]$. Can you check if $\mathbb{P}$ is a probability measure ?
Comment: I guess I just have to check $\mathbb{P}$ against the definition of a probability measure to check if $\mathbb{P}$ is really a probability measure?
Comment: Yes, that's correct @Alex
Comment: What about countable additivity. How do we verify this characteristic is satisfied for the probability measure? @Thành Nguyễn


Evaluate $\lim_{(x,y) \to (0,0)}\frac{-xy}{x^2 + y^2}$

Question:
Evaluate the following limit: $$\lim_{(x,y) \to (0,0)}\frac{-xy}{x^2 + y^2}$$

My try:
Using polar substitution - putting $x =r\cos(\theta)$, $y = r\sin(\theta)$,
$$\implies\lim_{r \to 0} \frac{-r^2\cos(\theta) \sin(\theta)}{r^2(\sin^2\theta+\cos^2\theta)} =\lim_{r \to 0} -\cos(\theta) \sin(\theta) = -\cos(\theta) \sin(\theta)$$
Does this make any sense?
Also, approaching from two different sides,
$$\begin{align}\lim_{(x,y) \to (0,0)}\frac{-xy}{x^2 + y^2} & = \lim_{x\to 0}\frac{-x(0)}{x^2 + (0)^2} = 0\\\lim_{(x,y) \to (0,0)}\frac{-xy}{x^2 + y^2} & = \lim_{y\to 0}\frac{-(0)y}{(0)^2 + y^2} = 0 \end{align}$$
Both are equal... but the limit doesn't exist which I verified from Symbolab. What should I do to evaluate this?
Comment: You cancel the $r^2$ so the limit depends essentially on your angle. Wouldn't that indicate that the limit does not exist? Just to be clear: You can use polar coordinates to prove that the limit does NOT exist. You cannot use polars to prove that the limit exist.
Comment: What happens if you approach to the origin along the line $y=x$?
Comment: Well, there can be only one limit, and $\theta$ can change. $\cos\theta\sin\theta$ is a "directional limit." But $\lim_{(x,y)\to (0,0)}$ doesn't specify a direction.
Answer: Consider $(x, y) = (\frac{1}{n}, \frac{1}{n})$ as $n \to \infty$. In that case, your limit evaluates to $-\frac{1}{2}$, which is a contradiction with the other two limits you found so the limit doesn't exist.
Answer: Let $y=ax$. Then
$$
\lim_{x\to0}f(x,ax)=\frac{-a}{1+a^2}
$$
and certainly depends on $a$.
Answer: Using polar coordinates you find that $$\lim_{(x,y)\to (0,0)}\frac{-xy}{x^{2}+y^{2}}=\lim_{r\to 0;r>0}\frac{-r^{2}\cos \theta\sin \theta}{r^{2}}=-\cos\theta\sin\theta, \quad (*)$$
So the limit doesn't exists, it depends of values for $\theta$ , just take $\theta=\pi$ and we have $0$ as limit but $\theta=\pi/6$ we have $-\sqrt{3}/4$ as limit, contradiction. I think it's perfectly valid argument. If you need use path, just see in the path $r(t)=(t,mt)$ with $m\in \mathbb{R}^{*}$.
EDIT:
As pointed out Hans Lundmark in the comment, the line in $(*)$ has problems about rigor mathematics. We will try to fix with change of variables to polar coordinates we have for $x^{2}+y^{2}\not=0$, that,
$$\frac{-xy}{x^{2}+y^{2}}=-\frac{r^{2}\cos\theta\sin\theta}{r^{2}}=-\cos\theta\sin\theta, \quad r>0$$
and since for different values of $\theta$ we get differents values so the $\displaystyle \lim_{(x,y)\to (0,0)}\frac{-xy}{x^{2}+y^{2}}$ doesn't exists.
Comment: The argument is valid, but it shouldn't be written that way. The first equals sign that you have written is false, since the left-hand side doesn't exist, while the right-hand side does, if you interpret it as a one-variable limit in $r$ for a fixed value of $\theta$, which is precisely what you do when you write your second equals sign.
Comment: Hi @HansLundmark thank you for the feedback and I understand your remark. Can you show how I should write it, formally? Maybe as like: Change of variables to polar coordinates give $\frac{-xy}{x^{2}+y^{2}}=-\cos\theta\sin \theta$ and then fix $\theta$ for some values? I understand the problem is in left-hand the limit doesn't exists but right-hand the limit exists so not matching.
Comment: Yes, that's much better. Write it like that, and then say something like "since we get different values for different $\theta$, the two-variable limit doesn't exist".
Comment: @HansLundmark I edited, what do you think now? Thanks for you feedback.
Comment: It still looks weird to me, since you write that something (which actually doesn't exist, but we don't know that yet) is simultaneously equal to $0$ and to $-\sqrt{3}/4$. I would avoid using the notation $\lim_{(x,y)\to (0,0)}$ at all, until after the limit has been shown to exist (or not).
Comment: Hi @HansLundmark I fixed it again, now is it more rigorous?
Comment: Now it looks fine!
Comment: Thank you very much, I have learned a lot from your corrections @HansLundmark !


Change WooCommerce Product Name Include Color When Attribute Selected

Question: I'm looking for someone me help getting the WooCommerce variable product title to change based on color. In this specific case I would like the title to change when a color is selected, like "Product name - Black".
I follow this topic Change WooCommerce variable product title based on variation but it not work with WooCommerce version 3.9.1
and the code
add_filter( 'wp_footer','custom_product_title_script' );
function custom_product_title_script(){
    global $post;

    // Only single product pages
    if( ! is_product() ) return;

    // get an instance of the WC_Product Object
    $product = wc_get_product($post->ID);

    // Only for variable products
    if( ! $product->is_type( 'variable' ) ) return;

    // Here set your specific product attributes in this array (coma separated):
    $attributes = array('pa_color');

    // The 1st loop for variations IDs
    foreach($product->get_visible_children( ) as $variation_id ) {

        // The 2nd loop for attribute(s)/value
        foreach($product->get_available_variation( $variation_id )['attributes'] as $key => $value_id ){
            $taxonomy = str_replace( 'attribute_', '', $key ); // Get the taxonomy of the product attribute

            // Just for defined attributes
            if( in_array( $taxonomy, $attributes) ){
                // Set and structure data in an array( variation ID => product attribute => term name )
                $data[ $variation_id ][$taxonomy] = get_term_by( 'slug', $value_id, $taxonomy )->name;
            }
        }
    }

    ?>

    <?php
}

Answer: I try new code and it work with new version 3.9.2
add_filter( 'wp_footer','custom_product_title_script' );

function custom_product_title_script(){
    global $post;

    // Only single product pages
    if( ! is_product() ) return;

    // get an instance of the WC_Product Object
    $product = wc_get_product($post->ID);

    // Only for variable products
    if( ! $product->is_type( 'variable' ) ) return;

    // Here set your specific product attributes in this array (coma separated):
    $attributes = array('pa_colour');

    // The 1st loop for variations IDs
    foreach( $product->get_visible_children() as $variation_id ) {

        // The 2nd loop for attribute(s)/value
        foreach($product->get_available_variation( $variation_id )['attributes'] as $key => $value_id ){
            $taxonomy = str_replace( 'attribute_', '', $key ); // Get the taxonomy of the product attribute

            // Just for defined attributes
            if( in_array( $taxonomy, $attributes) ){
                // Set and structure data in an array( variation ID => product attribute => term name )
                $data[ $variation_id ][$taxonomy] = get_term_by( 'slug', $value_id, $taxonomy )->name;
            }
        }
    }

    ?>

    <?php
}


Mudar o tema da navbar do Bootstrap

Question: Olá,
Procurei muito na internet um método que eu possa mudar o tema da navbar do Bootstrap ao clicar em um botão.
Navbar quando o usuário acessou o site:

Quando o usuário clicasse no botão:

Grato desde já.
Answer: Podes usar a classe navbar-inverse que faz o efeito que procuras.
Junta um auscultador de eventos que remova essa classe no primeiro clique.
Um exemplo seria assim:
$('.navbar-inverse').on('click', function(){
    $(this).removeClass('navbar-inverse');
});

Exemplo: https://jsfiddle.net/7q6chbsL/

Mudar o tema da navbar do Bootstrap


material ui and redux-form - how to implement submit validation

Question: I am using Redux Form and material UI to implement a registration page. My onSubmit function uses the fetch API to send a POST request to the server. If there is any server-related error (e.g duplicate email) the server returns an error response with some details about the rejected fields.
At this stage, I would like to display the errors in my form, but I can't get it to work. I tried throwing a SubmissionError, and throwing a JSON object. Is there any example online that I can follow?
Thanks.
Answer: You should use asyncValidate prop of reduxForm decorator.
asyncValidate:
const asyncValidate = (values, dispatch) => {
    // Your fetch request returns Promise object
    return new Promise(resolve => {
        // I use setTimeout just to imitate latency from server
        setTimeout(() => {
            throw { emailNotUnique: 'Email should be unique' }
        }, 300)
    })
}

reduxForm:
export default reduxForm({
    form: 'yourFormName',
    asyncValidate: asyncValidate,
    asyncBlurFields: ['email']
})(YourForm)


Algebra step for Noether theorem

Question: In Tong's preliminaries for QFT, he makes the following step while showing Noether's theorem:
$(\frac{\partial L}{\partial q}\delta q + \frac{\partial L}{\partial \dot q}\delta \dot q) = \left(\frac{\partial L}{\partial q} - \frac{d}{dt}\left(\frac{\partial L}{\partial \dot q} \right)\right)\delta q + \frac{\partial L}{\partial \dot q}\delta q$
How do you get algebraically from the left to the right side there?
Answer: The equality you asked about is wrong, and I will show why. Since $$\frac{\partial L}{\partial \dot{q}}\delta \dot{q} =\frac{\partial L}{\partial\dot{q}}\left ( \frac{d}{dt}\delta q \right )$$ we can write using the product rule: $$\frac{d}{dt}\left ( \frac{\partial L}{\partial \dot{q}}\delta q \right ) = \frac{d}{dt}\left ( \frac{\partial L}{\partial \dot{q}} \right )\delta q+\frac{\partial L}{\partial \dot{q}}\delta \dot{q}$$ and so $$\frac{\partial L}{\partial \dot{q}}\delta \dot{q} = \frac{d}{dt}\left ( \frac{\partial L}{\partial \dot{q}}\delta q \right )-\frac{d}{dt}\left ( \frac{\partial L}{\partial \dot{q}} \right )\delta q$$ and so the equality would be: $$\frac{\partial L}{\partial q}\delta q + \frac{\partial L}{\partial \dot{q}}\delta \dot{q} = \left ( \frac{\partial L}{\partial q} - \frac{d}{dt}\left ( \frac{\partial L}{\partial \dot{q}} \right )\right )\delta q + \frac{d}{dt}\left ( \frac{\partial L}{\partial \dot{q}} \delta q\right )$$ which is the same as your equality, except it has a time derivative on the last term of the RHS. Notice that the first two terms in the RHS vanish by the Euler-Lagrange equation.
Comment: You're right, I misrepresented Tong! And your answer still made me understand the intended reasoning, well done!

Algebra step for Noether theorem


binary representation of integers congruent 1 and 3 modulo 4

Question: Let $k=b_nb_{n-1}\ldots b_3b_2b_1b_0$ be the binary representation of an odd positive integer.
Prove:
If $k\equiv 1 \mod 4$ then $b_1=0$.
If $k\equiv 3 \mod 4$ then $b_1=1$.
I think that to prove the above I need to use $k=1 +4q$ or $k=3 +4q$ for $q\geq 0$. Any suggestions?
Answer: Hint
Think of the binary number $k=b_{n}b_{n-1}...b_{2}b_{1}b_{0}$ as $k=b_{0}(1)+b_{1}(2)+b_{2}(4)+b_{3}(8)+b_{4}(16)+b_{5}(32)+...$
If $b_{0}$ and $b_{1}$ are both equal to zero, then every other term in that sum is divisible by $4$.
Comment: Thanks. But what if $k$ is odd, that is, $b_0=1$?
Answer: Consider the value $k' = b_nb_{n-1}b_{n-2}...b_3b_200$.  This value is divisible by 4 (specifically, it is $4 \times b_nb_{n-1}b_{n-2}...b_3b_2$), and therefore it is equal to zero, modulo 4.
But $k = k' + b_1b_0$
So
$$k \mod 4 = (k' + b_1b_0) \mod 4$$
$$ = ((k' \mod 4) + (b_1b_0 \mod 4)) \mod 4$$
$$ = (0 + b_1b_0) \mod 4$$
$$ = b_1b_0$$
Now since $k$ is odd, $b_0 = 1$, and the only two possibilities for $b_1b_0$ are $01$ and $11$ (that is, 1 and 3).  The result follows immediately.
Answer: Thank you for the suggestion. Here is my proof.
If $k=1 +4q$ for some $q>0$, then
$$bin(k)=bin(1)+bin(4)\cdot bin(q)$$
$$b_n b_{n-1}\ldots b_2b_1b_0=001 +100 \times a_ta_{t-1}\ldots a_2a_1a_0$$
$$b_n b_{n-1}\ldots b_2b_1 1=001 + a_ta_{t-1}\ldots a_2a_1a_0 0 0$$
$$b_n b_{n-1}\ldots b_2b_1 1=001 + a_ta_{t-1}\ldots a_2a_1a_0 0 0$$
$$b_n b_{n-1}\ldots b_2b_1 1= a_ta_{t-1}\ldots a_2a_1a_0 0 1$$
Therefore, $b_1=0$.
Similar proof can be obtained for the case $k\equiv 3 \mod 4$.


What is the difference between events in VB and C#?

Question: I am a VB programmer working my way into C#. I learned how to create and raise events in vb and am finding that it isnt done the same way in C#. Has anybody come across an article that will help me to understand how to do events in C# and maybe explain why it is different in VB.
Thanks
Comment: This question explains the difference between `handles` in VB.Net and C# event syntax http://stackoverflow.com/questions/794332/migrating-handles-from-vb-net-to-c
Answer: Does this help?
VB.NET vs. C# - Delegates / Events
Answer: The main difference is the syntax that's used.  Underneath, they use the exact same mechanisms within the CLR.
However, VB.NET provides special syntax via WithEvents and Handles, allowing you to do:
Dim WithEvents button1 As Button

Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyButton.Click
    ' Handle button click
End Sub

C# doesn't provide an equivelent - all events must be explicitly subscribed to via event +=, which is more like VB.NET's AddHandler statement.
Answer: The difference is mostly syntactic.
See this handy reference about the differences.
The event handler in VB.NET is declared with the Handling key word appended to the event handler signature. In C# you need to use register it with +=.
In VB.NET you invoke the event with RaiseEvent, in C# you call the delegate directly.
Answer: Reading from:
http://msdn.microsoft.com/en-us/library/aa645739(VS.71).aspx

An event in C# is a way for a class to
  provide notifications to clients of
  that class when some interesting thing
  happens to an object. The most
  familiar use for events is in
  graphical user interfaces; typically,
  the classes that represent controls in
  the interface have events that are
  notified when the user does something
  to the control (for example, click a
  button).
Events, however, need not be used only
  for graphical interfaces. Events
  provide a generally useful way for
  objects to signal state changes that
  may be useful to clients of that
  object. Events are an important
  building block for creating classes
  that can be reused in a large number
  of different programs.

Refer to the article for the rest.
Answer: A good quick general reference for some key differences in syntax can be found here.  Search for "events" to get to that section.
Key differences is that VB requires you to use some keywords rather than addition/subtraction to wire up events, but gives you a handles keyword automatically wire a routine to an event.  And when passing a delegate, you must use a pointless AddressOf keyword.  (Sorry for the editorial, but I think that keyword causes more confusion than it saves!)


multiple image list failed to be displayed

Question: I want to display my multiple image list which I uploaded my specific product. but when I using a loop for display, I don't understand why?.here is my code:
Model

//model for multiple images

  public class Photo1
    {
        [Key]
        public int PhotoId { get; set; }
        public string Image { get; set; }
    }

//main model

 public class Shop
    {
        public int Id { get; set; }

        [Required]
        [Display(Name = "product name")]
        public String Name { get; set; }
        [Required]
        public int Price { get; set; }

        public String Image { get; set; }
        public String Image1 { get; set; }

        public List<Photo1> Photos { get; set; }

        [Required]
        public int Quantity { get; set; }

        [Required]
        public bool IsAvailable { get; set; }

        [Display(Name = "Category")]

        public int? CategoryTypeId { get; set; }

        [ForeignKey("CategoryTypeId")]
        public Category Category { get; set; }

        [Display(Name = "SubCategory")]

        public int? SubCategoryTypeId { get; set; }

        [ForeignKey("SubCategoryTypeId")]
        public SubCategory SubCategory { get; set; }
    }

Controller
        [HttpGet]

        public ActionResult Details(int? id)
        {

            if (id == null)
            {
                return NotFound();
            }

            var product = _db.Shop.Include(c => c.Category).Include(c => c.SubCategory).FirstOrDefault(c => c.Id == id);

            if (product == null)
            {
                return NotFound();
            }

            return View(product);
        }

    }

Details.cshtml

@model DigitalShop.Models.Shop

@{
    ViewData["Title"] = "Details";
}

 Product Details

@*

*@
<form method="post" asp-action="" enctype="multipart/form-data">

            @**@

           @if (Model.Photos != null)
            {
                @foreach (var photo in Model.Photos)
                {
                    @if (photo != null)
                    {

                    }
                }
            }

            ×

 @Model.Name

            <input type="hidden" asp-for="Id" />

@Model.Price $

            Clearence

                            <button type="button" class="btn btn-default btn-number btncartsniper" data-type="minus" data-dir="dwn"></button>

                        <input asp-for="@Model.Quantity" class="form-control input-number Snippper_qty" value="0" type="number">

                            <button type="button" class="btn btn-default btn-number btncartsniper" data-type="plus" data-dir="up"></button>

            @*@if (leathers != null)
                {*@
            <button type="submit" class="btn btn-danger form-control" asp-action="Remove" asp-route-id="@Model.Id">Remove To Cart</button>
            @*}*@
            @*else
                {*@
            <input type="submit" value="Add To Cart" class="btn btn-dark form-control" />
            @*}*@

        Back To List

</form>

@section Scripts{

    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");

    }

}

my output is :

but I want to show my all multiple photos of every product. I failed to understand what's the solution to this.
Answer: You should loop through Photos.
That's what the error indicates. It tries to find the enumerator of Shop (Model), while you're intending to loop through photos.
        @if (Model.Photos != null)
        {
            @foreach (var photo in Model.Photos)
            {
                @if (photo.Image != null)
                {

                }
            }
        }

You should also include Photos to the product you're returning, otherwise the list will be null.
Comment: not working. for that, I found a new error    ``` Photo1 does not contain the definition of photos and not accessible extension method" Photos.accepting a first argument type could be found```
Comment: I updated my answer. You also have to change the code inside the loop because you are already in the list.
Comment: I copied your code on my project. but again found a new error ``` An error occurred during the compilation of a resource required to process this request. Please review the following specific error details and modify your source code appropriately. ```
Comment: :) please send a screenshot of the error you see. Also, did you copy the updated answer?
Comment: but I not found the system to send the screenshot to the comment section.
Comment: All Error ```
C:\Users\Hp\Desktop\DigitalShop\DigitalShop\DigitalShop\Areas\Customer\Views\ShopShow\Details.cshtml

Expected a "{" but found a "@". Block statements must be enclosed in "{" and "}". You cannot use single-statement control-flow statements in CSHTML pages. For example, the following is not allowed: @if(isLoggedIn) Hello, @user Instead, wrap the contents of the block in "{}": @if(isLoggedIn) { Hello, @user }
+
                @foreach (var photo in Model.Photos)
 ```
Comment: This error should be fixed with the updated answer. It just implies the rules of nested blocks. Please try again and let me know :)
Comment: I copied your code newly. found no error.but can not found my multiple image list of every product
Comment: Great! :) Now you have to make sure the path to the images is correct.
Comment: I keep my all image Images folder under the www-root folder.you can also see my database. here I also build a path.but why i can't show image
Comment: Firstly, If you are in .net core make sure you have app.UseStaticFiles(); in startup configure. If so, then try to include a hardcoded image to the view just to see if you can pinpoint one image correctly. If you can do that, you just have to compare the paths to find out what's different.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/222478/discussion-between-indrit-kello-and-shane-watson).


Missing some components in SSIS toolbox in Visual Studio 2017

Question: I am using Visual Studio Community 2017 for developing SSIS packages and I use SQL Server 2016.
Some of components are not in SSIS Toolbox.
This is that I have now:

and this is my colleges have(They don't have the same version of Visual Studio that I have):

For example: I need to add a XML Source component to one of my Data Flow but there is not anymore in Other Sources sector in SSIS Toolbox.
I tried to add the missing components (Tools -> Choose Toolbox Items ->) but I don't have the tab for SSIS component.

How can I add those components (For example XML Source) to my Toolbox?
Answer: I have found the cause of this problem.
By changing the TargetServerVersion to SQL Server 2016 in Project properties. My project has been converted and now i have this component in my ToolBox.

Now, I have XML Source component in my SSIS ToolBox.
Comment: This leaves my toolbox completely empty, and unfortunately I cannot figure out exactly what packages/components I am missing here :(
Comment: Are you looking in the SSIS Toolbox? View > Other Windows > SSIS Toolbox @kadrach
Comment: @kadrach honestly I don't know why you have that probleme
Comment: In my case the "containers" was missing but i just had to step in the "control flow" tab an it appeared. No TeargetServer changes required
Answer: I can confirm the answer given by Ardalan Shahgoli resolved my missing component.  I have captured a screenshot demonstrating the problem and the resolution.  In my example, I was missing a component 'Excel Source Plus' from the 'CozyRoc' addin
PROBLEM:
Missing some components.  The data flow has the component on the canvas, but there are of error messages in the Error List window, and you are unable to edit the component.  For example, you might see an error message such as this:

Severity  Code    Description Project File    Line    Suppression State
  Error     Validation error. Alt Data Flow_Merge Data Task: Alt Data
  Flow_Merge Data Task: The component metadata for "Lookup Plus, clsid
  {8DC69D45-2AD5-40C6-AAEC-25722F92D6FC}" could not be upgraded to the
  newer version of the component. The PerformUpgrade method
  failed.       SSASUsageStats.dtsx 0

RESOLUTION:
Changing the TargetServerVersion will effect which components are available in the 'SSIS Toolbox'.  As seen in the screenshot, there are tons more components after changing the project property TargetServerVersion.  For example, 'Excel Source Plus' is found.  The Data Flow canvas now has an image by the icon.  And the component now has an 'EDIT' option.


HTML Select Option tag having differemt colours on same row or same option

Question: There is a new requirement whereby we need to have a different colour for a single select list item i.e on a option row there needs to be 2 different colours.
Sample html code below:
<select name="test">
  <option value = "red blue"> red blue </option>
  <option style="color:blue;" value = "Row2"> Row2 </option>
  <option style="color:green;" value = "Row3"> Row3 </option>
</select>

For example for the first select option, I want to see text "red" in red colour and "blue" in blue colour in the same list item.
Please can someone provide a working example with complete code if possible
Many thanks
Comment: It works fine here https://jsfiddle.net/f8vdnyn8/
Comment:
 red blue
 Row2
 Row3
Comment: So you mean to say you want to split the color values and apply for every term in the option??
Comment: Are you want to implement on dynamic list or static list? Please tell me. #Rthemus
Comment: Hi all thanks for getting back.it is a static list. All I want is as per my sample code the word red to show in red colour and the word blue to show in blue colour.
Answer: In my opinion and experimentation with your code, it might not be possible directly(failed code). But if you want a work around/fix for it, you can use a small external library like purecss(take the menu component of it) and simply write a code like this:
Just an example to give an idea.
HTML:

      select here

red blue

Row2

Row3

Jquery:
$(".pure-menu-children li").each(function(i, opt){
  var colors = $(opt).find(".pure-menu-link").attr("value"); // get the value
  var txt = $(opt).find(".pure-menu-link").text(); // get the text
  var txtarr = txt.trim().split(" "); // split them
  var colorarr = colors.trim().split(" ");
  $(opt).find(".pure-menu-link").html(""); // clear the content of the option
  var len;
  if(txtarr.length >= colorarr.length){
    len = txtarr.length - colorarr.length;
    while(len--){
      colorarr.push("black");
    }
  }
  len = txtarr.length;
  while(len--){
    $(opt).find(".pure-menu-link").append(" "+txtarr.shift()+" ");
  }
});

Working code : https://jsfiddle.net/dkv6q2da/8/ (check the external sources for the menu component of purecss)
Hope it helps.
Comment: Well I updated the code and answer, Now it should do the things its supposed to correctly, i guess
Comment: Thanks dvenkatsagar. Very helpful.
Comment: For I think you would need to add the html5shiv library, or something to make it modern enough. It not a problem with Jquery as far as I know.
Answer: It is very easy you can just name the every option to a class and add the css style to that class as you like.

        This should have a WHITE background
        This should have a RED background
        This should have a YELLOW background
        This should have a GREEN background

Comment: That is not what the OP wants, he wants to see each term in a option with a different color.
Comment: yes dvenkatsagar is right I want  different colours in the same row or within the same option tag. For example if the select option value is a sentence then the 1st word has to be in red and 2nd word in blue and 3rd word in green.  What the user wants is to break up the option value in multiple colours. in a traditional option one can use inline style but that style applies to the entire value not part of the value.
Comment: Are there any more ways to achieve this.@dvenkatsagar has provided a good example. However we have 2 other select options on the same page which look different to the style @dvenkatsagar has provided.Wish it was allowed in the option tag like this     red blue
Comment: Well, a suggest would be to keep the selects a simple unified format/style, other wise you would need to modify code little for each select option. :)
Comment: Thanks @dvenkatsagar. We noticed that the colours do not appear when the browser mode is set to IE10 Internet Explorer 10 Compatibility view.
This is what our PC's default to.
To get the colours of jquery list to show we have to do this
In IE go to Tools --> F12 developer tools --> Go to Browsermode IE10 menu --> Select Interner Explorer 10


Search boxes for individuals content types

Question: I'm trying to have a search facility for different content types on their term pages.
So I have a view that lists all the terms that link through to a page that lists all the nodes that has that term. On this page I want to have a search box which can be used to search any node within it's content type. Now this is fine if I only needed to search one content type, using the Custom Search module I can tell Drupal to only search one content type.
However I need to do exactly the same as above but for a different content type. What would be the best way of implementing this?
Answer: Found an answer in the end if anyone else comes here searching for a solution. Turns out you could do what I wanted with the custom searech module I mentioned in my question. If you go into modules in the admin area there's also a custom search block module that comes with custom search that can be enabled. This gives you the ability to add as many blocks with different confiurations as you please. You then just go into blocks in structure and configure to your hearts content for each block then use those blocks where you want, job done! Just need to work out how to change the template now!


Yield return dentro de um using

Question: Considere a seguinte situação:
public class MeuRecursoBemCaro : IDisposable
    {
        public T FazerOperacaoBemCara(T item)
        {
            //Do operação
        }
        public void Dispose()
        {
            //Dispose logic
        }
    }

public IEnumerable<T> OperarSobreMeusItens(IEnumerable<T> MeusItens)
    {
        using (MeuRecursoBemCaro recurso = new MeuRecursoBemCaro())
        {
            foreach(T item in MeusItens)
            {
                yield return recurso.FazerOperacaoBemCara(item);
            }
        }
    }

Há certeza que meu Dispose() será chamado ou o yield return não vai deixar o using cair na clausula finally que ele cria implicitamente?
Comment: Vai passar sim!, faz assim coloque um breakpoint no `public void Dispose()` e execute normalmente seu código
Answer: Não sei se há alguma outra questão implícita, mas se é só isto, não há problema algum com o yield return. Ele não deixa de ser um return. De uma maneira geral, não há maneira da rotina deixar de passar pelo finally implícito. Se quiser saber sobre os raros casos realmente catastróficos onde o finally não será executado, veja nessa resposta. Mas nada relacionado ao yield return.
Pelo menos nunca vi nada dizendo que isto fosse possível. Pelo contrário, apesar de não ter lido nada neste sentido, tudo que já vi indica claramente que em condições normais não há meio de burlar o finally.
Comment: Fiquei preocupado sobre uma possibilidade de que o Dispose() não fosse chamado para algumas centenas de arquivos em disco devido a uma operação que necessita de um yield return, assim criando um grande problema na minha pequena aplicação. Achei [esta resposta](http://stackoverflow.com/questions/1405877/a-concern-about-yield-return-and-breaking-from-a-foreach) sobre um assunto quase igual ao meu, e respondido diretamente por um dos developers do C#. Sua resposta também foi útil. Valeu.
Answer: Quando se chama um método com yield, o que ele faz é criar um objeto do tipo enumerável.
O foreach cria um IEnumerator<T> através do método GetEnumerator.
Normalmente, quando o método acaba de enumerar todos os elementos, o código nos blocos finally é executado. Um using é equivalente a ter um try... finally com o Dispose no finally.
Mas nem sempre os ciclos são executados até ao fim. Um exemplo disto é quando têm break ou o método Take do LINQ.
O tipo IEnumerator<T> define o método Dispose. Quando o foreach acaba, este método é chamado.
O Dispose de enumeradores de métodos com yield é usado para executar código de blocos finally, que de outra forma não seria executado para ciclos interrompidos.
Naturalmente, caso se use o enumerador manualmente, falte o Dispose e não se iterar até ao fim, o código nos finally/Dispose não é executado.
É também importante notar que os métodos com yield podem devolver o tipo IEnumerable não genérico apesar desta interface não definir o método Dispose.
Nesse caso, o foreach tenta converter o enumerável para IDisposable para chamar o método Dispose na mesma.
Isto é, considere-se a seguinte classe:
    using System;
    using System.Collections;
    using System.Collections.Generic;

class Program
{
    class MyType : IDisposable
    {
        public string Id;

        public void Dispose()
        {
            Console.WriteLine("Disposing MyType " + Id);
        }
    }

    public static IEnumerable<int> X1(string id)
    {
        using (new MyType { Id = id })
        {
            yield return 1;
            yield return 2;
        }
        Console.WriteLine("End {0}", id);
    }

    public static IEnumerable X2(string id)
    {
        using (new MyType { Id = id })
        {
            yield return 1;
            yield return 2;
        }
        Console.WriteLine("End {0}", id);
    }

    static void Main(string[] args)
    {
        foreach (var i in X1("Generic loop")){ }
        foreach (var i in X1("Interrupted generic loop"))
        {
            break;
        }
        X1("Manual generic dispose").GetEnumerator().Dispose();
        X1("No Enumerator generic dispose").GetEnumerator();
        foreach (var i in X2("Old-style loop")) { }
        foreach (var i in X2("Interrupted old-style loop"))
        {
            break;
        }
        X2("No Enumerator old-style dispose").GetEnumerator();
        Console.ReadLine();
    }
}

O output deste programa é:
Disposing MyType Generic loop
End Generic loop
Disposing MyType Interrupted generic loop
Disposing MyType Old-style loop
End Old-style loop
Disposing MyType Interrupted old-style loop

O código compilado do Main é equivalente a (código obtido com o ILSpy):
// Program
private static void Main(string[] args)
{
    foreach (int i in Program.X1("Generic loop"))
    {
    }
    using (IEnumerator<int> enumerator2 = Program.X1("Interrupted generic loop").GetEnumerator())
    {
        if (enumerator2.MoveNext())
        {
            int j = enumerator2.Current;
        }
    }
    Program.X1("Manual generic dispose").GetEnumerator().Dispose();
    Program.X1("No Enumerator generic dispose").GetEnumerator();
    foreach (object k in Program.X2("Old-style loop"))
    {
    }
    IEnumerator enumerator4 = Program.X2("Interrupted old-style loop").GetEnumerator();
    try
    {
        if (enumerator4.MoveNext())
        {
            object l = enumerator4.Current;
        }
    }
    finally
    {
        IDisposable disposable = enumerator4 as IDisposable;
        if (disposable != null)
        {
            disposable.Dispose();
        }
    }
    Program.X2("No Enumerator old-style dispose").GetEnumerator();
    Console.ReadLine();
}

Comment: Marquei a sua resposta como answer pelo exemplo e pela explicação. Thanks.

Yield return dentro de um using


get the vid of last saved vocabulary

Question: How can I get the last saved vid. taxonomy_vocabulary_save($vocabulary); is not returning the vid.
I have used the following way.
$vocabulary = new stdClass();
$vocabulary->name = 'Currencies';
$vocabulary->machine_name = 'currencies';
taxonomy_vocabulary_save($vocabulary);
// get the vid of currency
$vocabulary = taxonomy_vocabulary_machine_name_load('currencies');
//save a variable for vid
variable_set('currencies_vid', $vocabulary->vid);

Is there any better method?
Answer: The vocabulary object that you pass to taxonomy_vocabulary_save() will automatically be populated with the new vid, so you don't need to reload the vocabulary after you've saved it.
This code will work fine:
$vocabulary = new stdClass();
$vocabulary->name = 'Currencies';
$vocabulary->machine_name = 'currencies';
taxonomy_vocabulary_save($vocabulary);

variable_set('currencies_vid', $vocabulary->vid);

get the vid of last saved vocabulary


Adjusting data for missing observations

Question: I have an unbalanced panel data set of 40 cities and 20 years.  It is unbalanced because the data are not collected for certain cities for every year.  The data are then balanced after these 20 years.
Suppose the time periods are 1960 to 1979 and then 1980 to 1999.  I want to compare the data for 1979 with the data from 1980, but this is somewhat difficult to do because the 1979 data have some missing observations.
How do I do this?  Should I predict what the 1960 to 1979 data would have been had the data been balanced using the unbalanced data?  Then forecasting the data would make the 1979 data balanced so that I can compare the 1979 data with 1980.
My concern is that predicting the data for 1979 using the 1960-1979 data may cause the series to inherently not be continuous with the 1980 data.
Comment: Have you tried Expectation Maximization for parameter estimation? http://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm
Comment: Try [this review](http://sites.stat.psu.edu/~jls/aaps_schafer.pdf), and the references therein. Multiple imputation (of some form) is a standard method.
Answer: Multiple imputation is an important and common practice. Assuming your data are normally distributed and missing more or less at random, I would recommend you impute the missing values.
A good package that I use quite frequently is Amelia for R. http://gking.harvard.edu/amelia/ The package uses various probabilistic methods to impute the missing values, and provides pretty good diagnostic tools as well.
Answer: As @gmacfarlane suggests, you should probably use multiple imputation.
However, it's not necessary that anything be normally distributed.  Most good software, including the Amelia package will impute other kinds of data as necessary.  Indeed one of the nice things about Amelia is that it can also take into account the fact that your data is a time series.
For multiple imputation to work your data should be 'missing completely at random' (MCAR) or 'missing at random' (MAR) which are (very regrettably) technical terms in this field.  See other questions on this site for a definition of MCAR and MAR.  Alternatively slides 14-19 of @guest's link provide some more details.
Specific to your question: you should use anything that might be informative to impute your missing data.  Specifically that includes the complete data you have from 1980 and later.  (Counterintuitively, it also includes any dependent variable values you might be working with.)  Using all the information you have to impute will ensure you are not actively introducing any discontinuities.  The only constraint is that you should ideally not have a final analysis model with variables not available to the imputation model; that really might cause artifactual discontinuities.
After you've imputed your half dozen completed data sets, you run the analysis you originally wanted to do on each imputed dataset and combine the results.  The multiple imputation FAQ discusses how to do this, and also the issues above.
Comment: This is a nice paper on MI using chained equations http://onlinelibrary.wiley.com/doi/10.1002/sim.4067/abstract

Adjusting data for missing observations


slideToggle(); para linha em tabelas

Question: $(document).ready(function(){
    $("#flip").click(function(){
        $("#panel").slideToggle("slow");
    });
});

Maria

1.000

José

2.000

Seguindo o código acima, eu preciso clicar em Maria e aparecer o valor abaixo (1.000), e o mesmo com José. Está funcionando perfeitamente quando clica em Maria, mas não para José. Como soluciono este problema?
Comment: Você está utilizando `id` que é um identificador único e somente o primeiro elemento encontrado no documento é selecionado, tente mudar para classe, exemplo `` e `$('.flip')` relacionada https://pt.stackoverflow.com/questions/39875/qual-a-prioridade-do-html-id-ou-class/39879#39879
Comment: A diferença é que o meu original, ele oculta o linha debaixo e só quando clicada, ela aparece, e a sua edição faz ao contrário.
Comment: Veja a resposta, se é isso que pretende, veja que adicionei um `$(this).next('.panel')` para selecionar o próximo elemento, ou seja o
Answer: Você está utilizando id que é um identificador único e somente o primeiro elemento encontrado no documento é selecionado, tente mudar para classe, exemplo:

$(document).ready(function(){
    $(".flip").click(function(){
        $(this).next(".panel").slideToggle("slow");
    });
});
.flip{
  background-color:red;
  cursor:pointer;
}
.panel{
  background-color:blue;
  display:none;
}

Maria

1.000

José

2.000

Comment: PERFEITO. Funcionou. Eu gostaria de saber, como deixar a linha com os números ocultas quando carrega a pagina e só apareça se clicado. O caminho inverso da tua alteração. Tem como?
Comment: 100% AGORA. muito obrigado.
Comment: @RafaelBrito tem sim, basta adicionar a propriedade `display:none` na classe `.panel` do CSS.

slideToggle(); para linha em tabelas


A classic exponential inequality: $x^y+y^x>1$

Question: This is a classic problem, but I haven't seen it on the site before.

Suppose $x$ and $y$ are real numbers that both lie in the interval
  $(0,1)$. Prove  $$x^y+y^x>1.$$

The following spoiler box contains a hint that indicates the solution I know. Does anyone know a more natural solution?

 Use Bernoulli's inequality to show $$x^y\ge \frac{x}{x+y}.$$

Edit: I recently learned the source is the 1996 French math olympiad.
Comment: Sorry, was wrong. The good thing is, I didn't notice it before it got three upvotes, so it earned me a badge.
Comment: in fact, we have $x^y+y^x\ge 1+\min{\{x,y\}}$
Comment: @math110 Do you have a proof?
Comment: I don't understand why this question is closed as duplicate of a poorer Please-Solve-Question (which hence can't be deleted)?
Comment: @math110 when $x=y=1/2$, $x^y+y^x=\sqrt{2}<1+1/2=1+\min\{x,y\}$.
Answer: Well, let me point out a natural way to "guess" an auxiliary inequality you mentioned above. So we want to prove that
$$x^y+y^x>1.$$
As in most problems of such type the the first idea to try is some convexity.
It is highly unlikely that direct Jensen's would work so we want to think about weighted one, namely
$$m_1f(x_1)+m_2f(x_2)\ge (m_1+m_2)f\left(\frac{m_1x_1+m_2x_2}{m_1+m_2}\right).$$
The simplest way to "create weights" is to separate $x$ and $y,$ in other words we rewrite out inequality in the form
$$x^y+y^x=x\cdot \frac{1}{x^{1-y}}+y\cdot \frac{1}{y^{1-x}},$$
and this is also a natural way to rewrite it since we like positive powers $1-x$ and $1-y$ more than negative one. Now it is time to apply Jensen's and the simplest function one can think of is $f(t)=\frac{1}{t}.$ This leads to the inequality
$$x^y+y^x\ge (x+y)f\left(\frac{x^{2-y}+y^{2-x}}{x+y}\right)=\frac{(x+y)^2}{x^{2-y}+y^{2-x}}.$$
Now we want to show that $(x+y)^2=x^2+xy+xy+y^2>x^{2-y}+y^{2-x}.$ So we would like to show that $x^2+xy\ge x^{2-y}$ and $y^2+xy\ge y^{2-x}.$ But the first inequality after cancelation reduces to
$$x+y\ge x^{1-y},$$ or
$$x^y\ge \frac{x}{x+y}.$$
Comment: I'm not sure if I would call this natural, but I am quite bad with inequalities. Do you know of any other inequalities that can be solved with this weighted convexity method? (Feel free to post them as separate questions if the solution is too lengthly to explain here.)
Comment: I greatly appreciate this insight, though.


Unable to scroll long modal after stack another modal

Question: I have to modal, modal 1 is long and it open first, I can easily scroll through the page when it appear, Modal 2 is short but when I stack open modal 2 (Open modal 2 when modal 1 still open) and then close modal 2: Modal 1 can no longer scroll. I've tried to hide model 1 then show it again when modal 2 is hide but it not help
<code>$('#modal2').on('hide.bs.modal', function () {
   $("#modal1").modal('show');
});
</code>
Answer: OK, after digging, I found a hack, posting here so anyone have the same problem can work around.
<code>            $('body').on('hidden.bs.modal', function (e) {
                if($('.modal').hasClass('in')) {
                    $('body').addClass('modal-open');
                }
            });
</code>
Comment: One note - there is no need to modify the code above with your specific modal's ID# - just run it as is.
Comment: Thank @SteveFrench for clarify. Yes, this code is for general case.
Answer: The simple answer is that Bootstrap does not support overlapping modals. From their documentation, the first warning says;

Overlapping modals not supported
Be sure not to open a modal while
  another is still visible. Showing more than one modal at a time
  requires custom code.

More than likely this is one of the reasons why they don't recommend it. I wouldn't personally recommend stacking modals without very good reason, there are probably better ways to do what you want to do, for example, you could simply programatically close the first modal before you open the second, you could change the content of your first modal dynamically, you could use tabs within your modal etc.
It looks like you say you've already closing your first modal before opening the second. Maybe you can expand on that point instead since it's apparent that Bootstrap doesn't support or recommend stacking modals out of the box.
Answer: The hack from @Thinh Hoang Nhu wasn't working for me, but he was on the right track. If anybody stumbles across this same problem, my solution was to add a class to the 2nd modals(the ones I know I open after opening first another modal) and added this function with a small delay.
<code>$('body').on('hide.bs.modal', '.modal2nd', function () {
    setTimeout(function(){
        $('body').addClass('modal-open');
    }, 500);
});
</code>
This worked for me.


Determining if a language is Recursively Enumerable

Question: Here is a problem from John Hopcroft's "Introduction to Automata Theory" that I'm having a hard time trying to understand.

Exercise 9.2.5:
  Let L be recursively enumerable and let Overscript[L, _] be non-RE. Consider the > language:
L' = {0w | w is in L}  $\cup$  { 1w | w is not in L }
Can you say for certain whether L'  or its complement are recursive, RE, or non-> RE?  Justify your answer:

Here is the oficial answer:

"Note that the new language defined in the displayed text should be L'; it is > > different from the given language L, of course. Also, we'll use -L for the > > complement of L in what follows.
  Suppose L' were RE. Then we could design a TM M for -L as follows. Given input w, M changes its input to 1w and simulates the hypothetical TM for L'. If that TM > accepts, then w is in -L, so M should accept. If the TM for L' never accepts, > then neither does M. Thus, M would accept exactly -L, which contradicts the fact > that -L is not RE. We conclude that L' is not RE."

and here is what I don't get:
..."Thus, M would accept exactly -L, which contradicts the fact that -L is not RE"....
Why? M is the Turing Machine for -L, so it is supposed to accept -L, right?
If we can construct a Turing Machine for a language, then it is RE. We have constructed a TM for something we know is not RE (-L), based on the TM for the  supposedly RE L'.  So what? how does this leads to the conclusion that L' is not RE?   I'm very confused...
Any help will be much appreciated
Thanks!
Comment: It was assumed that the complement of $L$ is not r.e.
Answer: The hypothesis of the exercise is that $L$ is RE and $-L$ is not RE. The argument is that if $L'$ were RE, then $-L$ would also be RE, contradicting this hypothesis.
Answer: I use the term c.e. for r.e. and computable for recursive.
$L'$ is not c.e. If $L'$ was c.e., then you can enumerate computably all the elements of $L'$. From this computable enumeration of $L'$, you can make an enumeration of $\overline{L}$ as follows: in the enumeration of $L'$, if you see a string enumerated that starts with $1$ of the form $1w$, then put $w$ into the enumeration of $\overline{L}$. This gives an enumeration of $\overline{L}$, so $\overline{L}$ is c.e. Contradicting the assumption. Since $L'$ is not c.e., it can not be computable.
Note that $-L' = \{0w : w \notin L\} \cup \{1w : w \in L\}$. Apply the same argument to $-L'$ to conclude it is not c.e.