Incorrectly solving the determinant of a matrix

Question: Compute $det(B^4)$, where $B =
    \begin{bmatrix}
     1       & 0 & 1 \\
     1       & 1 & 2 \\
     1       & 2 & 1
    \end{bmatrix}
$
I created
$C=\begin{bmatrix}
     1       & 2 \\
     1       & 1 \\
    \end{bmatrix}
$ and
$
 D= \begin{bmatrix}
     1       & 1 \\
     1       & 2 \\
    \end{bmatrix}
$
$det(B) = -det(C) -2det(D) = -(1-2) - 2(2-1) = -(-1)-2(1)=1-2=1, 1^4=1$
However, the correct answer is 16. I'm confused on where I made my wrong turn
Comment: $ det(AB)=det(A)det(B)$
Comment: Actually, if the OP is expanding by the second column, as suggested by the $-2\det{D}$ term, then  $C = \begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}$
Comment: It looks like you're expanding by the second column. Then $C$ is incorrect and anyway it should be $\det{B} = \det{C} - 2\det{D}$.
Comment: $C=\left[
\begin{array}{cc}
1 & 2 \\
2 & 1 \\
\end{array}
\right]
$
Answer: You have calculated det$(B) $ wrong - you just got the order of signs mixed up, when calculating the determinant by expanding into $ 2 \times 2 $ matrices.
It is det $(B) =  1 \begin{vmatrix} 1 & 2 \\ 2 & 1 \\ \end{vmatrix}  - 0 \begin{vmatrix} 1 & 2 \\ 1 & 1 \\ \end{vmatrix} + 1 \begin{vmatrix} 1 & 1 \\ 1 & 2 \\  \end{vmatrix} $.
Hence det$(B) = 1 ( 1 - 4 ) - 0(1- 2 )  + 1 ( 2-1 )   = -3 + 1 = -2 $.
And it seems you used the formula det$(A^n) =  ($det$(A)) ^ n $ which is correct and hence det$(B^4) = ($det$(B))^4 = ( -2 )^4 = 16 . $
Answer: Why did you do that? Just use determinant along the first row. This way is easier because there is a 0 in that row.
$$
        \begin{vmatrix}
        1 & 0 & 1 \\
        1 & 1 & 2 \\
        1 & 2 & 1 \\
        \end{vmatrix}=1\begin{vmatrix}
        1 & 2 \\
        2 & 1 \\
        \end{vmatrix}-0\begin{vmatrix}
        1 & 2 \\
        1 & 1 \\
        \end{vmatrix}+1\begin{vmatrix}
        1 & 1 \\
        1 & 2 \\
        \end{vmatrix}=(1*1-2*2)+(1*2-1*1)=\\
-3+1=-2
$$
and $(-2)^4=16$
Answer: We have
$$
\det(B) = 1 \times \det(E) + 1 \times \det(D) = (1 - 4) + (2 - 1) = -2
$$
where $ E $ is
$$
\begin{bmatrix}
1 & 2 \\ 2 & 1
\end{bmatrix}
$$
Then
$$
\det(B^4) = \det(B)^4 = (-2)^4 = 16
$$
Answer: Use row reduction to calculate the determinant:
\begin{align}
\begin{vmatrix}1&0&1\\1&1&2\\1&2&1\end{vmatrix}=\begin{vmatrix}1&0&1\\0&1&1\\0&2&0\end{vmatrix}=\begin{vmatrix}1&0&1\\0&1&1\\0&0&-2\end{vmatrix}
\end{align}
hence $\;\det B=1\cdot1\cdot(-2)=-2$, so $\;\det B^4=(\det B)^4=16$.


Roll dice and ignore worst results

Question: I am at my wits' end with my very basic statistics knowledge.
I roll $n$ dice with $k$ sides each (numbered $1$ thru $k$, laplace).
I then add the numbers of the $m$ best dice (the higher the roll the better).
This sum is the result.
What is the Expected Value of the result? (And how did you obtain it?)
What is the probability of getting the exact result of $x$ ($m \le x \le mk$)?
As you might have guessed, this question is about AD&D, and I got curious about the maths behind it.
EDIT:
I think I found a partial solution, but this raises more questions. Please to check to see my answer.
Comment: $n=4,k=6,m=3$ can be computed pretty easily by computer. I doubt there is a good general formula, but that's just a suspicion.
Comment: For $n=2$, $k=6$, and $m=1$, the result is known to be $4$. [cf. here](http://math.stackexchange.com/questions/223238/what-is-the-average-of-rolling-two-dice-and-only-taking-the-value-of-the-higher).
Comment: Thank you, George. Most interesting for me is the special case of $n=4,k=6,m=3$, but I am also curious about a general solution.
Answer: Answer:
The expected value for $n$ dice with $f$ faces, removing ("dropping") the $m$ lowest ones is:
$$
E(n,f,m)=\left(\frac{n+(n\cdot f)} {2}-m\right)-\frac{\displaystyle\sum_{d=1+n-m}^n(d-(n-m))\cdot\binom{n}{d}\cdot\left(\sum_{p=1}^{f-1}p^{n-d}\cdot (f-p)^d\right)}{f^n}
$$
Note: The original question was for keeping $m$ highest dice, not removing $m$ lowest ones. For keeping the highest $m$, just put $n-m$ for $m$ into the formula.

Explanation:
Consider 2 3-sided dice ($n=2, f=3$):
$$
\begin{array}{c|ccc}
\text{Sum} & 1 & 2 & 3 \\ \hline
1 & 2 & 3 & 4 \\
2 & 3 & 4 & 5 \\
3 & 4 & 5 & 6 \\
\end{array}$$
$$\text{Average value: } (2+6)/2=4 \\
\text{Elements: }3^2 \\
\text{Sum of all Elements: }4\cdot 3^2=36$$
This approach reduces the $\text{Sum}$:
First, make it a tree. Consider it to start at $(0,0)$ and reach $(1,1)$ with a diagonal arrow. It allows you to treat the first element the same as the others, which makes this approach cleaner.
$$\begin{array}{ccccc}
2 & \rightarrow & 3 & \rightarrow & 4 \\
\downarrow & \searrow & & &  \\
3 & & 4 & \rightarrow & 5 \\
\downarrow & & \downarrow & \searrow &  \\
4 & & 5 & & 6 \\
\end{array}$$
Every arrow here represents a 'step' that increases the value by the dimension of the arrow (1D or 2D). It's the same as picking up the highest $1$ or $2$ dice from whatever you rolled, increase their value by one, and put them back on the table.
If you remove one (the lowest) die, the $2$D dimension will "collapse" into $1$D (because you will only have one die left). Explained by the dice: Going from $(1,1)$ to $(2,2)$ is $2$ more, but after removing $1$ die, it's still just $(1)$ to $(2)$ (which is exactly a $1$D step, doing $+1$).
So, we'll reduce every value that's attached to a diagonal arrow by $1$. This includes $(1,1)$, because we consider it to be attached to $(0,0)$. Therefore, we have to decrease $(1,1)$, $(2,2)$ and $(3,3)$ by $1$ each.
Decreasing $(1,1)$ affects $9$ values (the entire tree), $(2,2)$ affects $4$, $(3,3)$ affects just itself.
The total decrease to be substracted from the $\text{Sum}$ is the following:
$$\left( \begin{array}{ccc}
1 & 1 & 1 \\
1 & 1 & 1\\
1 & 1 & 1\\
\end{array}\right) +
\left( \begin{array}{ccc}
0 & 0 & 0 \\
0 & 1 & 1\\
0 & 1 & 1\\
\end{array}\right) +
\left( \begin{array}{ccc}
0 & 0 & 0 \\
0 & 0 & 0\\
0 & 0 & 1\\
\end{array}\right)=3^2 + 2^2 + 1^2=14$$
And you end up with this tree:
$$\begin{array}{ccccc}
1 & \rightarrow & 2 & \rightarrow & 3 \\
\downarrow & \searrow & & &  \\
2 & & 2 & \rightarrow & 3 \\
\downarrow & & \downarrow & \searrow &  \\
3 & & 3 & & 3 \\
\end{array}$$
It gives $3$ for every combination of dice that contains a $3$, which is what we expect if we take away the lower die from that combination. Same for the lower values.
The maths look like this:
$$\text{Substracting the matrices above from the Sum: } 36-(3^2+2^2+1^2)=22 \\
\text{Expected value: Corrected Sum}/\text{Elements in Sum table}=22/9=2.444$$

What if you remove both dice? That should result in a $\text{Sum}$ of $0$, of course. Let's see.
The same logic as above applies. Now both dimensions collapse to $0$D. Every arrow/step does a $+0$.
Generally, all dimensions/steps decrease by $dimension - (dices - m)$. If you have $37$ dice and remove $17$, the $33$th dimension will decrease by $33 - (37 - 17)=13$. This ties a decrease to every dimension, based on $m$.
We only consider the dimensions where that is a positive value: $dimension - (dices - m) > 0$.
Above, the 2D step decreased by $2 - (2 - 1)=1$. We used this knowledge to correct the $\text{Sum}$ by $14$. This was done by counting the $2$D arrows - $3$ - and applying the decrease to every element that depended on the value the arrow pointed to.
For $m=2$, both dimensions become $0$D. We now need to take the $1$D dimension into account, as well.
This problem now becomes an arrow-counting problem. How many arrows are there and how much do they affect?
$$
\begin{array}{ccccc}
2 & \color{red}{\rightarrow} & 3 & \color{blue}{\rightarrow} & 4 \\
\color{red}{\downarrow} & \color{green}{\searrow} & & &  \\
3 & & 4 & \color{blue}{\rightarrow} & 5 \\
\color{blue}{\downarrow} & & \color{blue}{\downarrow} & \color{orange}{\searrow} &  \\
4 & & 5 & & 6 \\
\end{array}
\implies
\begin{array}{c|ccc}
\text{Matrix Size} & 1 & 2 & 3\\ \hline
\text{Dimension 1} & \color{blue}{4} & \color{red}{2} & 0\\
\text{Dimension 2} & \color{orange}{1} & \color{green}{1} & 1
\end{array}$$
This means that there is $1$ arrow affecting a matrix of dimension $2$ and side length $3$. That's the one from $(0,0)$ to $(1,1)$, of course.
It affects the entire tree and therefore will reduce the $\text{Sum}$ by $2 \cdot 3^2$ (the $2$ is the decrease for that dimension). There are two $1$D arrows that affect $2$ values each: The ones from $(1,1)$ to $(1,2)$ and to $(2,1)$. The remaining $4$ $1$D arrows affect just one value each.
So what you now substract from the $\text{Sum}$ is this:
$$\begin{align}
& 1 \cdot (4 \cdot 1^1 + 2 \cdot 2^1) + \\
& 2 \cdot (1 \cdot 1^2 + 1 \cdot 2^2 + 1 \cdot 3^2) = 36\end{align}$$
which sums up to $36$, great. That means from the $\text{Sum}$ above, we remove all $36$, giving us a $0/9 = 0$, which is what we expected.
In an $n$-dimensional tree, the arrow counts get pretty big pretty fast. Here's an example of 4d6:
dimension 1:
500 256 108 32 4 0
dimension 2:
150 96 54 24 6 0
dimension 3:
20 16 12 8 4 0
dimension 4:
1 1 1 1 1 1

The values increase like so (right to left):
$$\binom{dices}{dimension}\cdot step^{dices - dimension}$$
Where $step$ is zero-based, but starts at $1$. In other words, we'll skip the first step, which is $0$ for every dimension except the highest, and then give that highest dimension matrix a separate treatment.
Every such step decreases the total of the $\text{Sum}$ by
$decrease\cdot(faces-step)^{dimension}$.
Lastly, to account for the $0$th index of the highest dimension, we can circle back to the very beginning and decrease the value of all elements in the $\text{Sum}$ table by m.
Putting it all together, you end up with:
$$
E(n,f,m)=\left(\frac{n+(n\cdot f)} {2}-m\right)-\frac{\displaystyle\sum_{d=1+n-m}^n(d-(n-m))\cdot\binom{n}{d}\cdot\left(\sum_{p=1}^{f-1}p^{n-d}\cdot (f-p)^d\right)}{f^n}
$$
where $d$ denotes the dimension and $p$ the step. $p$ only goes to $f-1$, because the indices are zero-based. The decrease and the $\binom{n}{d}$ have been factored out. $m$ is the amount of the lowest dice you remove. So if $m = n$, the result will be $0$. If you want to use this with the amount of the highest dice you want to keep, then just put $n-m$ instead of $m$ into this formula.

Special cases:
In the case of $m=1$, which means 'roll $n$ dice, take away the lowest one', this collapses to:
$$
\begin{align}
E(n,f,1)&=\left(\frac{n+(n\cdot f)} {2}-1\right)-\frac{\sum_{d=1+n-1}^n(d-(n-1))\cdot\binom{n}{d}\cdot\left(\sum_{p=1}^{f-1}p^{n-d}\cdot (f-p)^d\right)}{f^n}\\
&=\left(\frac{n+(n\cdot f)} {2}-1\right)-\frac{(n-(n-1))\cdot\binom{n}{n}\cdot\left(\sum_{p=1}^{f-1}p^{n-n}\cdot (f-p)^n\right)}{f^n}\\
&=\left(\frac{n+(n\cdot f)} {2}-1\right)-\frac{\sum_{p=1}^{f-1}(f-p)^n}{f^n}\\
&=\left(\frac{(f+1)\cdot n} {2}-\frac{f^n}{f^n}\right)-\frac{\sum_{p=1}^{f-1}p^n}{f^n}\\
&=\frac{(f+1)\cdot n} {2}-\left(\frac{\sum_{p=1}^{f-1}p^n}{f^n}+\frac{f^n}{f^n}\right)\\
&=\frac{(f+1)\cdot n} {2}-\frac{\sum_{p=1}^{f}p^n}{f^n}\\
&=\frac{(f+1)\cdot n} {2}-\frac{H_{f}^{(-n)}}{f^n}
\end{align}
$$
where $H$ is the generalized harmonic number. In the further case of $n=2, m=1$, which means 'roll two dice, take the higher one/roll two dice, remove the lower one/roll with advantage', we get:
$$
E(2,f,1)=\frac{(f+1)\cdot 2} {2}-\frac{H_{f}^{(-2)}}{f^2}
=f+1-\frac{\frac{f^3}{3}+\frac{f^2}{2}+\frac{f}{6}}{f^2}
=\frac{(4f-1)(f+1)}{6f}
$$
which, divided by $f$, approaches $\frac{2}{3}$ as $f\to\infty$, giving the somewhat well-known result that rolling with advantage is, on average, approximately $\frac{2}{3}$ times highest face on the die.
Finally, for $n=2, f=3, m=1$, as above:
$$
E(2, 3, 1)=\frac{(4\cdot3 -1)(3+1)}{6\cdot3}=\frac{11\cdot4}{18}=\frac{22}{9}=2.444
$$
Some examples:
$E(2,6,1) = 161 / 36 = 4.47222$
$E(2,20,1)=5530/400=13.825$
$E(4,6,1)=15869/1296=12.2446$
$E(4,6,3)=6797 / 1296 = 5.2446$
$E(33,22,11)=410237042226924051890969990312773679921645 / 1238753918671327566481737454139790589952 = 331.169$
Answer: This is only the case $n=4,k=6,m=3$:
 X    Count     Probability
 3        1     0.0008
 4        4     0.0031
 5       10     0.0077
 6       21     0.0162
 7       38     0.0293
 8       62     0.0478
 9       91     0.0702
10      122     0.0941
11      148     0.1142
12      167     0.1289
13      172     0.1327
14      160     0.1235
15      131     0.1011
16       94     0.0725
17       54     0.0417
18       21     0.0162

Simple Perl program.
Comment: Thank you. Is there also a closed expression for $E(n,k,m)$ or $P(n,k,m,x)$ without the need of actually summing up all the possible combinations?
Answer: $\def\eqdef{\stackrel{\text{def}}{=}}$
The  $\ S\ $ you're interested in is that of the last $\ m\ $ order statistics of the values shown on the dice's faces.  The order statistics are those values $\ V_1\le$$\,V_2\le\dots\le V_n\ $ arranged in increasing order, and so
$$
S=\sum_{t=1}^mV_{n+1-t}\ ,
$$
or, putting $\ B_t\eqdef V_{n+1-t}\ $,
$$
S=\sum_{t=1}^mB_t\ .
$$
The expectation $\ E(n,k,m)\eqdef\Bbb{E}(S)\ $ can be evaluated using the linearity of expectation:
\begin{align}
\Bbb{E}(S)&=\sum_{t=1}^m\Bbb{E}\big(B_t\big)\\ &=\sum_{t=1}^m\sum_{r=1}^kr\,\Bbb{P}\big(B_t=r\big)\tag{1}\label{exp1}
\end{align}
and the probability mass functions $\ \Bbb{P}\big(B_t=r\big)\ $ of the random variables $\ B_t\ $.
In a separate section below, I derive an expression for the probability mass functions of $\ B_t\ $ and provide a Magma script for evaluating $\ E(n,k,m)\ $ using the expression \eqref{exp1}.
Since the order statistics aren't independent, it's not possible to obtain the probability mass function $\ P(n,k,m,x)\eqdef$$\,\Bbb{P}(S=x)\ $ of $\ S\ $ by convolving those of $\ B_m,$$\,B_{m-1},$$\,\dots,B_1\ $.  It is possible, however, to express $\ P(n,k,m,x)\ $ in terms of the joint probability mass function of $\ B_m,B_{m-1},\dots,B_1\ $.  While there's no simple closed form expression for it, it can nevertheless be expressed as a sum of products of powers, binomial coefficients and restricted composition numbers. The work necessary to evaluate this sum is a polynomial function of $\ n\ $ and so, when $\ n\ $ is large, it requires much less work than that needed to exhaust over all possible combinations, which grows exponentially with $\ n\ $.
The expression for $\ P(n,k,m,x)\ $ is
$$
\sum_{a=1}^{m-1}{n\choose a}\sum_{r=\max\left(1,\left\lceil\frac{x-ka}{m-a}\right\rceil\right)}^{\min\left(k,\left\lfloor\frac{x-a}{m-a}\right\rfloor\right)}p_{x-(m-a)r,a,r+1,k}\ \ \sum_{b=m-a}^{n-a}{n-a\choose b}\left(\frac{1}{k}\right)^{a+b}\left(\frac{r-1}{k}\right)^{n-a-b}
$$
if $\ x\ $ is not evenly divisible by $\ m\ $, where $\ p_{z,a,\ell,u}\ $ is the number of restricted compositions of length $\ a\ $ of the number $\ z\ $ into parts of sizes between $\ \ell\ $ and $\ u\ $ (inclusive), or
\begin{align}
\sum_{b=m}^n&{n\choose b}\left(\frac{1}{k}\right)^b\left(\frac{x-m}{mk}\right)^{n-b}+\\
&\sum_{a=1}^{m-1}{n\choose a}\sum_{r=\max\left(1,\left\lceil\frac{x-ka}{m-a}\right\rceil\right)}^{\min\left(k,\left\lfloor\frac{x-a}{m-a}\right\rfloor\right)}p_{x-(m-a)r,a,r+1,k}\ \ \sum_{b=m-a}^{n-a}{n-a\choose b}\left(\frac{1}{k}\right)^{a+b}\left(\frac{r-1}{k}\right)^{n-a-b}
\end{align}
if $\ x\ $ is evenly divisible by $\ m\ $.
The following Magma script evaluates $\ P(n,k,m,x)\ $ using the above expressions. You can run it by copying and pasting it into the online Magma calculator.  For $\ n=4,k=6,m=3\ $ it agrees with the results obtained by Thomas Andrews in his answer.   It also contains code to evaluate $\ E(n,k,m)\ $ using the definition
$$
E(n,k,m)=\sum_{x=m}^{km}xP(n,k,m,x)
$$
and obtains the same values for $\ E(n,k,m)$ Thomas B. does with the method he describes in his answer, except for the case $\ n=33, k=22\ $. When $\ n\ $ and $\ k\ $ are both that large, the computation of the restricted composition numbers $\ p\ $ exceeds the time limit imposed by the online Magma calculator.
restcomp:=function(x,n,l,u)
   rcold:=ZeroMatrix(Integers(),1,Min(x,u*(n-1)));
   rcnew:=ZeroMatrix(Integers(),1,Min(x,u*(n-1)));
   if (x lt n*l) or (x gt n*u) then
      return(0);
   end if;
   if n eq 1 then
       return(1);
   else
       for xi in [l..Min(x,u)] do
         rcold[1,xi]:=1;
       end for;
       for ni in [2..n-1] do
          for xi in [ni*l..Min(x,ni*u)] do
             for v in [Max(l,xi-(ni-1)*u)..Min(xi-1,u)] do
                rcnew[1,xi]:=rcnew[1,xi]+rcold[1,xi-v];
             end for;
          end for;
          rcold:=rcnew;
          rcnew:=ZeroMatrix(Integers(),1,Min(x,u*(n-1)));
       end for;
       tot:=0;
       for v in [Max(l,x-(n-1)*u)..Min(x-1,u)] do
          tot:=tot+rcold[1,x-v];
       end for;
       return(tot);
   end if;
end function;
P:=function(n,k,m,x)
   pr:=0;
   for a in [1..m-1] do
     g1:=Max(1,Ceiling(Rationals()!(x-k*a)/Rationals()!(m-a)));
     g2:=Min(k,Floor(Rationals()!(x-a)/Rationals()!(m-a)));
     sc:=0;
     for r in [g1..g2] do
         s:=0;
         for b in [m-a..n-a] do
            s:=s+Binomial(n-a,b)*Binomial(n,a)*(r-1)^(n-a-b)/k^n;
         end for;
         sc:=sc+s*restcomp(x-(m-a)*r,a,r+1,k);
     end for;
     pr:=pr+sc;
   end for;
   if IsDivisibleBy(x, m) then
      for  b in [m..n] do
          pr := pr+Binomial(n,b)*(x-m)^(n-b)/(m^(n-b)*k^n);
      end for;
   end if;
   return( pr );
 end function;

 E:= function(n,k,m)
    expv:=0;
    for x in [m..k*m] do
       expv:=expv+x*P(n,k,m,x);
    end for;
    return(expv);
 end function;

  for x in [3..18] do
    print x, P(4,6,3,x), RealField(7)!P(4,6,3,x);
  end for;

 print E(2,6,1), E(2,20,1), E(4,6,3), E(4,6,1);

Probability mass function of $\ B_t $
The event $\ \big\{B_t=r\big\}\ $ occurs if and only if the uppermost faces of some number $\ a\ $ between $\ 0\ $ and $\ t-1\ $ of dice bear numbers strictly greater than $\ r\ $, the uppermost faces of some number $\ b\ $ between $\ t-a\ $ and $\ n-a\ $ of the remaining dice show exactly $\ r\ $, and the uppermost faces of the remaining $\ n-a-b\ $ dice bear numbers strictly less than $\ r\ $. The probability of this event is
$$
\sum_{a=0}^{t-1}{n\choose a}\sum_{b=t-a}^{n-a}\left(\frac{k-r}{k}\right)^a{n-a\choose b}\left(\frac{1}{k}\right)^b\left(\frac{r-1}{k}\right)^{n-a-b}\ ,
$$
which is therefore the value of $\ \Bbb{P}\big(B_t=r\big)\ $.  In the above expression, $\ {n-a\choose b}\ $ is the number ways the $\ a\ $ dice to show numbers strictly larger than $\ r\ $ can be chosen, and $\ \left(\frac{k-r}{k}\right)^a\ $ is the probability that they will all in fact show numbers strictly larger than $\ r\ $, $\ {n-a\choose b}\ $ is the number of ways $\ b\ $ of the remaining $\ n-a\ $ dice to show exactly the number $\ r\ $ can be chosen, and $\ \left(\frac{1}{k}\right)^b\ $ is the probability that those  $\ b\ $ dice will in fact all show the number $\ r\ $. Finally, $\ \left(\frac{r-1}{k}\right)^{n-a-b}\ $ is the probability that the remaining $\ n-a-b\ $, designated as showing numbers strictly less than $\ r\ $ will in fact all show numbers strictly less than $\ r\ $.
The following Magma script to evaluate $\ E(n,k,m)\ $ for arbitrary values of $\ n,k\ $ and $\ m\ $ using the expression \eqref{exp1}.  It obtains the same values for $\ E(n,k,m)$ as the procedure given above using the probability mass function of $\ S\ $. Thanks to Thomas B. for picking up the fact that my $\ m\ $ is his $\ n-m\ $, and thus resolving an  apparent discrepancy I had been concerned about earlier.
expv:=function(n,k,m)
   ev:=0;
   for t in [1..m] do
     evbt:=0;
     for r in [1..k] do
       pbter:=0;
       for a in [0..t-1] do
         s:=0;
         for b in [t-a..n-a] do
            s:=s+Binomial(n-a,b)*Binomial(n,a)*(r-1)^(n-a-b);
         end for;
         pbter:=pbter+s*(k-r)^a/k^n;
       end for;
       evbt:=evbt+r*pbter;
     end for;
     ev:=ev+evbt;
   end for;
   return( ev );
 end function;

 print expv(2,6,1), expv(2,20,1), expv(4,6,3), expv(4,6,1);
 print expv(33,22,22), RealField(10)!expv(33,22,22);

 print expv(2,6,1), expv(2,20,1), expv(4,6,3), expv(4,6,1);
 print expv(33,22,22), RealField(10)!expv(33,22,22);

Addendum
I agree with the expression you derive for $\ E(n,k)\eqdef$$\,E(n,k,n-1)\ $ in your answer.  I believe it's possible to derive your expression by substituting the one I give above for $\ \Bbb{P}\big(B_t=r\big)\ $ into the sum $\ \sum_\limits{t=1}^{n-1}\sum_\limits{r=1}^kr\,\Bbb{P}\big(B_t=r\big)\ $.  The only way I can see of proving the identity algebraically, however, is to transfer the sum over $\ t\ $ across the other three sums in the expression so that it becomes the inner sum instead of the outer sum.  The algebraic manipulations necessary to do this are rather cumbersome and error-prone, and since I'm satisfied your expression is correct, I eventually gave up trying to prove it by this unnecessarily convoluted procedure. I did however write a Magma function to evaluate your expression for $\ E(n,k)\ $ and compare its output with that of $\ E(n,k,n-1)\ $ as produced by the above Magma script.  For every pair $\ n,k\ $ I tried, the results were identical. Here they are:
\begin{align}
E(2,6)&=\frac{161}{36}=E(2,6,1)\\
E(2,20)&=\frac{553}{40}=E(2,20,1)\\
E(4,6)&=\frac{15869}{1296}=E(4,6,3)\\
E(33,22)&=\frac{
56692906323757439755684138687075800338253661}{149889224159230635544290231950914661384192}\\
&=E(33,22,32)\ .
\end{align}
Comment: The values you're getting are correct. The difference is that your solution gives the result for keeping $m$ dice, mine is for removing $m$ dice. Keeping 11 dice (from 33d22) gives 204.669.
Comment: Fair point actually, I failed to make that clear. I've edited my answer. Your Magma links don't seem to work for me...?
Comment: @Thomas B. Thank you for resolving the apparent discrepancy.  In an earlier edit of mine, I inadvertently overwrote the Magma script I had originally  included in the answer.  I've now restored it.  Hopefully it was the absence of the script that was causing you problems, rather than the links not actually working.
Answer: I think I have come to a solution for $m=n-1$, but it would be great if someone could check it.
We roll $n$ $k$-sided dice, ignore the least roll ($m=n-1$) and sum the rest.
Let $P_\ge(x)$ denote the probability that every single roll of the $n$ rolls is greater or equal to $x$.
$P_\ge(x) = \dfrac {(k - x + 1) ^ n} {k^n}$
Let $P_{\ge2}(x)$ denote the probability that every single roll of the $n$ rolls is greater or equal to $x$ and at least one roll equals $x$.
$$P_{\ge2}(x) = \dfrac {(k - x + 1) ^ n} {k^n} - \sum_{\nu=x + 1}^kP_\ge(\nu) \\
= \dfrac {(k - x + 1) ^ n - (k - x)^n} {k^n}
$$
This $P_{\ge2}(x)$ is actually the probability that I have to rest $x$ from the sum of my rolls.
Its expected value is $E(P_{\ge2})$.
$$
E(P_{\ge2}) = \sum_{\nu=1}^k \nu P_{\ge2}(\nu) \\
= \sum_{\nu=1}^k \nu \dfrac {(k - \nu + 1) ^ n - (k - \nu)^n} {k^n}
$$
So I expect to subtract $E(P_{\ge2})$ from every $n$ rolls I do.
The expected value of rolling $n$ $k$-sided dice without ignoring any rolls is $E_0 (n,k)=\dfrac{k+1}{2}n$.
Hence the expected value for rolling $n$ dice and ignoring one is:
$$E (n,k) = E_0 (n,k)- E(P_{\ge2}) \\
= \dfrac{k+1}{2}n - \sum_{\nu=1}^k \nu \dfrac {(k - \nu + 1) ^ n - (k - \nu)^n} {k^n}
$$
Comparing the result of this formula with real results (little program doing the rolls) shows that it seems to hold.
Is my thinking correct or is this just an approximation (I am not sure about simply subtracting both expected values)?
How can this be expanded for $m \ne n-1$?
Comment: I believe your expression for $\ E(n,k)\ $ is correct. I've added some comments about this to my answer.
Answer: This class of question was also asked about here.
Multiset enumeration
I would be remiss not to mention AnyDice, which can conveniently compute many problems of this type and is the currently the most popular resource of its type in the tabletop RPG area. However, it does enumerate all $\binom{n + k - 1}{n}$ possible multisets that can come out of a pool, so
output [highest 11 of 22d33]

would attempt to evaluate over 781 trillion possibilities, far beyond its 5-second limit.
Fast Fourier Transform
That the sum of a set of dice can be computed via convolution is a classical result in discrete statistics. Convolution (sometimes also framed in terms of generating functions) allows us to use the fantastically efficient fast Fourier transform (FFT). With some more work, FFTs can also be used the case where only some of the dice are kept. Approaches of this type have been proposed on StackExchange, with examples including:

Formula for dropping dice (non-brute force)
Generating Function for sum of N dice [or other multinomial distribution] where lowest N values are "dropped" or removed

Dynamic programming
However, my preferred approach is dynamic programming (sometimes also framed in terms of recurrence relations). Examples include:

Roll and Keep in Anydice
How to calculate the probabilities for eliminative dice pools (dice cancelling mechanic) in Neon City Overdrive?

The short of it is that we compute the answer to the problem to "roll $n$ d10, keep $m$" by considering how many dice $k = 0 \ldots n$ might possibly roll a 10, and then use the solutions to "roll $n - k$ d9, keep $m - k$" -- namely, the remaining pool after the $k$ dice that rolled a 10 are removed -- to complete the solution. In turn, the solutions for d9s use the solutions for d8s, and so forth until we reach d1s and all of the remaining dice must roll 1. While not as fast as FFTs, the dynamic programming approach is much more flexible, covering general "single-pass" functions over order statistics: in addition to summing the dice, it can also be used to produce efficient solutions for matching sets, straights, RISK-like mechanics, and so forth.
I've implemented this in my Icepool Python package. Here is an example script for keeping the highest 11 out of 33d22:
from icepool import d

output(d(22).highest(33, 11))

You can try it online here.
If you are interested in learning more, you can read my paper on the subject.
@inproceedings{liu2022icepool,
    title={Icepool: Efficient Computation of Dice Pool Probabilities},
    author={Albert Julius Liu},
    booktitle={Eighteenth AAAI Conference on Artificial Intelligence and Interactive Digital Entertainment},
    volume={18},
    number={1},
    pages={258-265},
    year={2022},
    month={Oct.},
    eventdate={2022-10-24/2022-10-28},
    venue={Pomona, California},
    url={https://ojs.aaai.org/index.php/AIIDE/article/view/21971},
    doi={10.1609/aiide.v18i1.21971}
}

Roll dice and ignore worst results


How can i set v-rating to be fixed on vuetify?

Question: I'm Building a page with vue.js and vuetify and i need my v-rating to be fixed on the value that i want, i don't want the user can change that value.
This is what i have until now.
  <v-layout align-center justify-center row wrap>
    <v-flex xs12 md4 v-for="(idioma, i) in idiomas":key="i">

{{idioma.comp}}:

      <v-img id="imgCompetencias":src="idioma.imagem"height="100"width="100"></v-img>
      <v-rating v-model="idioma.rating" half-increments></v-rating>

    </v-flex>
  </v-layout>

Answer: Just add readonly as attribute.
Read more in the docu:
https://vuetifyjs.com/en/components/ratings
Comment: That worked, Thank you, I must have pass through when I read the v-rating documentation.
Answer: Try adding readonly property.
 <v-rating readonly v-model="idioma.rating" half-increments></v-rating>

Comment: That worked, Thank you, I must have pass through when I read the v-rating documentation.
Answer: juts add readonly
  <v-rating v-model="idioma.rating" half-increments readonly></v-rating>

based on doc


Spinner com SQLite

Question: Olá, boa noite. No meu projeto tenho um spinner
<Spinner
    android:id="@+id/spnCategorie"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/categories_array"
    android:prompt="@string/categories_prompt" />

Esse spinner é responsável por adicionar o valor na coluna CATEGORIE no meu banco de dados através da classe InsertProduct.class.
As categorias que populam esse spinner é a seguinte:
<string-array name="categories_array">
    <item>Mantimentos</item>
    <item>Açougue</item>
    <item>Peixaria</item>
    <item>Frios</item>
    <item>Hortifruti</item>
    <item>Café da Manhã</item>
    <item>Higiene</item>
    <item>Limpeza</item>
</string-array>

Estou convertendo o valor do spinner para String para inserir no banco de dados da seguinte maneira. (Não sei se é a maneira correta.)
Spinner CATEGORIE = (Spinner) findViewById(R.id.spnCategorie);
String stringCATEGORIE = CATEGORIE.getSelectedItem().toString();
...

Tenho outra classe (AlterProduct.class) responsável por alterar os valores dos produtos, gostaria que o spinner da classe AlterProduct.class retornasse a categoria salva no banco de dados.
Ex: Meu produto foi inserido no banco de dados com a categoria Frios, quando o usuário clicasse para alterar o produto, ele retornasse o valor Frios no spinner da classe AlterProduct.class
Att.
Giovani Rodrigo
Answer: Acredito que o que você precisa fazer é consultar o valor no banco de dados e setar o item selecionado no spinner, isso pode ser feito usando o método setSelection(int position)
Caso você queira setar o valor pelo texto e não pela posição dele nas opções do spinner esse link pode ajudar: https://stackoverflow.com/questions/2390102/how-to-set-selected-item-of-spinner-by-value-not-by-position
Comment: Qual a diferença em setar pela posição ou pelo valor?
Comment: O método recebe apenas a posição que deve ser setada, caso você não saiba essa posição exatamente você percorre a lista e compara os valores procurando a posição.
No fim você sempre estará passando uma posição que é o que o método pede como parâmetro.
Comment: Por position, ao invés de eu salvar o valor do imte selecionado como string, eu devo salvar como valor int da posição do item?
Comment: Melhor não, pois se você precisar alterar a lista futuramente você pode ter complicações.

Spinner com SQLite


equinox + sample.http - issue with tomcat 7

Question: I am importing sample.http from http://www.eclipse.org/equinox/server/http_in_container.php into eclipse , using tomcat 7 as server (linux platform).
It shows several problems such as :
<code>BundleActivator cannot be resolved to a type
No available bundle exports package 'javax.servlet.http'
</code>
and several such errors due to plugin dependencies not being imported.
(If I try with tomcat 6,it works).
Can someone point out what changes I should make for making the dependencies compatible with tomcat 7 ?
Answer: The problem is the org.eclipse.equinox.http.servletbridge jar.
It exports Servlet javax.servlet 2.3 but for Tomcat 7 you need javax.servlet 3.0
Maybe you can open up the jar file and fix that, but I have wasted quite some time with this construction, and never got it right. It is 5 years old, and that means trouble.
For me Felix worked a lot better, there is a clearer and more consistent explanation.
Take a look here: apache felix
I think with this setup you could still use Equinox with the FrameworkLauncher, if that is necessary


Groovy custom sort a map by value

Question: I have a map such as
m=[
     "james":"silly boy",
     "janny":"Crazy girl",
     "jimmy":"funny man",
     "georges":"massive fella"
];

I want to sort this map by its value but ignoring the case (this is really why the custom sort is needed). Hence I figured I had to implement a custom sort using a closure. But I'm brand new at Groovy and been struggling to get this very simple task done!
The desired results would be:
["janny":"Crazy girl", "jimmy":"funny man", "georges":"massive fella", "james":"silly boy"]

Thanks !
Answer: To sort with case insensitive, use
m.sort { it.value.toLowerCase() }

Answer: Assuming you mean you want to sort on value, you can just do:
Map m =[ james  :"silly boy",
         janny  :"Crazy girl",
         jimmy  :"funny man",
         georges:"massive fella" ]

Map sorted = m.sort { a, b -> a.value <=> b.value }

Comment: Also equivalent to `m.sort { it.value }`
Comment: m.sort { a, b -> a.value.toLowerCase() <=> b.value.toLowerCase() } is the correct answer for this other solution :)
Comment: This use natural ordering (or sorting) which is case sensitive. How can I make this case insensitive ?
Answer: If somebody is looking for how to make it work in the Jenkins pipeline script, you will have to create a separate method with @NonCPS annotation for that:
@NonCPS
def getSorted(def mapSizeMap){
    mapSizeMap.sort(){ a, b -> b.value <=> a.value }
}

And then call it from the pipeline script.
def sortedMapZoneMap = getSorted(mapZonesMap)
You can of course apply "case sensitive" logic on top.
Comment: Confirmed, I've been fighting this in a Jenkins pipeline and your suggestion is working for me. Thank you.
Comment: Actually it would make sense to create a separete question for that, that would include Jenkins pipelein in the title. Then it will be easier to find. I also spend a lot of time looking for solution :)
Comment: I created a separate question for that :
https://stackoverflow.com/questions/63121651/groovy-jenkins-pipeline-script-sort-a-map-by-value/63121652#63121652

I hope it will be easier to find. If somebody could upvode, I will be glad :)
Answer: BTW, here is code which is showing different sorting with and without toLowerCase():
Map m =[ james  :"silly boy",
         janny  :"crazy girl",
         jimmy  :"Funny man",
         georges:"massive fella" ]
Map sorted = m.sort { a, b -> a.value <=> b.value }
println sorted
sorted = m.sort { a, b -> a.value.toLowerCase() <=> b.value.toLowerCase() }
println sorted

And wll print:
[jimmy:Funny man, janny:crazy girl, georges:massive fella, james:silly boy]
[janny:crazy girl, jimmy:Funny man, georges:massive fella, james:silly boy]

Groovy custom sort a map by value


Custom login for specific role

Question: On a site there are some pages from a Content-type. Some of those pages (for the Belgium language only) need to be only accessible for Dokters.
So when you try to reach the URL of one of those pages you are redirected to a login-page.
But the role 'dokters' needs to have an extra login-field. Or only this field to login is even better if thats possible! It should be a field with 11 digits. Or if this is to complicated (Username, Password, 11-digit field).
How (which modules) are best practices to built this functionality?
UPDATE:
Now i managed to do a workaround with Content Access module. I made a role 'doctor'. And now only users with role 'doctor' can access those pages.
But is there something to do like when the Doctors visit those restricted pages they are redirected to a custom login-page. On this page you have a small form: Fill in your 11-digit code to access this page.
Because all doctors have their own 11-digit code. We don't have to send all doctors the username name and password for role 'doctor', instead they can access the content directly, with their 11-digit code! The only validation should be that the field contains 11 digits.
How do i manage this in the simplest/best way?
Comment: I'm sure something like this was asked before. I'll try to find a link when I'll have a while. But -  any reason why you want to treat them differently?
Comment: @Mołot because in the best possible scenario i want the doctors to login with only an 11 digit number like i [asked here](http://drupal.stackexchange.com/questions/186691/require-specific-login-page-for-certain-pages/186729#186729)
Comment: @Mołot so basically what i need i think is a conditional login-form. You have normal user login or you can login as a doctor. If you select checkbox 'login as Doctor' an extra field is added to the login form. Or am i thinking to complicated? I just have some pages on the site which require authentication with i.a. 11-digit number.
Comment: If there are certain pages which can only be viewed by docters, isn't it a better solution to create a custom permission which you grant to the doctors role? Or are those digits related to the restricted pages?
Comment: @Patrick Scheffer no the digits are not related to the restricted pages. Ok and how do i create a custom permission for those pages?
Comment: Can all doctors view all digit-protected pages? And do you want the doctor to login after entering the 11 digit code or is granting access to the content enough (in this case the user remains anonymous)?
Comment: yes all doctors (who has their 11-digit number) can see all those pages. Yes i want the doctor to login after entering the 11 digit code. Without login they can see the rest of the site like all other people.
Comment: @Patrick Scheffer is that possible some how?
Comment: Of course, anything's possible. :P However, I can't think of a module which does this so I think this would be custom code. You could create a form which logs the user in after entering the 11-digit code, but I don't know if that's very secure. An 11-digit code is fairly easy to hack by brute force..
Answer: First, create a custom permission:
/**
 * Implements hook_permission().
 */
function MY_MODULE_permission() {
  return array(
    'access doctor content' => array(
      'title' => t('Access content for doctors'),
    )
  );
}

If the restricted content is a custom page you can do this:
/**
* Implements hook_menu().
*/
function MY_MODULE_menu() {
  $items = array();
  $items['doctor_page'] = array(
    'title' => 'Doctor page',
    'page callback' => '_doctor_page_content',
    'access arguments' => array('access doctor content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

If the restricted content is a node make sure there is a reliable way to filter that content in your code (e.g. by adding a checkbox 'Protected' to the node). Set access restrictions on nodes like this:
/**
 * Implements hook_node_access().
 */
function MY_MODULE_node_access($node, $op, $account) {
  // Check if the content is protected.
  if (!empty($node->field_protected_content[LANGUAGE_NONE][0]['value'])) {
    // If so, check if the user has access to it.
    if (user_access('access doctor content', $account)) {
      // Allow access.
      return NODE_ACCESS_ALLOW;
    }
    // Deny access.
    return NODE_ACCESS_DENY;
  }

  // Handle the default restrictions.
  return NODE_ACCESS_IGNORE;
}

Don't forget to add your custom permission to the user role via the permissions page (admin/people/permissions).
Comment: Is it not easier to do above with [Nodeaccess](https://www.drupal.org/project/nodeaccess) module?
Comment: Yes, the same can be achieved with that module. However, it brings a lot of extra functionality, more than you need. The grants tab shows all user roles so you need to be careful which role you select and only give it the view permission. But if you don't mind that, it is a useful module.
Comment: Thanks for your quick reply. I **Update** my question above.

Custom login for specific role


java.text.parseexception unparseable date in android

Question: String dt=mDateButton.getText().toString();
String tm =mTimeButton.getText().toString();
  try {
    String format ="dd-MM-yyyy hh:mm a";

    DateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

    String v_date_str = dt + " " + tm;
    //  String setDate =sdf.format(dt + " " + tm);
    Date v_date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH).parse(v_date_str );

    DateFormat formatter = null;
    formatter = new SimpleDateFormat("dd-MMM-yyyy");

    Log.d("sset: ", ""+formatter.format(v_date));
  } catch (ParseException e) {
    e.printStackTrace();
  }

Note: where dt = 2013-03-02  and tm = 21:54 . but i got an error on 9th line. i dont know what's the reason. please help me to get out of this problem. thank you in advance.
Answer: The problem is you have a DateFormat pattern mismatch.
Since v_date_str is 2013-03-02 21:54, you can match its format using:
new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH)


Creating a basic calculator in python

Question: This is what I have so far:
import sys

first = float(sys.argv[1])
second = str(sys.argv[2])
third = float(sys.argv[3])

if second == "+":
  print first + third
elif second == "-":
  print first - third
elif second == "*":
  print first * third
elif second == "/":
  print first / third
elif second == "^":
  print first ** third
else:
  print "Invalid Operator"

The first and third arguments are supposed to be double floating point numbers. I wasn't sure how the operator is supposed to be represented, so I just named it "second" and set it as a string. I'm confused as to how I'm supposed to actually get the calculations. Are my if/elif/else statements wrong? Am I supposed to use "print" or "return" for actual calculations to be made?
This is an example of a test file:
 def test_add(self):
    output = self.runScript("simple_calc.py", "1", "+", "1")
    result = float(output)
    self.assertAlmostEqual(2.0, result, places=10)
    output = self.runScript("simple_calc.py", "-1", "+", "1")
    result = float(output)
    self.assertAlmostEqual(0.0, result, places=10)
    output = self.runScript("simple_calc.py", "1.0", "+", "-1.0")
    result = float(output)
    self.assertAlmostEqual(0.0, result, places=10)

Comment: Is there any specific error you're encountering?
Comment: The part which calculates a power using `^` using Python will not work. Use `**` in your code instead.
Comment: @slackxx, if you have new errors then ask a new question, don't edit them into your current question although I suggest you try debugging your own code before you do.
Comment: From your comments elsewhere, I see that you are taking a beginner Python course. Unfortunately, calculators are a very poor choice for beginner projects in a general programming language, as sanitizing and parsing arbitrary input is a very difficult task in this context.
Comment: @PadraicCunningham I can't make new questions. I need to wait 2 days lol
Answer: your using = instead of ==
so it should be like this
if second =="+":

and do the same for all
= is an assignment statement not comparison
Comment: Oooh. you're right! It's still not working though. :/
Comment: @slackxx you are expecting a return value from your script but your code is just printing it
Comment: When I use `return` I get that red scribbly line on the return lines that say `'return' outside of function`
Comment: @slackxx  yeah you can't use return without function , just take a look at this link  http://stackoverflow.com/questions/30664263/return-value-from-one-python-script-to-another
Comment: Turned it into a function and getting new error `ValueError: could not convert string to float:`
Comment: @slackxx you need to use some debugging , will help a lot , try printing the value which you are trying to convert into float(where you are getting error)
Answer: You could for example make a function called calculator and then use it with user inputs. :
def calculator(x, y, operator):
    if operator == "+":
        return x + y
    if operator == "-":
        return x - y
    if operator == "*":
        return x * y
    if operator == "/":
        return x / y

The x and y would of course be numbers user would input, operator is the operator of choice. So basically the function here would take 3 arguments.
Comment: We're currently doing loops and conditionals. Haven't reached functions in yet.
Comment: I see. Well the basics can still apply. What you could still do is ask for two separate numbers, then ask what operation to use and make if statements based on possible choices to do the operation.
Answer: Here is my solution:
def Operation():
    while True:
        operation = raw_input('Select operation: \n + = addition\n - = Subtraction\n * = multiplication\n / = Division\n')
        if operation.strip() == '+':
            break
        elif operation.strip() == '-':
            break
        elif operation.strip() == '*':
            break
        elif operation.strip() == '/':
            break
        else:
            print "Please select one of the operations"
            continue
    return operation

def number():
    while True:
        try:
            number = int(raw_input("Please enter a number: "))
            break
        except ValueError:
            print "Please enter valid number: "
    return number

num1 = number()
operator = Operation()
num2 = number()

def calculate(num1, operator, num2):
    if operator == "+":
        return num1 + num2
    elif operator == "-":
        return num1 - num2
    elif operator == "*":
        return num1 * num2
    elif operator == "/":
        return num1 / num2

print calculate(num1, operator, num2)

Creating a basic calculator in python


Extjs 4: grid duplicated in web interface same structure. Each grid has a different store

Question: I have a web interface with several grids
Each grid have same structure.
But each grid is filled by a different store with same model.
Ext.define("erapnot.view.taskslist.EastItemSdPnGrid", {
  extend: "Ext.grid.Panel",
  xtype: "eastitemsdpngrid",
  store: "EastItemStore",
  columns:[...

I tried to add an "id" for each grid as following:
id:'east-panel',
xtype: 'panel',
region:'east',
title: 'LIST',
items: [{
          id:'**firsteastitemgrid**',
          xtype: "eastitemgrid"
       }, {
          id:'**secondeastitemgrid**',
          xtype: "eastitemgrid"
       }
       ]
},

So I tried this in my grid
Ext.define("erapnot.view.taskslist.EastItemGrid", {
  extend: "Ext.grid.Panel",
  xtype: "eastitemgrid",
  store:{"#firsteastitemgrid": "EastItemStore" ,
         "#secondeastitemgrid":"EastItemDifStore"},

I have no syntax error but it doens't work.
Is it possible to have a grid defined only one time with several store ? Or must I create one grid by store even if all grid have same structure, model, controller.
Thanks in advanced.
Comment: What is different about them? Surely you're not showing exactly the same grid with the same content over and over again.
Comment: For example, all grids content "name" "firstname". Only SQL request in backend retrieves a different result but all grid will display a result with a list of "name" "firstname".
Comment: Right, but how does it retrieve a different result? My point is, what is the part that changes. The server doesn't randomly return different data.
Comment: Nothing changes except my "proxy:{url: 'abc/cde'.... in my store.js files to call a different SQL request.
Answer: your solution seems very strange. try to set the store during instantiate:
items: [{
      store:"EastItemStore",
      xtype: "eastitemgrid"
   }, {
      store:"EastItemDifStore",
      xtype: "eastitemgrid"
   }]

and in the grid definition don't set any store.
Answer: Do something like this:
Ext.define('MyGrid', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.mygrid',

    columns: [],

    initComponent: function() {
        this.store = new Ext.data.Store({
            model: 'MyModel',
            proxy: {
                type: 'ajax',
                url: this.storeUrl
                // other options here
            }
        });
        this.callParent();
    }
});

Then you can use it later:
items: [{
    xtype: 'mygrid',
    storeUrl: '/foo/a'
}, {
    xtype: 'mygrid',
    storeUrl: '/foo/b'
}, {
    xtype: 'mygrid',
    storeUrl: '/foo/c'
}]


How do I create a new function that will take in an array of numbers and add all of them?

Question: I have to create a new function that will take in an array of numbers and add all of them together. The Code below is what I have, but I'm nut sure what I'm missing.
var total = 0;
arr = [7, 8, 9];

function totalOfNumbers(arr){
   for (i = 0; i < arr.length; ++i) {
     total += arr[i];
   }
   return total;
}
console.log(totalOfNumbers);

Thanks for your time.
Comment: You might want to declare `total` inside the function and actually call the function...
Comment: You're not *calling* the function. Try `totalOfNumbers(arr)`
Comment: You are not calling the function but just printing the string function, and you better make use of Array.prototype.reduce for the this operation and call the function by passing an array as an argument to it like this
console.log(totalOfNumbers(arr))
see my answer below.
Answer: Try like this
var total = 0;
    arr = [7, 8, 9];

    function totalOfNumbers(arr){
       for (i = 0; i < arr.length; ++i) {
             total += arr[i];
    }
    return total;
    }
    console.log(totalOfNumbers(arr));  //Note here calling function with arr

Answer: You have to call or invoke (by specifying parenthesis at the end of the function name) the function by passing the array as parameter. If you do not specify the parenthesis, instead of execution of the function, the function itself will be returned:

var total = 0;
var arr = [7, 8, 9];

function totalOfNumbers(a){
  for (i = 0; i < a.length; ++i) {
   total += a[i];
  }
  return total;
}
console.log(totalOfNumbers(arr)); // call the function by specifying parenthesis at the end of the function name
Answer: You can make use of Array.prototype.reduce method for that operation.
below is the code for the function that will make use of reduce method and return the sum of all values in an array
function totalOfNumbers(arr){
    return arr.reduce((a,b)=>a+b);
}

/*and then call the function by passing the array that you want to
get the sum of elements */

let arr = [7,8,9];
let sumOfArray = totalOfNumbers(arr);
console.log(sumOfArray)

Click here for further information about Array.prototype.reduce
Answer: Here is a very basic, functional approach, that is a less terse version to add contents of an array. You probably will want to validate that all the elements are actual javascript Numbers before you try to add. You can find documentation on the reduce function here .
let total = 0;
let arr = [7, 8, 9];

function totalOfNumbers(values){
   return values.reduce((accumulator, value) => {
     accumulator += value;
     return accumulator;
   }, 0);
}
console.log(totalOfNumbers(arr)); // 24

Answer: You can try
var numbers = [65, 44, 12, 4];

function add(total, num) {
  return total + num;
}
var total = numbers.reduce(getSum);

Answer: Here is the one liner :)
const totalOfNumbers = arr => arr.reduce((a,v) => a + v)


Find the number of arrangements of BANANA

Question: Attempt:

If the Ns appear next to each other

I treat as if there is 1 B, 3 As, 1 N which leads to $\frac{5!}{1!3!1!}$

Every N is followed by an A

I count the possible "unique characters" as NA-2, A-1, B-1 so I end up with $\frac{4!}{2!}$

the two Ns must be separated

No matter how much I think about it, I'm not sure I can get an answer that doesn't lead me with a headache.
Comment: Why are you trying to solve in this way?
Comment: Possible duplicate of [how many ways can the letters in ARRANGEMENT can be arranged](http://math.stackexchange.com/questions/236471/how-many-ways-can-the-letters-in-arrangement-can-be-arranged)
Comment: For #3, arrangements with Ns separated = all possible arrangements - arrangements with Ns together.
Answer: We have simply -
$\frac {6!}{3! × 2!}$ to arrange alphabets of BANANA.
Dividing by 3! and 2! as we 3 A's and 2 N's.


Node.Js Threadpool in Windows

Question: So my understanding is, any blocking file system operation (such as fs.readFileSync) is eventually delegated to one of the thread in thread pool to keep event loop free. Now, I am running my application from windows and the command i am using, set UV_THREADPOOL_SIZE=4 & node index.js
My sample code below,
const start = new Date().getTime();
readFile();
readFile();
readFile();
readFile();
readFile();

function readFile() {
  fs.readFileSync('./content/1.txt');
  const end = new Date().getTime();
  console.log('Time took: ', (end - start) / 1000);
}

Now no matter whether I set the thread pool size to one or four, the execution time remains almost same. FYI, there are two CPU cores in my PC. Therefore my expectation was, if I set thread pool size to four (or let the default settings work) out of my 5 function call to read the file, say first four takes x secs (I understand it won't be the exact time for both call but going to be very close), then the last one  (x+n), where x & n are random numbers and represents time difference in seconds.
But that's not happening. Irrespective of the number of thread pool calls are taking same time to complete and getting completed one by one.

So, looks like my understanding about how node.js thread pool works is not right. Any help would be appreciated. Thanks.
Answer: The first issue is that you're using fs.readFileSync().  That means your file operations are only going to be requested one at a time.  The 2nd one won't start until the first one is done.  This has nothing to do with the thread pool.  This is because you're using the blocking, synchronous version of readFile().  The JS interpreter will be blocked until the first fs.readFileSync() is done and the second one only gets to start after the first one is done and so on.  So, because of that, in this case it won't really matter how many threads there are to serve the file system.
If you want to engage more than one thread in file operations, you need to use asynchronous file operations like fs.readFile() so you can have more than one file operation in flight at the same time and thus have more of an opportunity to use more than one thread.
Also, file operations on the same disk are not as scalable with multiple threads/CPUs as some other types of operations because the read/write heads can only be in one place at a time so even if you do change the code to successfully engage multiple threads or CPUs you can't get full parallel file access on the same drive due to the serialization of the read/write head position.
Here's an example of a test using the asynchronous fs.readFile():
const start = new Date().getTime();
let cntr = 0;

readFile(0);
readFile(1);
readFile(2);
readFile(3);
readFile(4);

function readFile(i) {
  fs.readFile('./content/1.txt', function(err, data) {
      if (err) {
          console.log(err);
          return;
      }
      const end = new Date().getTime();
      console.log(`Time took: ${i} ${(end - start) / 1000}`)
      if (++cntr === 5) {
          console.log(`All Done. Total time: ${(end - start) / 1000)}`;
      }
  });
}

This test would likely be more meaningful if you read a different file (that wasn't already in the OS file cache) for each call to readFile().  As it is the 2-5 requests are likely just fetching data from memory in the OS file cache, not actually accessing the disk.
Comment: @DebasishChowdhury - Well, multiple threads/CPUs helps operations that use the CPU a lot and doesn't help things much at all that don't use the CPU much.  So, it depends upon the operation.
Comment: perfect explanation .. silly me .. of course  read file sync will block the entire execution .. what i was thinking .. btw.. special thanks for your brief input on scalability. One quick question, when you mentioned **Also, file operations on the same disk are not as scalable with multiple threads/CPUs as some other types of operations** - this other types mostly means any heavy piece of code that is synchronous and therefore blocking in nature.  right?

Node.Js Threadpool in Windows


Pearson chi squared for correlated sample

Question: I am looking into the STS statistical test for random sequence.
There are multiple statistical tests for a random bit sequence and each of them produces a p-value or multiple p-value.
After the test finished, I have dozens of p-values for multiple tests and each of them distributes approximately uniform over $[0,1]$.
I would like to incorporate all of them to a single p-value:
If I assume the p-values are independent, then I can compute the Pearson chi square  on the p-values (i.e. discretize the uniform value to some discrete intervals, e.g. $[\frac{i}{10}, \frac{i+1}{10}]$).
The problem is that I cannot assume the p-values are independent.
What I can do:
I can compute the correlation matrix between all the p-values, and maybe multiply by the squared inverse to whiten the correlation and then assume they are independent,
Other more rigorous suggestion would be helpful.
Answer: There are several methods for doing this. Perhaps Cinar, O., & Viechtbauer, W. (2022). The poolr Package for Combining Independent and Dependent p Values. Journal of Statistical Software, 101(1), 1–42. https://doi.org/10.18637/jss.v101.i01 may help you even if you do not use R. Cinar's PhD thesis which he defended earlier this year (2022) at the University of Maastricht may help you if it is available on-line.
Comment: If I understand correctly, to deal with dependent variable it is assume that the joint (pairwise) statistic is known and that the joint distribution (after normilize the p-value) is also jointly normal, right?


Search javascript object to return the relevant catId

Question: I have the following javascript array and I am trying to simply return the catId for an id - for instance if I search for the id of 10000356 I want to return the value of 4. How should I do this?
categoryIds = [
    {
        "id": 10000282,
        "catId": 0
    },
    {
        "id": 10000340,
        "catId": 0
    },
    {
        "id": 10000341,
        "catId": 0
    },
    {
        "id": 10000334,
        "catId": 1
    },
    {
        "id": 10000333,
        "catId": 2
    },
    {
        "id": 10000336,
        "catId": 2
    },
    {
        "id": 10000337,
        "catId": 3
    },
    {
        "id": 10000356,
        "catId": 4
    }
]

categoryIds.filter(id => id == 10000356);

Expected outcome :
4 - the catId for `10000356` is the integer 4.

Comment: Use find : `categoryIds.find(obj => obj.id == 10000356).catId`
Comment: Ah, I thought the `?` operator was only available in Typescript, not in JS. Good to know. Yes I know, the result of `find` can be null, so of course one has to check for nullity and this kind of things.
Comment: @JeremyThille NO ```categoryIds.find(obj => obj.id == 10000356)?.catId``` because find can return null if it doesn't find anything and here your code will break since you do not check it and you may try to return null.catId and that's an error
Comment: Yep it is available in js, and this will prevent a bad copy past :P
Answer: const result = categoryIds.find((data) => data?.id === 10000356); // beware result can be null
// use ?. to avoid error if data is null
// rembere that you have an array of object not of id ;)
console.log("the catId for 10000356 is the integer " + result?.catId);

use find if you are sure that the id are unique and I think it's the case here.
find will return the data you want and return null if not found
Comment: if you use a version of js that doesn't support ?. can use some if like if (data) { return data.id === 10000356} else {return false}


Azure Active Directory authentication from native application without requiring user login

Question: Here is what I am trying to accomplish -
A native application which is going to be run on a system where I cannot involve the user to login but I want to access web services secured behind AAD using a bearer token. There are two options -

Use a certificate based flow (which I want to avoid for few reasons
specific to my project)
Use the client secret

Issue I am running into:
When I call acquiretokenasync using the Native AAD application's client ID and a client credential built using the AAD web application's (which the native app has permissions to) client secret, I get the following error  -
{"AADSTS70002: Error validating credentials. AADSTS50012: Invalid client secret is provided.\r\nTrace ID: f52cc954-2674-47ee-9a7b-094451b05c7c\r\nCorrelation ID: 1ba8ac64-cc4a-4ff7-83d6-a333504459d6\r\nTimestamp: 2016-08-20 01:45:08Z"}
So given that the client secret is indeed correct (which I am positive about), what could be the real issue behind this error?
Thanks in advance for your help :)
Answer: You can't use the native application client ID and web application client credential (client secret). The native application has no associated secret, only the web application has. Native applications are assumed to run on insecure hosts, such as the desktops and smartphones. Client secrets would become too fragile.
For more information on how to authenticate a native application and access resources, take a look at these articles:

Authentication Scenarios - Native Application to Web API
Developing Native Client Applications
Answer: There are two types of application which we can register in Azure Active Directory.

Select Native for client applications that are installed locally on
a device. This setting is used for OAuth public native clients.
Select Web app/API for client applications and resource/API applications that are installed on a secure server. This setting is
    used for OAuth confidential web clients and public user-agent-based
    clients. The same application can also expose both a client and
    resource/API.

Native applications are public clients in OAuth2 parlance. Those apps are meant to run on a device and aren't trusted to maintain a secret - hence, their entry in the directory does not have the corresponding property. Without a secret, there is no way to assert the identity of the app - hence such apps cannot gain app level permissions and the portal UX reflects that. Conversely web apps are, again in OAuth2 parlance, confidential clients. They can get delegated tokens for their users, but they can also use client credentials to get tokens as themselves. Native apps can obtain tokens for the user via the OAuth2 authorization grant.
Refer this article further.


No Back Option showed

Question: This is my navigation.class which is also my main class.It has inside my navigation drawer and allfragments(fragment)
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation33);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        toolbar.setNavigationIcon(R.drawable.ic_flash);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        cooLayout=(ConstraintLayout)findViewById(R.id.cooLayout);
        FloatingActionButton myFab = (FloatingActionButton) findViewById(R.id.fabId);
        myFab.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivity(new Intent(navigation33.this,Post.class));
            }
        });
        auth = FirebaseAuth.getInstance();
//        db = FirebaseFirestore.getInstance();

        final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        authListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user == null) {
                    startActivity(new Intent(navigation33.this, login_user.class));
                    finish();
                }
            }
        };
         drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);

        drawer.addDrawerListener(toggle);

        toggle.syncState();
        setTitle("Appx");

         navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        fragmentManager = getSupportFragmentManager();

        myFragmentTransaction = fragmentManager.beginTransaction();
        myFragmentTransaction.replace(R.id.cooLayout, new AllFragments()).commit();
    }

I have the answers here where just by adding                 getSupportActionBar().setDisplayHomeAsUpEnabled(true); fixes their problem,however not mine.
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/orange"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include
    layout="@layout/content_navigation33" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fabId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:backgroundTint="@color/colorPrimaryDark"
    app:srcCompat="@drawable/ic_lightbulb" />

Shouldn't this be by default,what am I missing here?
Thanks in advance!
How it is

How I want it to be
Comment: hi @someguy your back button is not showing?or is it only not clickable?
Comment: also what is your base activity? AppCompat? ActionBarActivity?
Comment: back option only not showing ahh? or toolbar also not showing ahh?
Comment: what???toolbar shows,the back btn doesn't, before giving -1 please read the question. @RanjithKumar
Comment: Hello I am not giving -1.. I just want to answer your question.. If you not still believe me I will prove with my downvote. (One person can one vote only). Before complaint pls make sure its right or wrong..
Comment: @LeviAlbuquerque thanks you,it is not showing at all.it opens just like the swipe tabs,meaning that the bar icon doesnt change
Comment: I see, could you post activity_navigation33.xml ?
Comment: @LeviAlbuquerque just added my app bar navigation
Comment: what about your activity? AppCompact or ActionBar?
Comment: @LeviAlbuquerque the one posted is my main activity,the others are parts areonNavigationItemSelected,onBackPressed.Basically I replace the coolayouT(content navigation) with fragments.
Comment: I get it,.I wanted to know what class your main activity extend, AppCompatActivity or ActionBarActivity?
Comment: AppCompatActivity @LeviAlbuquerque
Answer: Try setting the icon for your toolbar.
    toolbar.setNavigationIcon(R.drawable.ic_back_arrow);
    toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onSupportNavigateUp();
        }
    });

EDIT:
I tested it here and if you add can controle the showing up  or hiding of the back arrow by calling this on your toggle object:
toggle.setDrawerIndicatorEnabled(false);

Then to update the toolbar again
    public void onBackPressed() {
...
        toggle.setDrawerIndicatorEnabled(true);

So if you do this:
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
 toggle.setDrawerIndicatorEnabled(false);

Don't forget to add:
 @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

This works only when:
    myFragmentTransaction.addToBackStack(null);

You won't get the hamburger button but the back arrow. So you need to make your toggle a member variable so you can access it globally and control when you want to show or hide the back arrow.
Comment: yeah, right after getSupportActionBar().setHomeButtonEnabled(true);
Comment: I found out how to go back the only thing now is to update the `code toolbar.i put the if (id == R.id.nav_profile) {
            fragment = new UserFragment();
            toggle.setDrawerIndicatorEnabled(false);
`
Comment: this should be inside my main class
Comment: I sse in the picture that you have a hamburger button instead of the back arrow, afaik you can't have both at the same time. Does the hamburger button turn into an arrow when you click it?
Comment: No,thats the problem when go to the users fragment the button doesnt change at all.I want it to change like the one in the twitter picture
Comment: it does what I wanted but when I click on it,it doesnt bring me back to the homefragment
Comment: I know, I pointed you towards the answer so you could work it out by yourself :)
Comment: toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });...this exits me out the application
Comment: For what I've seen from you code you'll want to replace the fragment, instead of calling onBackPressed()

No Back Option showed


Breaking down Wald CI, Wilson CI, and Agresti-Coull CI

Question: I'm supposed to be writing R functions to calculate the Wald CI, Wilson CI, and Agresti-Coull CI for binomial proportion, I have a source that provides the equations, but I am completely lost. I am looking at the equations, but have no clue where I am supposed to be getting all the values I need.
Ward CI = $p̂ ± k n^{-1/2} (p̂q̂)^{1/2}$
Wilson CI = $(X+k^2/2)/(n+k^2)±(kn^{1/2})/(n+k^2)((p̂q̂+k^2)/(4n))^{1/2}$
Agresti-Coull CI = $p̂ ± k(p̂q̂)^{1/2}n̂^{1/2}$
I'm pretty sure I have most of it, but I am can't figure out what the value of k is.
n=40
p = 0.2
alpha=0.05
q=0.8
These formulas are from http://projecteuclid.org/download/pdf_1/euclid.ss/1009213286
I was wondering if anyone could break these down and explain them to me?
Comment: Where did you get the formulas? From something like this? https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval
Comment: The formulas were from formulas 1, 4 , and 5 in this article http://projecteuclid.org/download/pdf_1/euclid.ss/1009213286
Comment: The article defines the terms (like $\hat{p}$ and $n$) that it uses!
Comment: The one I am really struggling with is K, it says k=Z(alpha/2) but how do I get Z?
Comment: The article defines $z$ also -- right before equation 1 it says $\kappa=z_{\alpha/2}=\Phi^{-1}(1-\alpha/2)$
Comment: I see that, but have no clue what that means.
Answer: $X$ is the number of successes. $n$ is the number of trials. $\hat{p}=X/n$. $\hat{q}=1-\hat{p}$.
The article defines $\kappa$ in terms of $z$ and in turn defines $z$ right before equation 1:

$\kappa=z_{\alpha/2}=\Phi^{-1}(1-\alpha/2)$

$\Phi$ is the standard normal cdf.
$\Phi^{-1}$ is the inverse function of the standard normal cdf.
$\Phi^{-1}(1-\alpha/2)$ is the $1-\alpha/2$ upper tail quantile of the normal distribution.
For example for a 95% CI, $1-\alpha=0.95$ so $1-\alpha/2=0.975$ and $\Phi^{-1}(1-\alpha/2)\approx 1.96$.
In the article the Agresti-Coull interval is defined in terms of $\tilde{p}$  not $\hat{p}$. However, $\tilde{p}$ is of the same form as $\hat p$ but with an additional $\kappa^2/2$ successes and an additional $\kappa^2/2$ failures. For $\alpha=0.05$ that adds just under $2$ to $X$ and just under $4$ to $n$.
I think that covers all of the terms in equations 1, 4 and 5.
Comment: I'm still not sure what the Φ is or how to calculate that. Is it a standard from a table?
Comment: @Jamie If you're working by hand you'd use [normal tables](https://en.wikipedia.org/wiki/Standard_normal_table). If you're on a computer you call a standard function to evaluate it. Suitable statistical/mathematical function libraries will either offer $Φ$ and $Φ^{-1}$ or the error function ($\text{erf}$) and its inverse from which $Φ$ and $Φ^{-1}$ are readily calculated. In R $Φ$ and $Φ^{-1}$ are given by `pnorm` and `qnorm` respectively. Try `qnorm(0.975)`. See `?Distributions` for a list of links to the various distributions in vanilla R for which the `d`,`p`,`q` and `r` functions work.


Why is Gio Gonzalez's WAR is 0.01 ahead of Max Scherzer in ESPN's current WAR rankings?

Question: As of the time of this post, Gio Gonzalez's WAR is 0.01 ahead of Max Scherzer.  It's a pretty small difference, but when I look at the more traditional stats, it's really hard to see why they should even be close.
Gonzalez: 2.50 ERA, 1.14 WHIP, 163 K's in 179 IP
Scherzer: 2.32 ERA, 0.87 WHIP, 239 K's in 178 IP
I always thought that sabermetrics-oriented stats tended to favor pitchers who struck out more batters.  Scherzer has way more strikeouts and far fewer baserunners allowed (as indicated by the WHIP).  Can someone explain why their WARs are so similar despite this?  In my view, there's a pretty huge difference in WHIP and K's.  Also, there's a really big difference in their FIP values -- Gonzalez is at 3.89 while Scherzer is at 2.96.  Why don't these differences show up in the WAR for each pitcher?
Answer: Well it's depends on the type calculation that being done and there is no one way to determine WAR.
As for FIP values, ESPN uses WAR data provided by Baseball Reference which doesn't use FIP values while calculating WAR.  Instead, it uses runs allowed by the pitcher and compares that to the league average pitcher (adjusting for quality of opposition), parks pitched in, and quality of defense behind the pitcher.
But Fangraphs uses FIP values while calculating WAR and the result is different so Max Scherzer has WAR 5.2 as opposed to 6.86 in ESPN ranking while Gio Gonzalez has WAR of 3.0.
So, different variable used in calculating WAR will yield different result. And Gio Gonzalez who is ahead in one calculation may not be so in other calculation as data shows.
Other sources: calculating pitcher-war, wikipedia, sports.yahoo, war comparison


Twig template ignoring value in a for loop

Question: I'm looking to ignore a value in an array, so that only three of the four children are displayed here. There are four items in the page.root but I only want to display three of them.

      {% for child in page.root %}

          {{ child.title }}

      {% endfor %}

Looking through the documentation I can't find a way of limiting the for loop.
Thanks for the help!
============
Right, I was running Stacey app that also uses Twig. Sorry for that, I should have been more specific.
With stacey, slice is a method so this solves my problem:

      {% for child in slice (page.root, 0,3) %}

          {{ child.title }}

      {% endfor %}

I found that here. This correctly outputs only three of the children in page.root.
Answer:
"The template system is meant to express presentation not program
  logic." - Django documentation

So, you can use if statment,
{% for child in page.root %}
  {% if child.title != 'any title' %}

    {{ child.title }}

  {% endif %}
{% endfor %}

For the more information
Answer: The common solution for "printing only the first n items" is the slice filter:
{% for child in page.root|slice(0, 3) %}
    {# params are start and length, so that means the first 3 items #}
{% endfor %}

Comment: It was added in twig 1.6, which version are you using (the most recent one is 1.12.1).
Comment: Never mind, just fixed the problem. I think I am running an older version but I don't want to mess with it as it's a part of the Stacey app. Thanks for the help though.


I can not use the method .equals(..), it throws NullPointerException

Question:  req.getParameter("doit").equal("good");

Is it impossible to write this line in the
method? Without it, the program runs correctly. However whenever I write that line, it shows the error messages..

java.lang.NullPointerException at adhoc.FinePrint.doFilter(FinePrint.java:50)

Is there any way that I can check whether "doit" parameter is equal to "good"??
Comment: what is the error you are seeing?
Comment: It says "The server encountered an internal error that prevented it from fulfilling this request. "
Comment: and "java.lang.NullPointerException
 at adhoc.FinePrint.doFilter(FinePrint.java:50)"
Comment: No you are seeing this error from the client side you have to check the error log on your server.
Comment: so that is the real problem `req.getParameter("doit")` is returning null.
Comment: But I checked that req.getParameter("doit") returns correct value.
Comment: Do you know the function is kind of recursive? make sure it has value on all the chain objects.
Comment: @BBbbBB Check my answer. Instead of use equal use equals method
Answer: I'd recommend to turn your equals around to
"good".equals(req.getParameter("doit"));

This prevents the NullPointerException when the request parameter "doit" is not set.


How do I create a search page?

Question: I have the Search API and the Solr search modules installed. In /admin/config/search/search-api, I see my server and index created and with status set to OK. I can see on the index view page that my content is indexed correctly.

I did not use the Solr Search Defaults module because I have removed the default Article content type, and I don't want to recreate it. Without this content type, there is an error when activating the module.
How can I create a search page displaying all indexed results (for anonymous users, not in BO)?
One tutorial shows that Solr Search Defaults module uses views. I've created a view, where in View settings > Show I've selected Ideas index.
In the view, Format > Show is set to Rendered entity. Search index is the view mode. I have a page, but no content is displayed.
No filters are required, and all are exposed.

Other tutorial says I should create a search page in Configurations > Search and metadata > Search pages menu, but I don't have that menu.

Here are my Fields for Ideas index.

Here is another view I've tried, with Show > fields

Here are my error logs, there is a Notice:

Here is what I see using <code>{{ kint(page.content) }}</code> on my Search results page:

If I create a view with VIEW SETTINGS > Show > Content my content IS diplayed correctly.
Comment: You probably have one or more filters set to "required" - if you clear those flags all results should be displayed I think
Comment: You don't need the defaults module. Once content is being indexed you can either create a Views page or you can code it yourself using the Solarium client.
Comment: No, no filters are required. I've added my view to the description of the question, you can see.
Answer: After installing the searc api module:
1) goto: /admin/config/search/search-api/index/default_index/edit
If you want for example to search for both Users & Content at once, make sure that both entities for Content & Users under the Data sources section are checked.
2) Goto: http://site8.dd:8083/admin/config/search/search-api/index/default_index/fields
This page is used to choose which are the fields you want to be indexed for your search.
So make sure on this page that all the fields you want to search your entities by are added to your entities; If not,
add any field using the +Add Fields button.
3) On the same page: http://site8.dd:8083/admin/config/search/search-api/index/default_index/fields
Any field you add, it has its own data type which you have also the permission to change it.
As per the data type table available at the bottom of the page:

Fulltext fields are analyzed fields which are made available for
  fulltext search.  This data type should be used for any fields
  (usually with free text input by users)  which you want to search for
  individual words.

so in your view, if you want to use the Fulltext search to search for your contents, every indexed field on this page should also be set to Fulltext data type.
4) Goto: http://site8.dd:8083/admin/config/search/search-api/index/default_index
And make sure that the index Status bar is 100% and so all your contents are indexed to be searchable.
When you have done the above, create a new view as per below:

Show: index default content index
Check Create page box
Display format Grid
Hit save and edit button.

Within the views configuration page:
Under add fields section:

add any fields you want and make sure the field title has the (indexed field) text.

Under the filter criteria section:

add the fulltext search field and exposed to visitors.

Here you go, visit your search page and enjoy.
If none of the above helped you, feel free to ask any other question in comments or update your current question.
Comment: Yes if no filters are used, all the indexed content should be displayed for you. Did you try 1) clear your caches ? 2) Re-index all your content ? 3) add all necessary field for your content from the search api configuration page ? If you did all the above and still no luck, i am affraid you will have to give access your view and configuration page so i can debug it for you !
Comment: Thank you. I had all this, and now tried also your way to use _Format > Show > Fields_. It still displays nothing.
I expect to display all indexed content if there are no filters used. Right?
Comment: I've done 1-2-3. I've just updated the description with more screenshots, please, see if it helps.
The site is on local environment only now, so no access is possible.
Comment: I have checked all your configuration and everything seems to be correct ! In this page **Here are my Fields for Ideas index**, try to change the boost value for the **fulltext** type fields to a higher value for example 13.0 and if possible and you have time re-create your view using simplytest.me platform for easier debugging
Comment: I've set values to 13.0, then cleared caches, recreated a view just to test: no changes.
I really do not figure out how to use https://simplytest.me/, it seems Solr Search module does not exist there.
Comment: No worries, i will setup one simplytest.me testing site for you and i will try to recreate your issue... i will revert back to you as soon as i finish
Comment: Thank you. If you are interested to see the code, it is here https://github.com/oksana-skotar/interiors
Comment: I have an idea that a problem may be linked to a template. I use a theme, and maybe there the template is not correct for a search page. I see that simple "page.html.twig" template is used for this page. But how can I check if `{{ page.content }}` has all what is needed to display my search results?
I've updated the description with Kint results.
Comment: This seems way off track. All that is needed is a Views page to show the results - nothing else. If you suspect a theme issue, switch to Bartik to eliminate that possibility.
Comment: I have created a test website here (https://df8mk.ply.st/search-for-articles) similar to your configuration and all is working properly for me. You may check the configuration on the test website by using **username/password:** oksana/oksana about the theme issue, as Kevin suggested revert back to the default bartik theme and check your results again.
Comment: Wow, that's impressive! But I can not access the link (https://df8mk.ply.st/search-for-articles has error 404 and https://www.df8mk.ply.st/search-for-articles says that the site is dangerous and there is no option to go there.
Comment: @Kevin You're right, I've switched to Bartik, it does not display content as well.
Comment: The test website i have made for you used simolutest.me platform and that means that the website will expire after 12 hours and you will no longer have access to it
Comment: Ok, that's frustrating. Sorry, it was night in my zone. I'm trying to deploy on a hosting now.

How do I create a search page?


Tecla ENTER salvar tabela ao invés de espaçar

Question: Tenho a seguinte tabela que deixar editar diretamente no grid:

Os códigos dela:

Tabela MySQL

CREATE TABLE IF NOT EXISTS `php_interview_questions` (
`id` int(8) NOT NULL,
  `question` text NOT NULL,
  `answer` text NOT NULL,
  `row_order` int(8) NOT NULL
)

INSERT INTO `php_interview_questions` (`id`, `question`, `answer`, `row_order`) VALUES
(1, 'PHP array functions example', 'is_array(), in_array(), array_keys(),array_values()', 3),
(2, 'How to redirect using PHP', 'Using header() function', 4),
(3, 'Differentiate PHP size() and count():', 'Same. But count() is preferable.', 1),
(4, 'What is PHP?', 'A server side scripting language.', 0),
(5, 'What is php.ini?', 'PHP configuration file.', 2);

DB Controller:

<?php
class DBController {
    private $host = "localhost";
    private $user = "root";
    private $password = "";
    private $database = "blog_examples";

    function __construct() {
        $conn = $this->connectDB();
        if(!empty($conn)) {
            $this->selectDB($conn);
        }
    }

    function connectDB() {
        $conn = mysql_connect($this->host,$this->user,$this->password);
        return $conn;
    }

    function selectDB($conn) {
        mysql_select_db($this->database,$conn);
    }

    function runQuery($query) {
        $result = mysql_query($query);
        while($row=mysql_fetch_assoc($result)) {
            $resultset[] = $row;
        }
        if(!empty($resultset))
            return $resultset;
    }

    function numRows($query) {
        $result  = mysql_query($query);
        $rowcount = mysql_num_rows($result);
        return $rowcount;
    }
}
?>

index.php

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$sql = "SELECT * from php_interview_questions";
$faq = $db_handle->runQuery($sql);
?>

      <title>PHP MySQL Inline Editing using jQuery Ajax</title>

                Q.No.
                Question
                Answer

          <?php
          foreach($faq as $k=>$v) {
          ?>

                <?php echo $k+1; ?>
                <td contenteditable="true" onBlur="saveToDatabase(this,'question','<?php echo $faq[$k]["id"]; ?>')" onClick="showEdit(this);"><?php echo $faq[$k]["question"]; ?>
                <td contenteditable="true" onBlur="saveToDatabase(this,'answer','<?php echo $faq[$k]["id"]; ?>')" onClick="showEdit(this);"><?php echo $faq[$k]["answer"]; ?>

        <?php
        }
        ?>

saveedit.php

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$result = mysql_query("UPDATE php_interview_questions set " . $_POST["column"] . " = '".$_POST["editval"]."' WHERE  id=".$_POST["id"]);
?>

A tabela esta toda funcionando perfeitamente, a unica coisa que quero mudar é seguinte, quando edito um valor e dou ENTER a linha quebra pra baixo,se eu clicar na tela em algum lugar vago a mesma salva o que foi digitado,o que eu quero, quando eu pressionar a tecla ENTER acontecer da mesma forma que se eu clica-se na tela,salva-se minha informação.
Fonte da tabela: PhpPot Home (Caso queiram ver,lá tem uma demo.)
@Diego Souza
Answer: Coloca no TD um onkeydown chamando os mesmos parâmetros do onblur.
onKeyDown="checkEnter(event, this,'question','<?php echo $faq[$k]["id"]; ?>')"

Mas chamando a função abaixo:
function checkEnter(e, editableObj, column, id){
   if (e.keyCode == 13 && e.shiftKey == false) {
      saveToDatabase(editableObj, column, id);
      e.preventDefault();
   }
}

Comment: fiz as alterações mais continua espaçando para baixo
Comment: Esqueci de passar o evento.
Comment: Veja agora se dá certo.
Comment: Estranho, continua dando erro.
Comment: Veja se está entrando dentro do IF.
Comment: Veja o que o console do chrome esta me retornado,sabe o que é ? adicionei a pergunta,adicionei também as minhas linhas,talvez esteja fazendo errado.
Comment: Arrumei o código, dê uma olhada e testa.
Comment: Deu certo,não sei se é possível mais deixa eu implementar uma pergunta: quando faz o processo ele só atualiza aquele campo (como se fosse um re-flash nele), e possível eu fazer isso na linha toda? e também após fazer o processo o campo sair da edição ?
Comment: Sim. É possível. Mas acredito que isso caiba melhor numa outra pergunta.
Comment: se puder me ajudar: http://pt.stackoverflow.com/questions/178849/tabela-edit%C3%A1vel-dar-re-flash-nos-campos-fechando-o-campo-editavel


Como usar o POST em um json para um servidor Http

Question: Eu estava pensando como posso fazer um  POST de um json para um servidor http. O código que estou usando para fazer o json é o seguinte:
Person person= new Person();
                    product.FirtsName = "Ola";
                    product.ID = 1;
                    product.age= 10;

                    string json = JsonConvert.SerializeObject(product);

E esta é a classe Person:
 public class Person
    {
        public int ID { get; set; }
        public string FirtsName { get; set; }
        public int age { get; set; }
    }

Answer: Primeiramente, vou alterar sua classe Pedro, para uma classe chamada Pessoa e arrumar nomenclaturas. Decida se vai usar propriedades em inglês ou em português. Neste caso, vou utilizar as propriedades em inglês:
public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public int Age{ get; set; }
}

Ajustado isso, você precisa de um método assíncrono e de um objeto HttpClient. Neste caso optei por retornar um bool caso a operação retorne um código de sucesso:
///
/// Cria uma pessoa
///
/// <param name="person">Objeto 'Person'</param>
/// <returns></returns>
private async Task<bool> CreatePersonAsync(Person person)
{
    var client = new HttpClient();
    client.BaseAddress = new Uri("endreço da sua web api");
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    // Transforma o objeto em json
    string json = JsonConvert.SerializeObject(person);

    // Envia o json para a API e verifica se obteve sucesso
    HttpResponseMessage response = await client.PostAsync("Controller da sua API para criar a pessoa", new StringContent(json, Encoding.UTF8, "application/json"));
    response.EnsureSuccessStatusCode();

    if (response.IsSuccessStatusCode)
    {
       return true;
    }

    return false;
}

Note que em "endreço da sua web api" é o endereço http da sua API.

Por exemplo: http://criapessoa.azurewebsites.net/api/

Note que em "Controller da sua API para criar a pessoa" é o apenas o
  nome do Controller responsável por criar a "pessoa" (objeto Person).

Por exemplo: se dentro da sua API o Controller responsável por criar as pessoas se chame "Pessoa", é esse nome que vai colocar.
Utilizando o método
Para chamar esse método e esperar o resultado, você pode fazer o seguinte:
// Método para criar a pessoa e enviar para a Web API
public async void CreatePerson()
{
   // Cria um objeto "Person"
   var person = new Person()
   {
       ID = 1,
       FirstName = "Pedro",
       Age = 10
    }

    // Cria a pessoa e armazena o resultado
    var isOK = await CreatePersonAsync(person);

    // Verifica se obteve sucesso
    if(isOK)
    {
        // Pessoa criada com sucesso
    }
}

Note que o método precisa ser async, pois dentro dele iremos chamar o
  método async que criamos anteriormente para criar a pessoa na  Web
  API. Além disso, utilizamos a diretiva await para esperar o método
  executar e retornar.
Comment: E como é que eu posso adicionar headers no seu código ?
Comment: Já tem um header adicionado na seguinte linha: client.DefaultRequestHeaders.Accept.Add(). Pode adicionar mais da mesma forma.
Comment: Muito obrigado pela ajuda.
Comment: @PedroAzevedo Alterei algumas coisas na resposta. Desaclopei o código que estava criando o objeto Person de dentro do método http e coloquei um exemplo de uso do método e da forma mais "correta" para fazer o que deseja.
Comment: Qual é a referencia  que se tem de usar para usar o HttpClient?
Comment: O using é esse: using System.Net.Http;
Comment: No meu condigo não consigo usar esse using
Comment: Qual tipo de projeto você está utilizando? WPF, Asp.Net, WinForms?
Comment: console .net mas não sei o porque de não aparecer
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/64360/discussion-between-perozzo-and-pedro-azevedo).
Comment: ainda não tenho
Comment: Fala pelo chat.


Cointegration testing with a dummy variable

Question: I have the model:
$y_t = \alpha + \beta_1 x_t + \beta_2 D_t x_t + \epsilon_t$
With $y_t$ and $x_t$ as $I(1)$ processes, and $D_t =1$ during a large financial crisis, $D_t = 0$ during non-crisis periods.
I have been asked to test this equation for cointegration. When I test whether $\hat{\epsilon}_t$ is $I(0)$ as you would in the 2-step Engle-Granger methodology, which test am I using? I've heard that ADF is biased under 2-step Engle-Granger. *

*Third link in the Google search. When the word document opens go to page 3 and look for the paragraph that begins with "The initial studies ..."
Comment: I did not realise that you had edited your question. My answer below is for the question as you had originally set up. The answer to your updated question requires a substantially different discussion of time-varying cointegration models. I suggest you roll back this question to its earlier form, and ask make a new question out of the current version.
Answer: A few clarifications first.

When you say that the dummy is 1 for exactly half the observations, that is clearly a "dummy" example, since it is unlikely that the regime shift happened exactly half-way through your sample. In a realistic scenario, you'd have to build the possibility of a break in the intercept and/or slope at an unknown data inside your sample.
If however you are certain that the break date occurs at the time that you think it does, then no further adjustment needs to be made, and you can follow the two-step Engle-Granger procedure to test for cointegration. This is highly inadvisable though, unless this is homework.
The issue of the critical values of the ADF is well-known and would affect the test of cointegration even in the absence of regime shifts. The Engle-Yoo critical values should be used in all cases.
What does cointegration mean in the context of the equation that you have set up? Recall that in the standard case, Engle-Granger residual-based tests of cointegration have no cointegration as their null, and the alternative is cointegration, that is, the existence of a cointegrating vector (a linear combination of the I(1) variables that is I(0)).
In this context, the null remains that the variables are not cointegrated, but the alternative now is existence of a cointegrating vector that potentially changes at the estimated break date, that is, there is a structural change in the cointegrating relationship at the data of the structural break. Note that there is a regime shift both under the null and the alternative hypothesis.

The appropriate reference here is the paper by Gregory and Hansen, which discusses residual based tests of cointegration in the presence of regime shifts.
Standard cointegration model
Consider the simple cointegration model
$$
Y_{1t} = \beta_0 + \mathbf{Y}_{2t}'\boldsymbol{\beta} + \varepsilon_t
$$
where $\mathbf{Y}_{2t}$ is an I(1) $m$-vector, and $\varepsilon_t$ is I(0). In the simplest case, $m=1$. The standard tests of cointegration estimate the above relationship by OLS and conduct tests of unit roots (where the null is that there is a unit root in the process) on the estimated residuals, $\hat{\varepsilon}_t$.
Regime-shift cointegration model
Now consider the model that you are interested in
$$
Y_{1t} = \beta_0 + \mathbf{Y}_{2t}'\boldsymbol{\beta} +\boldsymbol{1}_{\left[t \geq \tau\right]}\left(\beta_0^\dagger + \mathbf{Y}_{2t}'\boldsymbol{\beta}^\dagger\right)+ \varepsilon_t
$$
Note that the breakpoint is fixed at $\tau$, but is unknown. Just like before, $\varepsilon_t$ is I(0).
Testing in the regime-shift cointegration model
Following exactly the procedure in the non-regime shift case, we estimate this model by OLS, and compute the residuals $\hat{\varepsilon}_t$. Then we form tests of unit roots in the errors, considered at the fixed break date $\tau$ -- the $Z_\alpha(\tau)$, $Z_t(\tau)$, and the $ADF(\tau)$ tests. The construction of these test statistics is given on pages 104-105 of Gregory and Hansen -- there are no differences to the standard case with no regime shift.
The next step, however, is new, in that, the statistic for the sample is computed as the minimum of the statistics computed over all the possible break dates in the sample (trimmed to exclude the edges) in order to date the break. So,
$$
\begin{align}
Z_t &= \inf_\tau Z_t(\tau) \\
Z_{\alpha} &= \inf_\tau Z_{\alpha}(\tau) \\
ADF &= \inf_\tau ADF(\tau) \\
\end{align}
$$
This additional step adds an order of complexity, and critical values are no longer available in closed form and are difficult even to simulate.There is a great deal of theory on these tests, see for example, this comprehensive review by Pierre Perron.
In case you are interested in implemeting these tests, Bruce Hansen makes all the codes available on his website accompanying the paper, including newly added R codes. Note also that the Gregory and Hansen paper has a fully worked application of these tests.


Remove jquery CSS

Question: When i add drupal_add_library('system', 'ui.accordion'); to my template.php, 3 jquery css files are loaded, but i can't remove them with $css_to_remove[] = drupal_get_path('misc','ui').'/jquery.ui.core.css'; (i tried some paths, but none worked).
Can anyone tell me how to remove CSS files loaded by jquery libraries? Thanks
Answer: This code will help you. Add it to your template.php:
function THEME_NAME_css_alter(&$css) {
  // List of disabled drupal default css files.
  $disabled_drupal_css = array(
    // Remove jquery.ui css files.
    'misc/ui/jquery.ui.core.css',
    'misc/ui/jquery.ui.theme.css',
  );

  // Remove drupal default css files.
  foreach ($css as $key => $item) {
    if (in_array($key, $disabled_drupal_css)) {
      // Remove css and its altered version that can be added by jquety_update.
      unset($css[$css[$key]['data']]);
      unset($css[$key]);
    }
  }
}

If you want to remove some other css - just print_r $css variable to get its name and add it to $disabled_drupal_css.
Comment: Many thanks for your answer, it works perfectly. How is this different from `$css_to_remove[] = drupal_get_path('module','ckeditor').'/ckeditor.css';`?
Comment: If you want remove css styles from CKeditor you can add line: $disabled_drupal_css[] = drupal_get_path('module','ckeditor').'/ckeditor.css';
Answer: You have to use exactly the same name as the stylesheet you want to remove.
You could do that even in your theme .info file. The file does not need to exist, it is enough if you just add this line there:
stylesheets[all][] = jquery.ui.core.css

Remove jquery CSS