new datetime - only one instance at a time?

Question: How can I display 3 different datetime objects on one page? The code below will only return the server date (first item) and dismiss all others.
Purpose of this script is to show the current date and time of the users location, including daylight saving time (meaning, the actual time of the specific place, not just GMT + whatever timezone they are supposedly in).
$server_datetime = new DateTime();  //located in America/New_York timezone - GMT-5
echo "Current Server DateTime: " . $server_datetime->format('Y-m-d H:i:s');

echo "
";

$usersTimezone1 = 'Europe/London';  // GMT-0
$user_datetime1 = new DateTime(new DateTimeZone($usersTimezone1) );
echo "London User DateTime: " . $user_datetime1->format('Y-m-d H:i:s');

echo "
";

$usersTimezone2 = 'Asia/Shanghai';  // GMT+8
$user_datetime2 = new DateTime(new DateTimeZone($usersTimezone2) );
echo "Shanghai User DateTime: " . $user_datetime2->format('Y-m-d H:i:s');

echo "
";

Comment: Turn on error reporting
Comment: `Message: DateTime::__construct() expects parameter 1 to be string, object given` the DateTimeZone object should be the second parameter.
Answer:
Message: DateTime::__construct() expects parameter 1 to be string,
  object given

the DateTimeZone object should be the second parameter.
$server_datetime = new DateTime();  //located in America/New_York timezone - GMT-5
echo "Current Server DateTime: " . $server_datetime->format('Y-m-d H:i:s');

$usersTimezone1 = 'Europe/London';  // GMT-0
$user_datetime1 = new DateTime( 'now', new DateTimeZone($usersTimezone1) );
echo "London User DateTime: " . $user_datetime1->format('Y-m-d H:i:s');

$usersTimezone2 = 'Asia/Shanghai';  // GMT+8
$user_datetime2 = new DateTime( 'now', new DateTimeZone($usersTimezone2) );
echo "Shanghai User DateTime: " . $user_datetime2->format('Y-m-d H:i:s');

Comment: my hero... I knew it was something small ;)
Comment: but as per what _Sougata Bose_ said, turn on error reporting ;)
Comment: did that already, but my whole page died, resulting in a 500 error page, hence the error display was of no use. anyway, its sorted out now, thanks for the hand.
Comment: Well I'm glad it helped, can you please accept my post as the answer to your question.
Answer:    $server_datetime = new DateTime();  //located in America/New_York timezone - GMT-5
    echo "Current Server DateTime: " . $server_datetime->format('Y-m-d H:i:s');

    echo "
";

    date_default_timezone_set('Europe/London');
    $user_datetime = new DateTime();
    echo "London User DateTime: " . $user_datetime->format('Y-m-d H:i:s');

    echo "
";

    date_default_timezone_set('Asia/Shanghai'); // GMT+8
    $user_datetime2 = new DateTime();
    echo "Shanghai User DateTime: " . $user_datetime2->format('Y-m-d H:i:s');

    echo "
";

Output is:
    Current Server DateTime: 2017-03-14 06:22:59

    London User DateTime: 2017-03-14 05:22:59

    Shanghai User DateTime: 2017-03-14 13:22:59

Comment: Question: what if I want to base the usertime on the current server time? Eg. the server time '2017-01-01 13:00:00' is saved in my database, but now I want to display the equivalent time at that moment in timezone 'Asia/Shanghai', how would I do that? This doesnt seem to work:  `$user_datetime1 = new DateTime( $server_datetime, new DateTimeZone($usersTimezone1) );`
Comment: This may help you [converting a time to a different timezone with php](http://stackoverflow.com/a/17098897/2151290)
Answer: @Armitage2k try this:
<?php
$server_datetime = new DateTime();
echo "Current Server DateTime: " . $server_datetime->format('Y-m-d H:i:s');
echo "
";

$usersTimezone1 = 'Europe/London';  // GMT-0
$user_datetime1 = new DateTime();
$user_datetime1->setTimeZone(new DateTimeZone($usersTimezone1));
echo "London User DateTime: " . $user_datetime1->format('Y-m-d H:i:s');

echo "
";

$usersTimezone2 = 'Asia/Shanghai';  // GMT+8
$user_datetime2 = new DateTime();
$user_datetime2->setTimeZone(new DateTimeZone($usersTimezone2));
echo "Shanghai User DateTime:" . $user_datetime2->format('Y-m-d H:i:s');

echo "
";


Quick question about relation between Nullspace and Eigenspace

Question: I have a question about a note given in a linear algebra textbook. It is just given as a remark, with no proof or explanation so I want to make sure I understand it correctly.
First, it gives the definition of the eigenspace of A to be, The set, $$E_{\lambda}=\{{v \in \mathbb R^n : Av= \lambda v}\}$$
and it then notes, from this we can see that because $E_{0}=N(A)$, this $\rightarrow$ a matrix is singular if and only if $\lambda=0$  is an eigenvalue.
But I am still a little confused. If I am recalling correctly, a  transformation is singular if there exists a $v  \neq 0$ for which $T(v)=0$
I guess in this case it is in regard to if  a matrix is invertible or not?
I think I may be getting confused between the two differences ( if there is one) and the differences between talking about just A and a transformation in general.
Anyone have any advice /explanations for this?
Thank you!
Answer: A matrix $A$ is singular, as you recalled, if there exists a $v\neq 0$ for which $Av=0=0\cdot v$. This shows it is the same as saying $v$ is an eigenvector for the eigenvalue $0$. Thus
$$A\enspace\text{singular}\iff \ker A \neq\{0\}\iff 0\enspace\text{is an eigenvalue for}\enspace A.$$
Comment: I see, is this because v=0 cannot be an eigenvector itself?
Comment: Yes. If $v=0$ was accepted as an eigenvector, any value would be an eigenvalue. (For a similar reason, $1$ is not accepted as a prime number).


What Is The Limit Of The Sequence: $\frac{n^3}{{((3n)!)^\frac{1}{n}}}$

Question: What (if exists) the $\lim \limits_{n\to \infty}\dfrac{n^3}{{((3n)!)^\frac{1}{n}}}$?
I have no idea where to begin. Maybe I could use the ratio test? Please try to keep it as elementary as possible because we are only in the beginning of the course.
Thanks a lot.
Comment: A quick approach would be to use [Stirling's approximation](http://en.wikipedia.org/wiki/Stirling%27s_approximation).
Comment: @DavidMitra as always, thanks for your great help. unfortunately we haven't gotten to logarithm during the course yet.
Comment: @Anonymous: the idea is to use $x!\sim \sqrt{2\pi x}\left(\dfrac xe\right)^x$ with $x=3n$.
Answer: We use the fact that if $(a_n)$ is a sequence of positive numbers and if $\lim\limits_{n\rightarrow\infty}{a_{n+1}\over a_n}$ exists, then so does $\lim\limits_{n\rightarrow\infty}{\root n\of {a_n}}$ and the two limits are equal.
We apply this  to the sequence with terms $a_n={n^{3n}\over (3n)!}$.
We have:
$$
{a_{n+1}\over a_n} = {(n+1)^{3n+3}\over (3n+3)!}\cdot {(3n)!\over n^{3n}}
={(n+1)^3\over (3n+3)(3n+2)(3n+1) }\cdot {\Bigl({n+1\over n}\Bigr)^{3n} }
\quad\buildrel{n\rightarrow\infty}\over\longrightarrow\quad{e^3\over27}.
$$
Comment: @Anonymous $\bigl({n+1\over n}\bigr)^{3n} =\Bigl(\bigl(1+{1\over n}\bigr)^n\Bigr)^3$ tends to $e^3$. For the rational expression, expand the numerator and denominator and throw out negligible terms; you'll be left with $n^3\over27n^3$ (or divide every term in the numerator and denominator by $n^3$ after expanding everything).
Comment: @Anonymous This isn't what I suggested above, but gets the job done: $${(n+1)^3\over (3n+3)(3n+2)(3n+1)} ={n^3(1+{1\over n})^3\over 3n\bigl(1+{1\over  n}\bigr)\cdot3n\bigl(1+{2\over 3n}\bigr)\cdot 3n\bigl(1+{1\over3 n}\bigr) }={ (1+{1\over n})^3\over 27\bigl(1+{1\over n}\bigr) \bigl(1+{2\over 3n}\bigr) \bigl(1+{1\over3 n}\bigr) }. $$
Comment: $$\lim\limits_{n\rightarrow\infty}{n^3+2n\over 8n^3+5}
=\lim\limits_{n\rightarrow\infty}{ {1\over n^3}(n^3+2n)\over {1\over n^3}(8n^3+5)}
=\lim\limits_{n\rightarrow\infty}{{n^3\over n^3}+{2n\over n^3}\over {8n^3\over n^3}+{5\over n^3}}=\lim\limits_{n\rightarrow\infty}{ 1+ {2 \over n^2}\over8+{5\over n^3}}
=\lim\limits_{n\rightarrow\infty}{ 1+0 \over 8+0 }={1\over8}.$$(It might be better to just factor out $n^3$ from the numerator and denominator. Then you get to fourth expression immediately.)
Comment: could you please show a little more in-depth why ${(n+1)^{3n+3}\over (3n+3)!}\cdot {(3n)!\over n^{3n}}
={(n+1)^3\over (3n+3)(3n+2)(3n+1) }\cdot {\Bigl({n+1\over n}\Bigr)^{3n} }$
Comment: Sorry, but how do I develop this expression ${(n+1)^{3n+3}\over (3n+3)!}\cdot {(3n)!\over n^{3n}}=?$
Comment: @Anonymous$${ {(n+1)^{3n+3}\over(3n+3)!}\over{n^{3n}\over(3n)!}  }={(n+1)^{3n+3}\over (3n+3)!}\cdot{(3n)!\over n^{3n}}={\color{darkgreen}{(n+1)^{3n}}(n+1)^3\over (3n+3)(3n+2)(3n+1)\color{maroon}{(3n)!}}\cdot{\color{maroon}{(3n)!}\over \color{darkgreen}{n^{3n}}}.$$
Comment: @David Mitra You're amazing, thank you so much! :-)
Comment: @DavidMitra last thing actually, could you please show that $\frac{(n+1)^3}{(3n+3)(3n+2)(3n+1)}=\frac{n^3}{27n^3}$?
Comment: @Anonymous they aren't actually equal, but can you see that for the purposes of taking the limit they are essentially the same?
Comment: @Ragib Zaman why for the purpose of taking the limit they are essentially the same?
Comment: @David Mitra that was really nice :-)
Comment: @David Mitra I still would like to understand the "trick" you made in your previous argument; I expanded the expression $\frac{(n+1)^3}{(3n+3)(3n+2)(3n+1)}$ and got that it's equal to: $\frac{n^3+3n^2+3n+1}{27n^3+54n^2+33n+6}$ which isn't obviously $\frac{n^3}{27n^3}$; what are these "negligible terms" and why are they negligible?
Comment: @Anonymous It's the highest powers that count when taking a limit at infinity of a rational expression. Divide every term by $n^3$ (or, equivalently, factor out $n^3$ upstairs and downstairs). Once you've done this my remark about "negligible terms" should seem less cryptic...
Comment: @David Mitra sorry, but I want to be sure that I understand you as I'm sure it will happen a lot during the course; let's take a simpler expression: $\frac{n^3+2n}{8n^3+5}$; how do I divide every term by $n^3$ and how does it help me?
Comment: @David Mitra I can't stress how much I appreciate your time and willingness to help; you helped me a lot, THANKS!!!
Comment: @Anonymous You're very welcome; glad to help :)
Answer: Ok, since David posted the approach I was thinking about, I wanted to see (just for fun) if there are other ways to find the limit in a completely basic fashion.
There is! but this is a bit long, so I might skip some details.
First we state a few Lemmas:
Lemma A:
If $x_n$ is a monotonically increasing sequence, and converges to $L$, then for all $n$, $L \ge x_n$.
Similarly if $y_n$ is a monotonically decreasing sequence, and $y_n$ converges to $R$, then for all $n$, $R \le y_n$.
Proof: Left to the reader.
Lemma B:
$x_n = \left(1 + \frac{1}{n}\right)^n$ is a monotonically increasing sequence.
Proof: Consider $n$ copies of $1 + \frac{1}{n}$ and $1$ copy of $1$ and apply $\text{AM} \ge \text{GM}$.
$\square$
Lemma C:
$y_n = \left(1 + \frac{1}{n}\right)^{n+1}$ is monotonically decreasing.
Proof: Consider $n$ copies of $1 - \frac{1}{n}$ and $1$ copy of $1$ and apply $\text{AM} \ge \text{GM}$.
$\square$
Note that Lemmas B and C can also be proven using Bernoulli's inequality, though that might not be considered basic (but surely can be considered elementary). These proofs (including the above AM,GM proofs) have appeared on this site before, if I remember correctly.
Combining the above Lemmas, leads us to:
Proposition D:
$$ \left(1 + \frac{1}{n}\right)^{n+1} \ge e \ge \left(1 + \frac{1}{n}\right)^n$$
for all $n$.
Proof:  $x_n$ and $y_n$ of Lemmas B and C, both converge to $e$ and we now have the inequality by Lemma A.
Note that, you can define $e$ this way too. First, $y_n$ is convergent as it is monotonically decreasing and bounded below. That means that $x_n$ is convergent too and to the same limit. Call that limit $e$.
Using binomial theorem, one can show that $x_n \lt 3$, and so $e \le 3$ (this can probably be found in most textbooks which define $e$ as the limit of $x_n$).
$\square$
Now we come to the main result:
Proposition E
For all $n \ge 4$, we have that
$$ \left(\frac{n}{e}\right)^{n+8} \ge n! \ge \left(\frac{n}{e}\right)^{n-8}$$
Proof:
By induction on $n$.
The base case is easily verifed using $e \le 3$.
Let $A_n = \left(\frac{n}{e}\right)^{n+8}$. Then
$$\frac{A_{n+1}}{A_n} = (n+1)\frac{\left(1 + \frac{1}{n}\right)^{n+8}}{e} \ge n+1$$
using Proposition D.
Thus if $A_n \ge n!$, then $A_{n+1} \ge (n+1)!$.
Similary, if $B_n = \left(\frac{n}{e}\right)^{n-8}$, the we can show that
$B_{n+1} \le (n+1)B_n$ and by induction, $B_{n+1} \le (n+1)!$.
$\square$
Now we can apply Proposition E to your sequence to squeeze your term and get that the limit is $\frac{e^3}{27}$.
I will leave that to the reader.
Comment: the arithmetic mean of $1,2, \dots 3n$ should be $\frac{1+2+...+3n}{3n}$ and the geometric mean $\sqrt[3n]{1*2*3*...*3n}$?
Comment: @Anonymous: Actually I misread. I though that the denominator has the exponent of $\frac{1}{3n}$. This hint is not valid (at least the one I was thinking of). But there is another way without using logarithms (I think). Let me edit the answer.
Comment: @Anonymous: I have edited with another answer, which is completely basic, but let me warn you, it is long.
Comment: @DavidMitra: Thanks!
Comment: @Aryabhata First of all, thank you very much for the very in-depth proof, I really appreciate it! In Lemma B did you mean to write the following inequality: $\frac{1+n(n+\frac{1}{n})}{1+n} > \sqrt[n+1]{(1+\frac{1}{n})^n}$?
Comment: @Anonymous: Yes. And then manipulate that to show that $x_{n+1} \gt x_n$.
Answer: Stirling's approximation gives
$$
\lim_{n\to\infty}\frac1n(n!)^{1/n}=\frac1e\tag{1}
$$
Using $(1)$ yields
$$
\begin{align}
\lim_{n\to\infty}\frac{n^3}{{((3n)!)^{\frac1n}}}
&=\lim_{n\to\infty}\frac{1}{27}\left(\frac{3n}{((3n)!)^{\frac{1}{3n}}}\right)^3\\
&=\frac{1}{27}\left(\lim_{n\to\infty}\frac{1}{3n}((3n)!)^{\frac{1}{3n}}\right)^{-3}\\
&=\frac{1}{27}\left(\frac1e\right)^{-3}\\
&=\frac{e^3}{27}\tag{2}
\end{align}
$$

Alternate Proof of $\boldsymbol{(1)}$
$$
\begin{align}
\log\left(\lim_{n\to\infty}\frac1n(n!)^{1/n}\right)
&=\lim_{n\to\infty}\frac1n\sum_{k=1}^n\log\left(\frac kn\right)\\
&=\int_0^1\log(x)\,\mathrm{d}x\\[9pt]
&=-1\tag3
\end{align}
$$
which is equivalent to $(1)$.


I want to know a similar function for Array_contains in BigQuery. I am trying to get results for multiple values present in Array of Struct field

Question: I have a Array of Struct field containing values like- field_name= [1,2,3,4]
I want to identify rows where field_name NOT contains values 2 OR 3 in BigQuery
Sample Data: Assume I have 4 rows of data:
row_id = 1 , field_name = [1,2,3,4]
row_id = 2 , field_name = [1,2]
row_id = 3 , field_name = [3,4]
row_id = 4 , field_name = [4]
What I want- Expected Result: row_id = 4 , field_name = [4]
I tried with UNNEST and EXISTS, UNNEST gives output as row_id = 1, row_id = 2, row_id = 3 & row_id = 4
Answer: Consider below approach
select * from your_table t
where not exists (
  select value
  from t.field_name as value
  where value in (2,3)
)

if applied to sample data in your question - output is

if you would use where value in (1,2) - output were


Determinar a quantidade de vezes que um numero poderá se repetir em uma array

Question: Preciso criar um sistema de sorteio onde um determinado numero sera obrigado a aparecer 3 vezes em uma array.
Tem que possuir 9 posições aleatórias de 1 a 6 e somente um numero 1 pode repetir 3 vezes, os outros no máximo 2 vezes
Exemplo: array(1,2,1,3,5,3,6,5,1);
Da forma que pensei em trabalhar esta totalmente ineficiente, pois não tenho nenhum controle do numero que ira repetir, nem quantas vezes
$numeros_jogadas = rand(1, 6).",".rand(1, 6).",".rand(1, 6).",".rand(1, 6).",".rand(1, 6).",".rand(1, 6).",".rand(1, 6).",".rand(1, 6).",".rand(1, 6);

Comment: Poderia postar o que já tentou fazer?
Comment: Eu ia responder, mas não vi que era PHP e escrevi em C#. Mas se quiser dar uma olhada, o código tá aqui: https://dotnetfiddle.net/jWxK3t
Comment: @CypherPotato,CORRIGINDO - E quase o que preciso, so faltou determinar o numero que sera obrigado a repetir vou ver sua logica e tentar adaptar para o que preciso com as funçoes do PHP
Comment: Eu estava tentando de uma forma aleatória, mas depois percebi que a logica precisaria que um numero especifico repetisse , dai então eu fiquei perdido, vou editar e colocar o que tentei
Comment: @MarcosPaulo Na linha `gerado == 1` você pode substituir por qualquer número.
Comment: Você pretende fazer isso para outros números né? Por exemplo, número 1 se repete x, número 2 se repete y, etc...?
Comment: @CypherPotato, a ideia seria, mas creio que se eu consegir com apenas um numero ja me atende
Comment: Um número é **obrigado** a se repetir 3 vezes ou **até** 3 vezes?
Comment: Um numero e obrigado a repetir 3 vezes, poderia ser um numero especifico = 1
Answer: Uma idéia é já definir de início o número 3 vezes repetido e já inclui-los na array:
$num3 = rand(1, 6);
$array = array();
array_push($array,$num3,$num3,$num3);

Depois fazer um while para preencher as outras 6 posições com números aleatórios diferentes do número que já foi definido 3 vezes, e no meio usar um for para contar quantas ocorrências do novo número se encontra na array, e só inserir este novo número se não houver mais de 2 ocorrências dele. Veja o código completo com comentários explicativos:
<?php
function nums(){

   $num3 = rand(1, 6); // número que irá se repetir 3 vezes
   $array = array(); // declara a array
   // insere o valor nas 3 primeiras posições da array
   array_push($array,$num3,$num3,$num3);

   // enquanto a areray não tiver 9 posições
   while(sizeof($array) < 9){
      // número aleatório de 1 a 6
      $num = rand(1, 6);

      // se este número for diferente do número repetido 3 vezes
      // se for igual, o while continua rodando
      if($num3 != $num){

         // contador para contar ocorrências
         $conta = 0;

         // verifica ocorrências do número
         for($x = 0; $x < sizeof($array); $x++){
            if($array[$x] == $num) $conta++;
         }

         // se houver menos de 2 ocorrências
         // adiciona o número na array
         if($conta < 2) $array[] = $num;

      }

   }

   // randomiza a ordem dos elementos
   shuffle($array);

   // retorna a array
   return $array;
}

// printa a array na tela
print_r(nums());
?>

Veja o IDEONE
Depois que array estiver formada com as 9 posições, a linha shuffle($array); embaralha os elementos. Teste quantas vezes quiser e perceba que apenas 1 número possui 3 ocorrências, e o restante são diferentes e só conseguem se repetir no máximo 2 vezes.
Answer: Usando a ideia apresentada em C# pelo @CypherPotato eu fiz a implementação PHP.
A ideia é colocar em um loop pra gerar o array das 9 posições e ir conferindo a quantidade de valores já inseridos e só inserir caso ainda não tenha atingido o limite, caso seja adicionado o valor ao array o loop é incrementado em +1.
    $arr = array(1, 1, 1); //inicializa o array com o número obrigatório preenchido
    $i = 4; //inicia o inteiro controlador da quantidade de posições preenchidas no array

    //laço de repetição para garantir as 9 posições do array. O $i é incrementado sempre que for adicionado um valor ao array.
    while($i <= 9){
        $valor = rand(1, 6); //gera o valor randômico de 1 a 6

        //Verifica se já teve alguma ocorrência do valor gerado no array
        if(isset(array_count_values($arr)[$valor])){

            //caso o valor gerado não seja 1, verifica se já teve as 2 ocorrências para esse valor. Caso não tenha as 2 ocorrências, adiciona o valor ao array
            if(array_count_values($arr)[$valor] < 2){
                array_push($arr, $valor);
                $i++;
            }
        }else{
            //Se ainda não houver nenhuma ocorrência para o valor, adiciona ele ao array diretamente
            array_push($arr, $valor);
            $i++;
        }
    }

    shuffle($arr); //randomiza os valores do array

    print_r($arr);

O array_count_values conta as ocorrências de cada posição do array e agrupa, retornando o valor como um índice e a quantidade como valor desse índice. Exemplo:
$array = [1, 1, 3, 1, 2, 2];

O resultado do array_count_values seria
print_r($arr);

[
    1 => 3,
    2 => 2,
    3 => 1
]

Usando como exemplo esse outro array
$arr = ["banana", "maçã", "banana", "pêra", "banana", "pêra"];

Teriamos como resultado do array_count_values
print_r($arr);

[
    "banana" => 3,
    "maçã" => 1,
    "pêra" => 2
]

Comment: Provavelmente é a versão do php, tente mudar para `$arr = array(1, 1, 1);`
Comment: Obrigado @JrD eu estava tentando recriar aqui, mas sempre quebrando a cabeça, testando o codigo aqui, não sei pq local, ele roda normamente, mas no servidor da erro a array inicial   $arr = [1, 1, 1]; Sabe me dizer pq?
Comment: Tem mais detalhes do erro @MarcosPaulo?
Comment: So me fala que deu erro na linha 03
[22-Mar-2019 09:57:46 America/Sao_Paulo] PHP Parse error:  syntax error, unexpected '[' in /home/fxcompco/public_html/raspadinha/randon.php on line 3


Razor:  tag within conditional statement throwing error

Question: @if (Model.Property != null)
{
    <text>

    </text>
    Html.RenderPartial("~/Views/CustomView.cshtml", Model);
    <text> (line throwing error)

    </text>
}

Error: "The "text" element was not closed.  All elements must be either self-closing or have a matching end tag."
I struggle to understand why second set of <text> tags is returning that error. Any help to understand it would be appreciated.
Answer: In Razor, tags must be nested properly. <text>
</text> is not proper nesting.
I think in your case you simply should remove all the <text> and </text> tags:
@if (Model.Property != null)
{

        @Html.Partial("~/Views/InTimeTemplate/InputFormElements/ReadMore.cshtml", Model);

}

Which is equivalent to:
@if (Model.Property != null)
{

        @{
            Html.RenderPartial("~/Views/InTimeTemplate/InputFormElements/ReadMore.cshtml", Model);
        }

}

Partial will return the result, which will be rendered thanks to the @
RenderPartial will render it directly, but you need to introduce a C# block with @{ ... }
Comment: I've tried to do that. Removing `` tags is throwing "Cannot implicitly convert type 'void' to 'object' on HtmlHelper.RenderPartial. Everything is ok without `` tags.
Comment: @Chris My first version of the answer was wrong, I copy/pasted a bit too quickly, try the updated version.
Comment: Sorted. Still forgetting to enclose HtmlHelpers between curly brackets. Thanks
Answer: Bit too late but still:
Just as an example u can use "@:"
Like this:
@for (int t = 0; t < Model.TrainLines[i].Stations.Count; t++)
            {
                <circle id="pointA" cx="@stationCounter" cy="@trainLineCounter" r="3" />
               @: <text x="@stationCounter" y="@trainLineCounter" dy="30">A</text>
                stationCounter += 50;
            }


Nginx close keep-alive connection from php

Question: Hello Everybody
I have trouble with nginx server . I have configured nginx with keep alive connection.
keepalive_timeout  65;
And connect to server with persistent connection , i send many request to server in same connection .
I want to close persistent connection from php.
php exit and die command closes response , not connection . And client can resend to server request in same connection .
simply, i want to close persistent connection from php
I use this command ,
header('Connection:close');
But not affected , connection is still alive
How can close http connection from php
Comment: your question is not clear, what is the error ?
Comment: I connect to server from cliend and send request and php run this code.
header('Connection:close');

But this php code not close connection , the connection is still alive .

I am using persistent connection from client to server
Comment: can you show us the nginx config, the php code and php-fpm config (since you are using nginx I guess you are also using php-fpm)
Answer: I took SO long to find the answer to this.
In PHP you need to call:
fastcgi_finish_request();

Comment: I've been looking for this for hours.
Comment: Thank you! This solved a big issue we had with a payment interface and a redirect to the bank's web page.
Answer: From this servfault answer it seems you can try it by allowing this header in the nginx fastcgi handler.
fastcgi_pass_header Connection-close;

Comment: I am using this , but still connection is alive.
I use persistent connection
Comment: Do you have the "Connection: close" header in the HTTP response headers? with a space after `: `. Try with `fastcgi_pass_header Connection-close;`, show headers.


Which term describes a "stepwise" variable?

Question: Which term describes a "stepwise" variable? I.e. a variable that may only take sudden values (e.g. 0, 2/3 and 2), and has several observations at each of these values. The variable may indicate eg points in time.
The answer is not a discrete variable since these do not allow for decimal values. Nor is it a binned or grouped variable since there is no censoring.
Thank you.
Comment: What is the basis for your assertion that discrete variables "do not allow for decimal values"? (by which I assume you mean values that are not integers) ... it's perfectly possible for a discrete random variable to take values like 0, 2/3 and 2.
Answer: It is a categorical distribution. It is discrete since it can take a countable number of values. Discreteness is not about being integer, you can as well have your distinct values labeled by colors, names, letters, or anything you want. It's expected value is simply
$$ E(X) = \sum_{i=1}^k p_i x_i $$
for $k$ distinct outcomes $x_i$ occuring with probabilities $p_i$.


Programmatically loading Custom block in page/node preprocessor

Question: I've followed some previous solutions on DA to programmatically load a Custom block in my page preprocessor hook but nothing I try seems to be working.
Currently, my custom block is within Structure > Block Layout > Custom block Library under the name 'SGT Pricing Header' (Machine name: sgt_pricing_header, ID 12).
I have attempted loading it in the page preprocessor as well as the node preprocessor hooks.
Currently I have:
function THEME_preprocess_node(&$variables) {
    $block_entity = Drupal\block_content\Entity\BlockContent::load(12);// BLOCK_ID
    $block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'sgt_pricing_header');
    $variables['block_pricing_header'] = $block_view;
}

I have also used 'sgt_pricing_header' in place of the ID 2 with no success.
In the TWIG template, which is a paragraph template by the way, if that is relevant, I am simply trying to display the block with
{{ block_pricing_header }}

I referenced Programatically render a block in a twig template when trying to get this to work.
I also tried using Twig Tweak to display the block, without success.
{{ drupal_block('sgt_pricing_header') }}

Simply does nothing.
PHP Version: 5.6.32-1+ubuntu17.10.1+deb.sury.org+1
Drupal version: Lightning (lightning-8.x-2.17)
Not entirely certain what to try next other than simply hard code the block content into the template which I would prefer to avoid.
Answer: Rendering custom blocks with Twig tweak module can be done as follows (assuming the ID of your block is 12):
{{ drupal_entity('block_content', 12) }}

Answer: I think the problem here is that Drupal 8 has both block definitions (a.k.a. plugins) and block instances.  Both of which tend to be called blocks.  What is listed in the custom block library is a block definition. This is like what is done when a block is created with code.  It define the block but not the configuration.
An instance is the configuration data for a block.  It has the settings for a specific block.  E.g., title override, display title, region, and the like.
So, you are trying to render the block definition with code that requires an instance block.
How do you get an instance of a block to render?  The simplest way is to create a hidden region in your theme by adding a region line in the info file.  Something like "Hidden Blocks".
Add your custom (or code based) blocks to this region in the block placement screen.  I also tend to set the rules for where this can be displayed just to help keep these from being generated when not needed.
Once you do this, you should be able to render using the block id from the placement screen.  Note this can be different from the plug-in id on the custom block page if you have placed it more than one.
Comment: Ok, I used my original code, then added an 'instance' like you explained to the content region, configured it to appear on the content type I needed. Saved but then I disabled the block. My code now works :-) The block is appearing correctly. Many thanks. Marking this as the correct answer as it explains some needed theory and the fact that you need to add an instance. Thanks CG Monroe
Answer: Try this code by including EntityInterface:
// Block
use Drupal\Core\Entity\EntityInterface;
// the last part of the parameter is the block id
$block = \Drupal\block\Entity\Block::load('yourblockid');
$block_content = \Drupal::entityManager()
  ->getViewBuilder('block')
  ->view($block);
\Drupal::service('renderer')->renderRoot($block_content);

Comment: Thanks for response. Tried to implement but get and error stating the following:

Recoverable fatal error: Argument 1 passed to Drupal\block\BlockViewBuilder::view() must implement interface Drupal\Core\Entity\EntityInterface, null given, called in /home/mywebsite/public_html/docroot/themes/custom/mytheme/mytheme.theme on line 1088 and defined in Drupal\block\BlockViewBuilder->view() (line 70 of core/modules/block/src/BlockViewBuilder.php).

The use statement is at the top of the theme file and the code block is within the THEME_preprocess_paragraph(&$variables) hook.
Comment: Have you included the use Drupal\Core\Entity\EntityInterface;
See also: https://drupal.stackexchange.com/questions/219521/cant-render-a-block-due-to-recoverable-fatal-error/242962


Disable HDMI audio on tablet when using wired headset

Question: How can I disable HDMI audio output on tablet when using wired headset.
I would try
mgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
mgr.setWiredHeadsetOn(true);

and
mgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
mgr.setParameters("audio_devices_out_active=AUDIO_CODEC");

It didn't work :'(
Answer: Try with this permission in your manifest.
android.permission.MODIFY_AUDIO_SETTINGS.


Running IntelliJ in WSL2 - how to make keyboard shortcut ctrl+alt+arrows work

Question: My environment:
Windows 11 22000.493 -> Host OS
WSL 18.104.22.168
Ubuntu: 20.04.3 LTS -> Guest OS
IntelliJ: Build #IC-213.6777.52, built on January 28, 2022 -> Running inside WSL

I am running IntelliJ inside WSL as described here: https://learn.microsoft.com/en-us/windows/wsl/tutorials/gui-apps
I have configured my IntelliJ to use Windows Proper Redo keymap so that my shortcuts are the same as in the Windows environment.
All shortcuts seem to work as expected except the Navigation ones - Ctrl+Alt+Left/Right.

As shown in the screenshot - they are properly configured. If I switch the combination - they start to work, but I want to have them under Ctrl+Alt+Left/Right.
I read here IntelliJ Idea Ctrl+Alt+Left shortcut doesn't work in Ubuntu that Ctrl+Alt+Left/Right is interfering with Gnome but this is WSL and I have uninstalled Gnome completely by following https://askubuntu.com/questions/767577/how-can-i-remove-gnome-desktop-environment-without-messing-unity-de-ubuntu-16 and running
sudo apt-get remove --auto-remove ubuntu-gnome-desktop

Still there appear to be some settings left on my Ubuntu:
$ gsettings list-recursively | grep org.gnome.desktop.wm.keybindings | sort | grep Control
org.gnome.desktop.wm.keybindings cycle-panels ['<Control><Alt>Escape']
org.gnome.desktop.wm.keybindings cycle-panels-backward ['<Shift><Control><Alt>Escape']
org.gnome.desktop.wm.keybindings move-to-workspace-down ['<Super><Shift>Page_Down', '<Control><Shift><Alt>Down']
org.gnome.desktop.wm.keybindings move-to-workspace-left ['<Control><Shift><Alt>Left']
org.gnome.desktop.wm.keybindings move-to-workspace-right ['<Control><Shift><Alt>Right']
org.gnome.desktop.wm.keybindings move-to-workspace-up ['<Super><Shift>Page_Up', '<Control><Shift><Alt>Up']
org.gnome.desktop.wm.keybindings switch-panels ['<Control><Alt>Tab']
org.gnome.desktop.wm.keybindings switch-panels-backward ['<Shift><Control><Alt>Tab']
org.gnome.desktop.wm.keybindings switch-to-workspace-down ['<Super>Page_Down', '<Control><Alt>Down']
org.gnome.desktop.wm.keybindings switch-to-workspace-up ['<Super>Page_Up', '<Control><Alt>Up']

But none of them are bound to Ctrl+Alt+Left/Right.
I am out of ideas. How do I make the keyboard combination work in IntelliJ running inside WSL2?
Comment: Do other shortcuts with Ctrl+Alt (e.g. Ctrl+Alt+S for Settings) work there? What's your keyboard layout? Do you press left or right Alt (if you have one)?
Comment: Other shortcuts with Ctrl + Alt work as expected (e.g. Ctrl+Alt+S for Settings). I tried both left and right Ctrl + Alt combinations - none work with arrows.
I temporarily switched to Alt + Shift + Arrow for Navigate Back/Forward until I find a solution
Answer: You need to run WSL version >=56.1 as this version uses Microsoft Remote Desktop Client version 1.2.2924, which supports Ctrl+Alt+arrow key keyboard shortcuts.
https://github.com/microsoft/WSL/releases/tag/0.56.1
https://learn.microsoft.com/en-us/windows-server/remote/remote-desktop-services/clients/windowsdesktop-whatsnew#updates-for-version-122924
Answer: I don't known why. But if you reset this shutcut to other key. It'll work.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


How to use a Twig variable as View name in drupal_view() Twig Tweaks function?

Question: This works:
<code>{{ drupal_view('nursing_resource_blog_teasers', 'block_1') }
</code>
But this doesn't:
<code>{% set view_name = "nursing_resource_blog_teasers" %}
{{ drupal_view(view_name , 'block_1') }
</code>
It appears that drupal_view() isn't allowing a variable as the View name. Is there a way to make this work?
Answer: Solved it. I forgot about the tags in the field output.
This solved it for me:
<code>{% set view_name = content.field_blog_teaser_block|render|striptags|trim %}
</code>


GET Parameter View Scoped Bean

Question: I have a strange effect on my JSF2/richfaces 4 project. I use a viewscoped bean and a datascroller to view some data from my backing bean. The bean is viewscoped and to pass the figureId parameter I fire the preRenderView event.
<f:metadata>
    <f:viewParam name="figureId" value="#{pointEdit.figureId}" >
        <f:convertNumber pattern="###" />
    </f:viewParam>
    <f:event type="preRenderView" listener="#{pointEdit.init}" />
</f:metadata>

Displays fine, but when I click on the second site of the datascroller I get a nullponter exception for this line: <f:event type="preRenderView" listener="#{pointEdit.init}" />.
javax.el.ELException: /pointEdit.xhtml @17,66 listener="#{pointEdit.init}": java.lang.NullPointerException
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
    at com.sun.faces.facelets.tag.jsf.core.DeclarativeSystemEventListener.processEvent(EventHandler.java:128)
    at javax.faces.component.UIComponent$ComponentSystemEventListenerAdapter.processEvent(UIComponent.java:2477)
    at javax.faces.event.SystemEvent.processListener(SystemEvent.java:106)
    at com.sun.faces.application.ApplicationImpl.processListeners(ApplicationImpl.java:2102)
    at .....
Caused by: java.lang.NullPointerException
    at com.ebcont.gtv.ePrometheus.web.backingbean.PointEdit.init(PointEdit.java:74)  // <--first access to figure
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    ... 27 more

My Bean:
@ManagedBean
@ViewScoped
public class PointEdit implements Serializable {

    public void init() {
        FigureService figureService = Utils.getSpringBean(FigureService.class);
        figure = figureService .getById(figureId); // figureId will NOT be passed from GET
        pointListToDisplay = figure.getPoints();   // nullpointer :-(

Before I imported my new data it worked fine on my test figures.
Why is my figureId GET Parameter not found in the init function? With my testdata (5 figures) I never had a problem with this.
UPDATE:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:messages errorStyle="color:red" warnStyle="color:yellow" />
    <rich:tabPanel switchType="client">
        <rich:tab header="Punkte">
            <rich:panel>
                <f:facet name="header">
                    #{msg.pointEditDetail_figure_header }
                </f:facet>

                    <h:graphicImage url="/image?figureid=#{pointEdit.figure.id}"
                        style="border: solid 2px #013476;z-index: -2;">

                        <a4j:repeat value="#{pointEdit.points}" var="thepoi">
                            <h:panelGroup layout="block"
                                style="margin-top: -27px;top:#{thepoi.y}px; left: #{thepoi.x}px; background-image: url('images/poipin.png');background-repeat:none;width: 25px; height:27px; position:absolute; z-index: -0.9;display:none;"
                                styleClass="poi #{thepoi.id }">

                                    <a4j:repeat value="#{thepoi.labels}" var="poilabel">
                                        <h:panelGroup layout="block"
                                            styleClass="poilabel label#{thepoi.id}" style="display:none;">

                                                <h:outputText value="#{poilabel.locale.isoCode}:"
                                                    style="background-image: url('images/layerbackground.png'); background-repeat: both;" />
                                                <h:outputText value="#{poilabel.label.labelText}"
                                                    style="background-image: url('images/layerbackground.png'); background-repeat: both;"
                                                    rendered="#{not empty poilabel.label.labelText}" />
                                                <h:outputText value="Nicht verfügbar"
                                                    style="background-image: url('images/layerbackground.png'); background-repeat: both;"
                                                    rendered="#{empty poilabel.label.labelText }" />

                                        </h:panelGroup>
                                    </a4j:repeat>

                            </h:panelGroup>
                        </a4j:repeat>
                    </h:graphicImage>

                <h:commandButton value="#{msg.pointEditDetail_show_all_button}"
                    onclick="$('.poi').toggle()"
                    rendered="#{ not empty pointEdit.points}" />

                <h:button outcome="viewer.xhtml" value="#{msg.pointEditDetail_button_viewer}">
                    <f:param name="figureId" value="#{pointEdit.figure.id}"/>
                    <f:param name="zoom" value="1"/>
                </h:button>
            </rich:panel>

            <rich:panel>
                <f:facet name="header">
                    #{msg.pointEditDetail_points_header }
                </f:facet>
                <h:form>
                    <rich:dataTable value="#{pointEdit.points}" var="point"
                        id="pointtable" rows="10" rowKeyVar="rowId">

                        <rich:column>
                            <f:facet name="header">
                                #{msg.pointEditDetail_table_header_rowkey}
                            </f:facet>
                            #{rowId+1}
                        </rich:column>
                        <rich:column sortBy="#{point.id}" id="id"
                            sortOrder="#{pointEdit.pointIdOrder}">
                            <f:facet name="header">
                                <a4j:commandLink
                                    value="#{msg.pointEditDetail_table_header_point} #{msg.pointEditDetail_table_header_id }"
                                    render="pointtable" action="#{pointEdit.sortByPointId}" />
                            </f:facet>
                            #{point.id}
                        </rich:column>
                        <rich:column>
                            <f:facet name="header">
                                #{msg.pointEditDetail_table_header_x}
                            </f:facet>
                            #{point.x }
                        </rich:column>
                        <rich:column>
                            <f:facet name="header">
                                #{msg.pointEditDetail_table_header_y}
                            </f:facet>
                            #{point.y }
                        </rich:column>

                        <rich:column filter="#{pointEdit.labelFilter}">
                            <f:facet name="header">
                                #{msg.pointEditDetail_table_header_label}

                                <h:inputText value="#{pointEdit.labelFilterText}">
                                    <a4j:ajax event="change" render="pointtable" execute="@this" requestDelay="700"
                                        ignoreDupResponses="true"/>
                                </h:inputText>
                            </f:facet>
                            <a4j:repeat var="pointlabel" value="#{point.labels}">
                                #{pointlabel.locale.isoCode}:
                                <h:outputText value="#{pointlabel.label.labelText}"
                                    rendered="#{not empty pointlabel.label}" />
                                <h:outputText value="#{msg.pointEditDetail_not_available}"
                                    rendered="#{empty pointlabel.label}" />

                            </a4j:repeat>
                        </rich:column>
                        <rich:column style="text-align:center">
                            <f:facet name="header">
                                #{msg.pointEditDetail_table_header_show_point}
                            </f:facet>
                            <h:selectBooleanCheckbox styleClass="pinchk#{point.id}"
                                value="false"
                                onchange="checkboxdrivendisplay(this,'.#{point.id }');checkboxdrivendisplay(this,'.lblchk#{point.id }');"
                                onmouseover="jQuery('.#{point.id }').show(); jQuery('.lblchk#{point.id }').show();"
                                onmouseout="checkboxdrivendisplay(this,'.#{point.id }');checkboxdrivendisplay(this,'.lblchk#{point.id }');">

                            </h:selectBooleanCheckbox>
                        </rich:column>
                        <rich:column style="text-align:center;">
                            <f:facet name="header">
                                #{msg.pointEditDetail_table_header_show_label}
                            </f:facet>
                            <h:selectBooleanCheckbox style="display:none"
                                styleClass="lblchk#{point.id}" value="false"
                                onclick="checkboxdrivendisplay(this,'.label#{point.id }');"
                                onmouseover="jQuery('.label#{point.id}').show();"
                                onmouseout="checkboxdrivendisplay(this,'.label#{point.id }');">
                            </h:selectBooleanCheckbox>
                        </rich:column>
                        <rich:column>
                            <f:facet name="header">
                                #{msg.pointEditDetail_table_header_edit_label }
                            </f:facet>

                                <h:link outcome="labelEdit.xhtml" value="#{msg.pointEditDetail_table_edit_label}">
                                    <f:param name="pointId" value="#{point.id}"/>
                                </h:link>

                        </rich:column>
                        <rich:column>
                            <f:facet name="header">
                                #{msg.pointEditDetail_table_header_tag }
                            </f:facet>
                            <a4j:repeat var="tag" value="#{point.tags}" varStatus="index">
                                <h:link outcome="search.xhtml" value="#{tag.tag}">
                                    <f:param name="tags" value="true" />
                                    <f:param name="labels" value="false" />
                                    <f:param name="legends" value="false" />
                                    <f:param name="query" value="#{tag.tag}" />
                                </h:link>
                            </a4j:repeat>
                        </rich:column>
                        <rich:column>
                            <f:facet name="header">
                                #{msg.pointEditDetail_table_header_edit_tag }
                            </f:facet>

                                <h:link outcome="tagEdit.xhtml" value="#{msg.pointEditDetail_table_edit_tag}">
                                    <f:param name="pointId" value="#{point.id}"/>
                                </h:link>

                        </rich:column>
                        <f:facet name="footer">
                            <rich:dataScroller for="pointtable" />
                        </f:facet>
                    </rich:dataTable>

                </h:form>
            </rich:panel>
        </rich:tab>
        <rich:tab header="Daten">
            <h:form>
                <rich:panel id="legendpanel">
                    <f:facet name="header">
                        #{msg.pointEditDetail_legend_edit_header }
                    </f:facet>

                    <h:outputText rendered="#{not empty pointEdit.legendeStatus}"
                        value="#{msg.pointEditDetail_legend_edit_success}" />

                    <h:inputTextarea value="#{pointEdit.legende}" cols="40" rows="8"/>

                    <a4j:commandButton value="#{msg.pointEditDetail_legend_edit_button} "
                        render="legendpanel legende" action="#{pointEdit.editLegend}" />
                </rich:panel>
            </h:form>

            <h:form>
                <rich:panel name="labelPanel">
                    <f:facet name="header">
                        #{msg.pointEditDetail_label_edit_header }
                    </f:facet>
                    <rich:dataTable value="#{pointEdit.labels}" var="label"
                        id="labelTable" rows="10">
                        <rich:column>
                            <f:facet name="header">
                                Id
                            </f:facet>
                            #{label.id }
                        </rich:column>
                        <rich:column>
                            <f:facet name="header">
                                #{msg.pointEditDetail_label_edit_table_header}
                            </f:facet>
                            <rich:inplaceInput value="#{label.labelText }" showControls="true" layout="block" style="width: 98%"
                                 required="true">
                                 <a4j:ajax event="change" render="pointtable" listener="#{pointEdit.editLabel(label.id) }" />
                            </rich:inplaceInput>
                        </rich:column>

                        <f:facet name="footer">
                            <rich:dataScroller for="labelTable" />
                        </f:facet>
                    </rich:dataTable>

                </rich:panel>
            </h:form>

        </rich:tab>
        <rich:tab header="Verknüpfen">
            <ui:include src="linkFigures.xhtml" />
        </rich:tab>
    </rich:tabPanel>

Comment: PS: The first data can be loaded successfully! So it looses the figureId when scrolling the pages.
Answer: You need to either pass that parameter as <f:param> in the command link so that it retains in the subsequent request:
<h:commandLink>
    <f:param name="figureId" value="#{pointEdit.figureId}" />
</h:commandLink>

or to check in the init() if FacesContext#isPostback() equals to false before proceeding (so that it only runs on a fresh new GET request, not in the subsequent postbacks as the bean is view scoped and the properties are already been set anyway):
public void init() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // ...
    }
}

Comment: Thanks a lot for the quick answer! The datascroller does a post, but i do not understand why the ViewScoped bean forgets the figureId from the first run. When i enter the init() method for the first time figureId is set successfully. After the post it is not initialized, but due to the viewscope the value should be the same like from the first method call. Maybe i have an understanding problem for this scope. :-/
Comment: It does not forget the `figureId`. It has **received** an empty/null `figureId`. The `` runs on every request, not on first request only.
Comment: Ah now i get it. Thank you very much!
Comment: I checked my bean today with a breakpoint in the init() method and all properties are null. when i first enter the site i get the figure id and all seems correct. when i scroll one page further it seems that i get a new bean. even the pointlist queried the first time is empty. :-(
Comment: Another interesting point is that when i change the scope to session it works. :-/
Comment: So the bean is recreated? That can happen when something has failed in partial view state saving or you're returning non-null from action methods. Are you using `binding` anywhere in the view? Are you using JSTL ``, ``, etc tags anywhere in the view? You should return `null` or `void` from action methods and you could try disabling partial state saving in `web.xml`.
Comment: No Binding, and no of the JSTLs. All action methods are voids. Partial state disabling you described (http://stackoverflow.com/questions/6914662/jsf-2-0-viewscoped-life-cycle) didn't work either. It is quite strange that it is a specific figure which makes the problems. My old examples work like a charm. Anything else i could check?
Comment: Shall i post the whole page & bean?
Comment: I start to recall that `` has some specific problems similar to this. Try removing it, just to test. I'll look for any references in the meanwhile.
Comment: When i remove it i get the whole list which works on the first refresh. But many things in my other rich:Panels do not work propertly. Very strange, but maybe i overloaded the page.
Comment: I have another theory. The new images (figure) are larger and the entity contains it as byte[]. Can that be the problem? That the viewstate is too large?
Comment: The view state does not contain the model values. Your key problem is after all that the view scoped bean get trashed and recreated upon every datascroller link call. This is not normal. I suggest to create a brand new simple test page with a small 1-column table and a simple view scoped bean with `List` as test data and see if you can still reproduce this (bean get recreated). If that is the case, I'd report a bug to the RichFaces guys along with the testcase.
Comment: Ok then i'll test this again tomorrow to be sure and file the bug. Thank you so much for your support!
Answer: My new test images where 5 times larger then the images i got 4 testing. In my ViewScoped bean i had the figure as property so the whole byte[] had to be serialized.
After removing this design flaw it works again and also explains why the new images cause troubles!

GET Parameter View Scoped Bean


Problems with active-trails

Question: I have played with Menu Trail by Path and Menu Position, but none worked well with a Views-generated listing acting as a navigation menu.
Imagine the following scenario:

On the left side there is Views generated block of linked taxonomy terms.
When clicked, the link fills the main content area with a listing of nodes tagged with the given taxonomy term. The activated term link gets active-trail class - so far so good.
When you click a node link though, the node opens, but now - the active-trail is gone.

The complicating factor might be that my taxonomy is localized (each term has a translation within same vocabulary). But I believe there is a solution to that... Anyone?
Answer: It's important to understand that taxonomy is not a menu system, the menu system is.  There are ways to make the menu system mirror taxonomy, but they are separate systems.  Taxonomy_menu might be able to help.

Problems with active-trails


Use linq to iterate through large DB tables

Question: I have two tables: Foo and Bar. For each row in Foo, I now want to add a row in Bar which references the respective Foo record. Foo will likely contain several millions of records.
Normally this answer would have been perfect: linq to sql - loop through table data and set value. But as it says on the tin, using the following line is not particularly ideal for large tables.
List<User> users = dc.Users.ToList();

Since caching the entire table in a List<> is not going to work, what other options do I have? Is there an elegant way to "page through" the records, for instance? Since I am quite sure that this is a relatively common problem, I think it's likely that there is a best practice for this too. I have not been able to find it, however.
Comment: Is there any reason at all why you need to do this in code? Batch processing like this is generally much easier and faster in the database, using a simple SQL query or stored procedure.
Comment: It is not clear what you want to do with this data in tables?
Comment: Why can't you use a `foreach` instead of using `ToList()`? And if you need to read million of rows, it is normally better (if possible) to disable `ObjectTrackingEnabled`
Answer: Your talking about several million rows of data, then Linq is not your friend.
Consider using a stored procedure or, if you like, DbContext.ExecuteCommand.
Both will result in a huge performance gain.
Comment: This is the answer... you want that operation to happen within the DB.
Answer: You can work with predefined batches using .Skip() and .Take() methods. Another thing to consider is using a trigger so that you don't need to worry about the second table at all.


$\mathbb{R}^2$ rotations

Question: Considering $\mathbb{R}^2$ for the two rotations $g_1,g_2$ with centers of rotation $x_1$ and $x_2$ by $\theta_1$ and $\theta_2$ I have to show that $g_1\circ g_2$ is a rotation iff $\theta_1+\theta_2\notin\{0,2\pi\}$, the rotation angle is given by $\theta_1+\theta_2\mod 2\pi$ and I have to calculate the center of rotation.
A rotation is defined by $v\mapsto d_\theta(v-x)+x$ with $d_\theta=\begin{pmatrix}\cos(\theta) & -\sin(\theta) \\ \sin(\theta) & \cos(\theta)\end{pmatrix}$.
Also if $\theta_1+\theta_2\in\{0,2\pi\}$, $g_1\circ g_2$ is a translation by identity. Is there a nice proof of this?
Comment: I am not sure if I understand the question correctly.

But if the case is general true - it should be true for $x_1 = \vec{0}$ and $x_2 = \vec{0}$ - but in that case you always end up with a rotation, given by $R(\theta_1) R(\theta_2) = R(\theta_1 + \theta_2)$...
Comment: Yep - I did not understand the question. I now understand it...
Answer: So $$g_1(g_2(v)) = d_{\theta_1}(d_{\theta_2}(v-x_2)+x_2-x_1) + x_1 = d_\theta(v) + y ,$$ where $\theta = \theta_1 + \theta_2$, and $y = d_{\theta_1}(d_{\theta_2}(-x_2) + x_2-x_1) + x_1 $.  If $\theta$ is a multiple of $2\pi$, then $d_{\theta}$ is the identity, and hence $g_1 \circ g_2$ is a translation.  If $\theta$ is not a multiple of $2\pi$, then $I - d_\theta$ is an invertible matrix, and hence there exists a vector $z$ such that $z - d_\theta(z) = y$, and hence
$$ g_1(g_2(v)) = d_\theta(v-z) + z .$$
By the way, to show that $I - d_\theta$ is invertible when $\theta$ is not a multiple of $2\pi$, show that there is only one solution to $(I - d_\theta) w = 0$.
Answer: In the context of your question, the nicest proof is to insert the coordinates of the column vectors $v$ and $x$ into the formula for the rotation $v \mapsto d_\theta(v-x)$, and calculate.
Comment: There are other proofs available in synthetic geometry, starting from synthetic definitions of translations and rotations, but the context of your question is analytic geometry.
Comment: Yes I already did that and I applied the definition of $g_1\circ g_2(v) = g_2(g_1(v)) = d_{\theta_2}((d_{\theta_1}(v-x_1)+x_1)-x_2)+x_2$ and calculated, it gets very big and I get to no nice result in the end...
Answer: There is a standard way to combine rotation and translation by $(a, b)'$:
$$ A_\theta=\begin{pmatrix}\cos(\theta) & -\sin(\theta) & a \\ \sin(\theta) & \cos(\theta) & b \\ 0 & 0 & 1 \end{pmatrix} $$
which is applied to the vector $\begin{pmatrix}x & y & 1 \end{pmatrix}' $
You can first apply the translation, then rotation, then translation (each of those amounts to a matrix multiplication) and see what the result looks like.

$\mathbb{R}^2$ rotations


MongoDb How to group by month and year from string

Question: I am having field dateStr in collection
  {  ....    "dateStr" : "07/01/2020" .... }
  {  ....    "dateStr" : "07/01/1970"   .... }

I want to group by month and year from dateStr field
I have tried
    db.collection.aggregate(
       {$project : {
              month : {$month : new Date("$dateStr")},
              year : {$year :  new Date("$dateStr")}
          }},
        {$group : {
                _id : {month : "$month" ,year : "$year" },
              count : {$sum : 1}
        }})

Output :
{
"result" : [
        {
            "_id" : {
                "month" : 1,
                "year" : 1970
            },
            "count" : 2
        }
    ],
    "ok" : 1
}

But I am having two years 1970,2020. Why I am getting single record?
Answer:
You cannot use the date aggregation operators on anything else that is tho a Date object itself. Your ultimate best option is to convert these "strings" to proper Date objects so you can query correctly in this and future operations.
That said, if your "strings" always have a common structure then there is a way to do this with the aggregation framework tools. It requires a lot of manipulation thought that does not makes this an "optimal" approach to dealing with the problem. But with a set structure of "double digits" and a consistent delimiter this is possible with the $substr operator:
db.collection.aggregate([
   { "$group": {
       "_id": {
           "year": { "$substr": [ "$dateStr", 7, 4 ] },
           "month": { "$substr": [ "$dateStr", 4, 2 ] }
       },
       "count": { "$sum": 1 }
   }}
])

So JavaScript casting does not work inside the aggregation framework. You can always "feed" input to the pipeline based on "client code" evaluation, but the aggregation process itself does not evaluate any code. Just like the basic query engine, this is all based on a "data structure" implementation that uses "native operator" instructions to do the work.
You cannot convert strings to dates in the aggregation pipeline. You should work with real BSON Date objects, but you can do it with strings if there is a consistent format that you can present in a "lexical order".
I still suggest that you convert these to BSON Dates ASAP. And beware that the "ISODate" or UTC value is constructed with a different string form. ie:
new Date("2020-01-07")

Being in "yyyy-mm-dd" format. At least for the JavaScript invocation.
Comment: Thank you . It is helpful . It is working . I agree with your points . I will make proper grouping based on bson date object .
Comment: @Ramesh Good news. Then you can use the [date aggregation operators](http://docs.mongodb.org/manual/reference/operator/aggregation-date/) as was shown in your original code example.


Prove $a^{\frac{\phi(mn)}2} \equiv 1\pmod {mn}$

Question: I want to show that given $\gcd(m,n)=1$ with $m,n \gt2$ and $\gcd(a, mn)=1$, then $a^{\frac{\phi(mn)}2} \equiv 1\pmod {mn}$, where $\phi(mn)$ is the Euler Totient function.
My approach started using Euler's theorem, given $\gcd(a, n)= 1$ then $ a^{\phi(n)} \equiv 1\pmod {n}$. And since $(m,n)=1$ then: $$a^{\phi(mn)} \equiv 1\pmod {mn}$$
I just cannot seem to get the $\frac12$ factor to appear. What I tried doing was just raising both sides to the $\frac 12$
$$a^{\phi(mn)} \equiv 1\pmod {mn} \Rightarrow a^{\frac{\phi(mn)}2} \equiv 1^{\frac12}\pmod {mn} \equiv 1\pmod{mn}$$
But I somehow feel this is wrong. So another way I tried was again with Euler's theorem:
$$a^{\phi(n)} \equiv 1\pmod {n} \Rightarrow (a^{\phi(m)})^{\phi(n)} \equiv 1\pmod {n} \Rightarrow a^{\phi(m)\phi(n)} \equiv 1\pmod {n} $$
$$a^{\phi(m)} \equiv 1\pmod {m} \Rightarrow (a^{\phi(n)})^{\phi(m)} \equiv 1\pmod {m} \Rightarrow a^{\phi(n)\phi(m)} \equiv 1\pmod {m} $$
Multiplying one by the other yields:
$$a^{2\phi(m)\phi(n)} \equiv 1\pmod {mn} \Rightarrow a^{2\phi(mn)} \equiv 1\pmod {mn}$$
Or using the CRT:
$$a^{\phi(m)\phi(n)} \equiv 1\pmod {mn} $$
From here I have no idea on where to go or what to try, I was thinking perhaps something related to Wilson's Theorem to make the $\frac12$ factor appear, but since m and n may not be prime, they are just coprime, I don't know if I can use that. Am I going in the right direction?
Comment: Please search to avoid addinge dupe questions, Here they can be quickly [located by approach0](https://approach0.xyz/search/?q=%24a%5E%7B%5Cfrac%7B%5Cphi%5Cleft(mn%5Cright)%7D%7B2%7D%7D%5Cequiv1%5Cpmod%5Cleft%5C%7Bmn%5Cright%5C%7D%24&p=2).
Answer: Hint: Prove that $\phi(N)$ is even for all $N\geq 3$.  So both $\phi(m),\phi(n)$ are even, hence you have the spare factor of 2: $\operatorname{lcm}(\phi(m),\phi(n))\mid \frac12\phi(m)\phi(n)$.
Comment: No.  $\phi(m)$ divides $\phi(m)\frac{\phi(n)}{2}$ and $\phi(n)$ divides $\frac{\phi(m)}{2}\phi(n)$.  So $a^{\phi(m)\phi(n)/2}\equiv(a^{\phi(m)})^{\phi(n)/2}$ is $1$ mod $m$ and similarly mod $n$, and CRT gives the result.
Comment: So since $\phi(mn)$ is always even I can divide by $2$ without any restrictions just because I have the spare factor of $2$?
Comment: Please strive not to add more dupe answers to FAQs. Here they can be quickly [located by approach0](https://approach0.xyz/search/?q=%24a%5E%7B%5Cfrac%7B%5Cphi%5Cleft(mn%5Cright)%7D%7B2%7D%7D%5Cequiv1%5Cpmod%5Cleft%5C%7Bmn%5Cright%5C%7D%24&p=2).
Comment: @BillDubuque $m,n$ not primes and all results seems to be asking for prime case (or question 3491175 with 3n and 9n a very specific version)?
Comment: See [this answer](https://math.stackexchange.com/a/3433521/242) in the linked dupe (there are also many other dupes - it's a FAQ).


Confusion about bounded sequences

Question: Closed and bounded intervals are compact. Let $a,b\in R$, then the metric space $([a,b], usual  metric)$ is compact.
In the proof, it was said that $(x_{n})_{n}$ is a sequence in $[a,b]$. Then $(x_{n})_{n}$ is bounded.
I am unsure of why this last part is true. Why is the sequence bounded? It was not stated that it was convergent. Is it to do with the interval or the closed subset of R?
Comment: Do you know the _definition_ of "$(x_n)_n$ is bounded"???
Comment: Yes! I realize I confused bounded sequences with bounded sequence of functions.
Answer: We have
$$a \le x_n \le b$$
for all $n$. Hence $a$ is a lower bound of $(x_{n})_{n}$ and $b$ is an upper bound of $(x_{n})_{n}$.
Answer: A sequence is bounded if there exist $\alpha,\beta$ such that $\alpha \leq x_n \leq \beta, \forall n$. This is obviously true in this case, since $a \leq x_n \leq b$.

Confusion about bounded sequences


Compilation error : "no matching function for call to 'std::vector::insert(int, Card*&)'" C++

Question: I try to use insert function of vector but I get a compilation error saying:
src/Hand.cpp:71:78: error: no matching function for call to 'std::vector::insert(int, Card&)'
         Vvalues[place]->getVcards().insert(Vvalues[place]->getSize()-1, *card);
I understand that the types of the elements I'm sending to insert don't match insert's signature, but I can't figure out why.
this is my function:
bool Hand::addCard(Card* card)
{
int place = Hand::searchCard(card); // the case that there is values in Vvalues but no one of them contain &card value
if (place <0)
{
    Value* v = new Value(card);
    if (place == -1 || place == -2)    Vvalues.insert(Vvalues.begin(),v);
    else if (place == -3)    Vvalues.insert(Vvalues.end(),v);
    else if (place == -4)    insertValueSortedWay(v);
}
else
{
Vvalues[place]->getVcards().insert(Vvalues[place]->getSize()-1, *card);
}
return true;

}
and than I try to compile and I get this:
src/Hand.cpp:71:78: error: no matching function for call to 'std::vector<Card*>::insert(int, Card&)'
     Vvalues[place]->getVcards().insert(Vvalues[place]->getSize()-1, *card);

What is the problem and how do I fix it?
Comment: `Vvalues[place]->getSize()-1` doesn't give you a valid iterator for `Vvalues`. Looks like you rather want `Vvalues.end()` there.
Comment: `insert` takes an iterator, not an index.
Comment: You probably want to use `std::vector::push_back()` and not `insert`.
Comment: I tried it and it gives me the same error
Comment: I also tried push_back but got a segmentation fault
Answer: std::insert doesn't take int as a parameter.
Your getSize()  function is returns an int, and instead takes a iterator.
Here are the valid parameters for vector::insert in c++11
insert (const_iterator position, const value_type& val);
insert (const_iterator position, size_type n, const value_type& val);
insert (const_iterator position, InputIterator first, InputIterator last);
insert (const_iterator position, value_type&& val);
insert (const_iterator position, initializer_list<value_type> il);

Compilation error : "no matching function for call to ‘std::vector::insert(int, Card*&)’" C++


Apache Cordova: running cordova run browser without launching browser app

Question: I have Apache Cordova app on my dedicated server. Access it via console. But when I run
    'cordova run browser'
I get error
Static file server running @ http://localhost:8000/index.html
CTRL + C to shut down
Error executing "google-chrome --user-data-dir=/tmp/temp_chrome_user_data_dir_for_cordova http://localhost:8000/index.html": [21075:21075:0423/054416:ERROR:browser_main_loop.cc(271)] Gtk: cannot open display:
And thus I cannot start test server with my app. How I can avoid automatic browser start?
Thanx
Comment: Try serving the content instead. [Cordova server](https://www.npmjs.com/package/cordova-server). It might have some plugin limitations.
Answer: I know it's been a while but what I did to avoid opening browser was editing the file under './platforms/browser/cordova/run' and changing the line:
return cordovaServe.launchBrowser({target: args.target, url: projectUrl});

to:
return cordovaServe;

Comment: That line of code is now in `./platforms/browser/cordova/lib/run`.
Comment: A side note, commenting out the line also works for some reason.
Comment: And the content is now `return server.launchBrowser({ 'target': args.target, 'url': projectUrl });` (line 60). Changing it to `return server;` works for me.
Comment: Where is it now (cordova -v 10.0.0)?


Fingertip care for guitarists

Question: I have built up calluses enough to avoid most fingertip pain from playing guitar and bass, but I have rough and slightly cracked fingertips. My fretting hand isn't bad, but my right hand is very rough from playing the bass:

The cracks are a bit painful (especially when playing), and I have a tendency to make them worse by nibbling at the rough edges. Gently smoothing out the rough edges with a nail file helps, but I'd like to know if there's something better I can do to treat or prevent this.
I have seen this earlier question about painful fingertips, which has good advice about keeping your fingers dry and your skin clean, but I would like some more specific advice for preventing and treating fingertip damage.
Comment: I'm not answering because I may not actually have anything helpful (or what you asked for), but in my experience, with time the callouses will recede and you'll end up with thicker skin but no dry/cracked areas.
Comment: Perhaps halfwound or even flatwound guitar strings could help you temporarily?
Comment: in a pinch, super glue is super effective for skin that's trying to tear. Probably not so good as a long term solution, though.
Comment: Now that you mention it, I have noticed exactly that. My fingertips do still get chewed up occasionally but nothing like they used to. Maybe post that as an answer anyway? It's good advice for long term care even if it doesn't cover the short term.
Answer: This is pretty normal, and there are popular and effective solutions, including:

Common moisturisers
Vaseline and hand lotions
Emery boards to take off any sharp corners
Using gentle soaps like Dove which don't dry the skin

It really isn't much different to a normal skincare regime. Note that it's important to keep the skin flexible without weakening it, so use only gentle moisturisers, lotions, and soaps, preferably natural ones.
Comment: I have always heard it is all about natural, gentle moisturisers. I use only natural ones., so as not to weaken the skin but keep it flexible
Comment: Several answers to the linked question recommend against using moisturizers on your fingertips. Could you elaborate on that? Is it a matter of finding the right balance, or is it more of a timing thing?
Answer: In the long run, try not to worry too much about this problem. It is normal that your skin ends up being damaged by your strings. However, once your skin heals, it will be stronger/thicker than it was before. This means that patience is the best long term solution. The natural process of letting your skin heal is more important than the mitigation of a few days of pain.
One drawback of this is that you'll need to give your skin enough time to heal. The rule for "training" your body is always the same: after wearing it out, you need to give it time to heal and eventually become stronger. It applies to skin thickness just as well as it applies to muscle strength. Long story short: do not continue playing the bass while your fingers are clearly still hurt, even if you are using skin-oil or other treatments.
Answer: If skin is cracking, then it's dry.  Use moisturizers after you play.  Otherwise, allow the calluses of your fingers to build up.
Answer: For super-emergency care of dry, cracking skin, the best thing I've found is pure lanolin. It's a natural oil derived from sheepskin, and reported to be nearly chemically-identical to human skin-oil. It is thick and sticky like pine-sap, like concentrated vaseline. Best for overnight treatment, with latex or plastic gloves so you don't get it everywhere.
I used this to good effect when I had deep cracks in my fingertips from using harsh cleaning chemicals on an espresso machine without gloves.
And Lee makes a very good point. If your fingers are bad enough to need this stuff, then they absolutely need time to heal without adding further stress.
Answer: This may sound gross, but I heard this many years ago listening to some guys talk to a street performer in NYC...
Ear wax.  Just stick your finger in your ear every so often and massage the wax into your fingertip.
Comment: That is gross indeed. Especially the part where you put your dirty string picking finger in your ear. Good chances to get an ear infection.
Answer: There are lots of good or bad things to do. Using a pick especially on bass is good. I play with a pick for a different sound, style and to give my fingers a rest, or when they are sore.
Any pick from 1-3mm works best. Dunlop stubby picks are nice.
One of the best things to do is to use 100% pure Lanolin, the best natural moisturizer for skin, keeps the fingertips smooth & hydrated. It's not easy to find so look around online.

Fingertip care for guitarists


Pandas Storing df to csv in BytesIO

Question: I want to store the output of df to csv in Memory Object of BytesIo() (Not StringIO) and then zip it and here is my attempt:
import pandas as pd
import numpy as np
import io
import zipfile
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
s_buf = io.BytesIO()
df.to_csv(s_buf)
s_buf.seek(0)
localfile= io.BytesIO()
zf = zipfile.ZipFile(localfile, mode="w",compression=zipfile.ZIP_DEFLATED)
zf.writestr(localfile, s_buf.read())
zf.close()
with open("D:/my_zip.zip", "wb") as f: # use `wb` mode
    f.write(zf.getvalue())

Comment: `df.to_csv(s_buf)` => `TypeError: a bytes-like object is required, not 'str'`
Comment: what is the result of this code? it doesn't work??
Answer: I think this would be helpful:-
import gzip
from io import BytesIO
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
b_buf = BytesIO()
with gzip.open(b_buf, 'wb') as f:
    f.write(df.to_csv().encode())
b_buf.seek(0)
with open("my_zip.zip", "wb") as f:
    f.write(b_buf.getvalue())

Pandas Storing df to csv in BytesIO


find $a$ and $b$ where $x^3 - 4x^2 -3x + 18 = (x+a)(x-b)^2$

Question: I have a problem solving this as when I match the coefficients to the expanded brackets I end up with $2$ unknowns $a \& b$. So cannot substitute any values to find the other. According to the answers $a=2$ and $b=3$ but I cannot get there. Would someone be able to provide a worked through example so I can figure this out. Thanks.
Comment: Can you show your work of matching the coefficients? In particular, if you can get a linear expression like (say) $ 4 = a + 2b $, then we can substitute that into the other equations.
Comment: Are you familiar with the [Rational Root Theorem](https://en.wikipedia.org/wiki/Rational_root_theorem)?
Comment: I have 1 linear expression: -2b + a = -4
Comment: I also have 2 quadratic expressions: b^2 - 2ab = -3, and ab^2 = 18, thank you for your help
Comment: expanding the brackets gives: x^3 - 2bx^2 + b^2x + ax^2 - 2abx + ab^2
Answer: $x^3 - 4x^2 -3x + 18 = (x+a)(x-b)^2 = (x+a)(x^2-2bx+b^2)=x^3+(a-2b)x^2+(b^2-2ab)x+ab^2$
$a-2b=-4$, $a=2b-4$
$b^2-2ab=-3$
$ab^2=18$
$b^2-2ab= b^2 - 2b(2b-4)=-3b^2+8b=-3$
$3b^2-8b-3=(3b+1)(b-3)=0$, $b=\frac{-1}{3}, a=\frac{-14}{3}$(NA) or $b=3,a=2$
Comment: Thank you for this, I will work though it and try to figure it out. The worked through example I was given for  a different question in the material was so basic in comparison to this question. Seems like a ridiculous jump in what I am expected to be able to answer in one question. But if I can get my head round it, will be worth it. Thanks.
Comment: I'm there now. Thank you so much!
Answer: your conditions say that there is a nontrivial common factor  in
$x^3 - 4x^2 -3x + 18 $   and its derivative $3x^2 -8x -3 $
The next to last line below is a Bezout type formula...
We can investigate  that using  the Euclidean algorithm
$$  \left(   x^{3}  - 4 x^{2}  - 3 x  + 18 \right)  $$
$$  \left(  3 x^{2}  - 8 x  - 3 \right)  $$
$$  \left(   x^{3}  - 4 x^{2}  - 3 x  + 18 \right)  =  \left(  3 x^{2}  - 8 x  - 3 \right)  \cdot \color{magenta}{  \left(   \frac{ 3 x  - 4 }{ 9 }  \right) } +  \left(   \frac{  - 50 x  + 150 }{ 9 }  \right)  $$
$$  \left(  3 x^{2}  - 8 x  - 3 \right)  =  \left(   \frac{  - 50 x  + 150 }{ 9 }  \right)  \cdot \color{magenta}{  \left(   \frac{  - 27 x  - 9 }{ 50 }  \right) } +  \left( 0 \right)  $$
$$ \frac{ 0}{1} $$
$$ \frac{ 1}{0} $$
$$ \color{magenta}{  \left(   \frac{ 3 x  - 4 }{ 9 }  \right) }  \Longrightarrow  \Longrightarrow  \frac{  \left(   \frac{ 3 x  - 4 }{ 9 }  \right) }{ \left( 1  \right) } $$
$$ \color{magenta}{  \left(   \frac{  - 27 x  - 9 }{ 50 }  \right) }  \Longrightarrow  \Longrightarrow  \frac{  \left(   \frac{  - 9 x^{2}  + 9 x  + 54 }{ 50 }  \right) }{ \left(   \frac{  - 27 x  - 9 }{ 50 }  \right) } $$
$$  \left(   x^{2}  -  x  - 6 \right)  \left( \frac{ 9}{50 } \right)  -  \left(  3 x  + 1 \right)  \left(   \frac{ 3 x  - 4 }{ 50 }  \right)  =  \left( -1  \right)  $$
$$  \mbox{confirming  GCD} =   \color{blue}{  \left(   x  - 3 \right) }   $$
$$  \left(   x^{3}  - 4 x^{2}  - 3 x  + 18 \right)  =  \left(   x^{2}  -  x  - 6 \right)  \cdot \color{blue}{  \left(   x  - 3 \right) } +  \left( 0 \right)  $$
$$  \left(  3 x^{2}  - 8 x  - 3 \right)  =  \left(  3 x  + 1 \right)  \cdot \color{blue}{  \left(   x  - 3 \right) } +  \left( 0 \right)  $$
$$  \left(   x^{3}  - 4 x^{2}  - 3 x  + 18 \right)  \left( \frac{ 9}{50 } \right)  -  \left(  3 x^{2}  - 8 x  - 3 \right)  \left(   \frac{ 3 x  - 4 }{ 50 }  \right)  =  \color{blue}{  \left(   -  x  + 3 \right)  } $$
$$  \mbox{GCD} =   \color{blue}{  \left(   x  - 3 \right) }   $$
The conclusion is that $(x-3)^2$  divides
$x^{3}  - 4 x^{2}  - 3 x  + 18.$  So, divide the original by $x^2 - 6 x + 9,$  the quotient will be some $x +a$


evaluate my php code

Question: Ive write a PHP app which copy some pictures from a public website, but it runs pretty slow. I'll like to see where I have a bottleneck, or where the most times is spent. How can i do that?
I'm using Eclipse PDT as IDE. Are any plugins for it?
Comment: Most likely, more time is spent contacting the server and waiting for a response than anything else.
Answer: You should try xdebug:  http://www.xdebug.org/docs/profiler
And here is a documentation about PDT and xdebug: http://www.eclipse.org/pdt/documents/XDebugGuideForPDT2.0.pdf
Answer: Usually code to read/copy data from other servers will cause bottle neck. You can use below code to measure time for some parts of your code then figure it out
<code><?php
$time_start = microtime(true);

// your slow code here...

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "$time elapsed\n";
?>
</code>
Answer: Use Webgrind for detecting bottlenecks https://github.com/jokkedk/webgrind
Its an web interface for XDebug profiling.
Answer: On the server side, Xdebug is complex to install, configure, use (in eclipse), but it is powerful once you understand it.
On the client side, in Firefox, try Firebug; or in Chrome, try the Chrome developer tools to determine which elements of the web page need most time to load. Might be simple I/O problem if you're using high-resolution embedded images on your site, or network contacting times as a commenter suggested.
Comment: I appreciate ur replay and your right about that xdebug is difficult to install. I've tried once for 4h and I didn't make it run. I don;t know how to use Firebug, when it is about PHP code. FirePHP is an option but it doen't run on my machine setup after 30minutes of tries.

evaluate my php code


Highlight the selected item of a navigation pane

Question: Referring to the example "Nav with nested links" under https://developer.microsoft.com/en-us/fabric#/controls/web/nav , On click of a nav item, I want to highlight this item. I have set url as ' ' so that clicking on an item doesn't do anything. But, I want that item to be highlighted on click. How do I do this?
Any pointers would be helpful.
import * as React from 'react';
import { Nav,INavStyles } from 'office-ui-fabric-react/lib/Nav';
import { initializeIcons } from '@uifabric/icons';
initializeIcons();

    const navStyles: INavStyles = {
  root:{
      boxSizing: 'border-box',
      border: '1px solid lightgrey',
      overflowY: 'auto',
      height: 300
  },
  chevronButton: {
      height: 30
  },
  chevronIcon:{
      height: 30,
      lineHeight: 30
  },
  compositeLink: {},
  group:{},
  groupContent: {},
  link: {},
  linkText:{},
  navItem:{},
  navItems:{
    margin: 0
  },
};

export const NavNestedExample1: React.FunctionComponent = () => {
  return (
    <Nav
      styles={navStyles}
      ariaLabel="Nav example with nested links"
      groups={[
        {
          links: [
            {
              name: 'Parent link 1',
              url: '',
              target: '_blank',
              expandAriaLabel: 'Expand Parent link 1',
              collapseAriaLabel: 'Collapse Parent link 1',
              links: [
                {
                  name: 'Child link 1',
                  url: '',
                  target: '_blank'
                },
                {
                  name: 'Child link 2',
                  url: '',
                  target: '_blank',
                  expandAriaLabel: 'Expand Child link 2',
                  collapseAriaLabel: 'Collapse Child link 2',
                  links: [
                    {
                      name: '3rd level link 1',
                      url: '',
                      target: '_blank'
                    },
                    {
                      name: '3rd level link 2',
                      url: '',
                      target: '_blank'
                    }
                  ]
                },
                {
                  name: 'Child link 3',
                  url: '',
                  target: '_blank'
                }
              ]
            },
            {
              name: 'Parent link 2',
              url: '',
              target: '_blank',
              expandAriaLabel: 'Expand Parent link 2',
              collapseAriaLabel: 'Collapse Parent link 2',
              links: [
                {
                  name: 'Child link 4',
                  url: '',
                  target: '_blank'
                }
              ]
            }
          ]
        }
      ]}
    />
  );
};

Comment: can you provide some code?
Comment: Code added to the main thread.
Comment: I have never worked with this library but on clicking an item it probably triggers an event, according to [doc](https://learn.microsoft.com/en-us/javascript/api/office-ui-fabric-react/inavprops?view=office-ui-fabric-react-latest#selectedkey) you should keep the selectedKey in the state
Answer: Use className props to apply an additional CSS class to the Nav,INavProps interface

export const App: React.FunctionComponent = () => {
  return (
    <Nav
      className='nav' //here
      ariaLabel="Nav example with nested links"
      groups={[
            ....

 //App.css
    .nav :focus{
      color: brown;
      background-color: darksalmon ;
    }
   .nav :hover{
      color: .....;
      background-color: ......;
    }
   .nav :active{
      color: .....;
      background-color: ......;
    }

With INavStyles and selectors

const navStyles: INavStyles = {
  root: {
    boxSizing: 'border-box',
    border: '1px solid lightgrey',
    overflowY: 'auto',
    height: 300
  },
  linkText: {
    color: 'green',
    selectors: { '&:hover': { color: 'red' } }
  },
compositeLink: {
   selectors: {
      '&:active ,&:focus-within': { backgroundColor: 'orange' }
    }
  },
...

Comment: This does solve it. But, I was looking more from using the 'styles' attribute of type INavStyles. My Nav component has "styles" already defined and I want to handle this highlighting in the "styles" itself rather than adding "className" attribute as well. Thanks for your inputs Alex.
Comment: I have edited the code and now use the "styles" property of "Nav" component.
Comment: this just changes text color from green to red on hover over the nav item. What I am looking for is... when I click on an item say "Child link1", this item should stay highlighted (basically change the background color). Currently, when you hover over an item, we can see change in background color for each item. I want to highlight the currently clicked item.
Comment: `What I am looking for is... when I click on an item say "Child link1"` it's different from your question, that why I asked to create a new one. for highlight the currently clicked item you can use `compositeLink` as I have shown in the updated one.also, you can try with others like `link`,`linkText`,
  `navItem`,...to achieve different styles. good luck.
Comment: Thanks Alex. Will try.


Proof: Convergence in Distribution implying Convergence in Probability (Special Case)

Question: I am having a hard time understanding a proof.
The theorem says
$$X_n \rightarrow_D b \space \text{then} \space X_n \rightarrow_p b $$
where b is a constant.
A part of the proof says
$$\begin{align}
\lim_{n \rightarrow \infty} Pr[|X_n-b|\le \epsilon]
& = \lim_{n \rightarrow \infty}F_{X_n}(b + \epsilon) - \lim_{n \rightarrow \infty} F_{X_n}((b-\epsilon)-0)\\
& = 1 - 0\\
& = 1
\end{align}$$
Where $F_{X_n}$ is the cdf of the iid $X_i$ s.
I understand the big picture where why we want to prove that
$$\lim_{n \rightarrow \infty}Pr[|X_n-b|\le \epsilon] =1$$
and I also see that the expansion of the absolute value sign gives the expression in the first row.
But I have no idea why each of those expressions are equal to 1 and 0, respectively.
I think I am not really understanding what convergence in distribution really means.
I only know that the limit of the moment generating function simplifies to something...
Answer: $F_{X_n} (x) \to F_b(x)$ whenever $F_b$ is continuous at $x$. [Here $F_b(x)=1$ if $x \geq b$ and $0$ of $x <b$]. Note that $F_b$ is continuous at all points except $b$. Since $b+\epsilon >b$ and $F_b(b+\epsilon) =1$ you see that the first term is $1$. Similarly for the second term.
Comment: Please give me a moment, I will try to understand it ... I guess what I don't understand is, that a cdf is a constant.  How does that work?
Comment: In other words, how do we know that $F_b(x)=1$ when $x \ge b$ ? Hold on, I found https://math.stackexchange.com/questions/2271088/what-does-it-mean-to-get-the-cdf-of-a-constant-variable
Comment: Thank you!  I was able to understand it :)  I guess it is sometimes difficult to realize that there are people like me who doesn't understand that $Pr[X \le x] = Pr[b \le x]$ is what $F_b(x)$ really means.


Drop down menu. Sub menu drops down when you hover where it will appear

Question: Ideally, I want the drop down menu to only appear when the parent button is hovered / clicked.  However, the sub-menu is showing up when you hover over anywhere that the menu will appear.  I put it in JSfiddle:
http://jsfiddle.net/7g67j/
Ideal outcome is the adjustment to the JS that would make it so that the drop downs appear ONLY when the button they are under is hovered...
<code>$(document).ready(function(){
var w = $(window).width();
if(w > windowWdth) {$('#block_navigation > ul').css('display', 'block');    $('#block_navigation').css('height', '55px');
</code>
Comment: This seems to work fine for me... I tried Firefox, Chrome and IE and they all look good. What are you trying it on?
Comment: Chrome.  Maybe I didn't explain the issue very well.  If you hover anywhere where the drop down menu WILL BE, it shows up.  So for instance, under "Family Law" the last item on the menu is "protection from abuse" if you just mouse where the "Protection from Abuse" button would appear, the menu appears.  It should only appear when you mouse over "Family Law" at the top.   Does that make sense?
Comment: Whoa, that's weird. I see what you mean now :P
Comment: Well your problem is that the drop downs are always there, just with an opacity of 0. This (combined with all your hovers) means hovering over them makes them appear.  Most people use `display: block` and `display: none` for drop down menus (instead of changing the opacity). This kills your animation though http://jsfiddle.net/7g67j/4/
Comment: You could try messing with all your hover elements a bit more as well.
Answer: here is your updated jsfiddle. you have to add visibility:hidden in this div
<code>#block_navigation ul ul {
    z-index: 1;
    opacity:0;
    visibility: hidden;
}
</code>
Comment: Interesting... If this is what they are trying to do, this is some weird UI. I didn't understand this from the question though (which is kind of vague)
Comment: Well, that "Hidden" property is making it so that the menu does not show up above the slideshow beneath it...  Tried playing with Z-index, not able to get menu to show above element below...
Comment: On second thought, other element had Z-index as well.  I think we are all set here.   Thank you very much for your help.


Excel 2013 How to assign dates to cells

Question: I'd like to assign dates to cells in a planner spreadsheet I have made.
Currently, the rows are months, the columns are days of the week, and each individual cells just have a number for the day of the month.
I don't want to display the full date in the cell, just have the cell "know" what date it is representing. One use of this could be to have the current day always highlighted in a different colour when opening the spreadsheet. Is this possible in Excel?
Answer: Looking at your question, the results would require to show multiple "dates" within the cell.
For January '16 for example, you would have 4 different type of dates as January has 4 Mondays (4;11;18;25). Is this what you're looking to achieve? Otherwise it is not possible to have excel figure out a single date unless you provide it with additional references in order to come up with a result.
Comment: I may not have been entirely clear with my description. What I have is a Year Planner style thing, which shows the days of the year. I have simply given the column headings day of the week names, starting at Monday in B1, Tuesday in C1, across to Sunday in H1, then repeating Mon-Sun for the rest of a month across the top row. Then the first cell in each row has a month heading, starting at Jan in A1, Feb in A2, going down to Dec in A12. The response above from teylyn looks like it will do what I want. Cheers.
Comment: Hi alanp, thank you for your reply. I found this excel template that may save you having to start from scratch. (http://www.excelfunctions.net/excel-year-planner.html)
Answer: Enter a date into a cell. Format the cell to show the part of the date you want to see. In the screenshot, column A contains full dates in each cell. A2 and down are formatted with the custom format code shown in column C

Excel still treats the dates as the underlying full dates in formulas, even though only parts of the dates are showing in the cell.
Comment: Thanks teylyn, this is really great. I had no idea you could format dates to this extent. Haven't had a chance to fully test this approach, but looks like it will do what I want. Cheers :-)

Excel 2013 How to assign dates to cells


If $u$ is harmonic then $\int_G |\nabla u|^2\leq\int_G |\nabla v|^2$

Question: Let $G\subset \mathbb{R}^n$ be an open set with smooth boundary and
let $u,v:\bar{G}\rightarrow\mathbb{R}$ be $C^2$ functions.   Suppose
that $u$ is harmonic, i.e. $\Delta u=0$, and that $u|_{\partial G}=v|_{\partial G}$.
Prove that:
1. $$\int_G |\nabla u|^2=\int_G \left \langle \nabla u, \nabla v \right \rangle$$
2. $$\int_G |\nabla u|^2\leq\int_G |\nabla v|^2$$
I managed to solve the first part. It's a simple application of the assumptions and Green's identities, more specifically the second one (which can be found at the very beginning of these notes).
However, I'm stuck on the second one.
Using the first part it suffices to show that
$$\int_G \left \langle \nabla v, \nabla (v-u) \right \rangle\geq 0$$
but I cannot proceed from here.
I'd be glad for someone's help on this one.
Comment: Cauchy-Schwarz might help.
Comment: I thought about that. But I see no way to guarantee that $|\nabla u|\leq |\nabla v|$
Comment: Using the first equality we have
\begin{equation*}
\int_{G}\left\lvert\nabla u\right\rvert^{2}dx=\int_{G}\left<\nabla u,\nabla v\right>dx\le\sqrt{\int_{G}\left\lvert\nabla u\right\rvert^{2}dx}\sqrt{\int_{G}\left\lvert\nabla v\right\rvert^{2}dx}
\end{equation*}
now divide by $\sqrt{\int_{G}\left\lvert\nabla u\right\rvert^{2}dx}$
Comment: Ohhhh I see. That's a different kind of Cauchy-Schwarz than the one I had in mind then. Thanks! You can definitely post it as an answer!
Answer: We see that if
\begin{equation*}
\int_{G}\left\lvert\nabla u(x)\right\rvert^{2}dx=0
\end{equation*}
then the second inequality is clear. So we may assume this integral is positive. By the equality obtained before we have
\begin{align*}
\int_{G}\left\lvert\nabla u(x)\right\rvert^{2}dx&=\int_{G}\left<\nabla u(x),\nabla v(x)\right>dx\le\int_{G}\left\lvert \nabla u(x)\right\rvert\left\lvert\nabla v(x)\right\rvert{}dx\\
&\le\left(\int_{G}\left\lvert\nabla u(x)\right\rvert^{2}dx\right)^{\frac{1}{2}}\left(\int_{G}\left\lvert\nabla v(x)\right\rvert^{2}dx\right)^{\frac{1}{2}}
\end{align*}
Dividing through by $\left(\int_{G}\left\lvert\nabla u(x)\right\rvert^{2}dx\right)^{\frac{1}{2}}$ and squaring gives the desired inequality.
Answer: Perhaps a more easy way to see this is to write $\nabla v = \nabla (v-u) + \nabla u$. Then, by $\int_G \langle \nabla (v-u) , \nabla u\rangle = 0,$ we have
$$ \int_G |\nabla v^2| = \int _G |\nabla (v-u)|^2 + \int_G |\nabla u|^2 \geq \int_G |\nabla u|^2. $$
This can be thought of some sort of otrhogonal decomposition of $v$, hence the above is just pythagorean (if you like).


What is the difference between jQuery's mouseout() and mouseleave()?

Question: What is the difference between jQuery's mouseout() and mouseleave()?
Comment: http://api.jquery.com/mouseout/ and http://api.jquery.com/mouseleave/ are useful
Comment: Note: equivalent is `mouseover`, and equivalent to `mouseleave` is `mouseenter`.
Answer:
The mouseleave event differs from mouseout in the way it handles event bubbling. If mouseout were used in this example, then when the mouse pointer moved out of the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseleave event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse leaves the Outer element, but not the Inner element.

Source: http://api.jquery.com/mouseleave/
Comment: mouseover vs. mouseenter: https://jsfiddle.net/hejdav/945pv53h/3/ (mouseout & mouseleave equivalently)
Comment: Explanation above gets much more clear when seeing both methods working and the difference between them, worked for me.
Answer: There can be times when mouseout is a better choice than mouseleave.
For example, let's say you've created a tooltip that you want displayed next to an element on mouseenter. You use setTimeout to prevent the tooltip from popping up instantly. You clear the timeout on mouseleave using clearTimeout so if the mouse leaves the tooltip won't be displayed. This will work 99% of the time.
But now let's say the element you have a tooltip attached to is a button with a click event, and let's also assume this button prompts the user with either a confirm or alert box. The user clicks the button and the alert fires. The user pressed it fast enough that your tooltip didn't have a chance to pop up (so far so good).
The user presses the alert box OK button, and the mouse leaves the element. But since the browser page is now in a locked state, no javascript will fire until the OK button has been pressed, meaning your mouseleave event WILL NOT FIRE. After the user presses OK the tooltip will popup (which is not what you wanted).
Using mouseout in this case would be the appropriate solution because it will fire.
Comment: Could you explain why `mouseout` in that case will fire? Wouldn't the browser be still in locked state for `mouseout`?
Answer: jQuery API doc:
mouseout

This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves out of the Inner element in this example, a mouseout event will be sent to that, then trickle up to Outer. This can trigger the bound mouseout handler at inopportune times. See the discussion for .mouseleave() for a useful alternative.

So mouseleave is a custom event, which was designed because of the above reason.
http://api.jquery.com/mouseleave/
Answer: Event Mouseout will trigger when mouse leaves the selected element and also when mouse leaves it's child elements also.
Event Mouseleave element will trigger when pointer will leave the selected element only.
Reference: W3School
Answer: I encountered a similar problem using plan Javascript instead of jquery, but they're some how related and I'll leave my two cents in case someone else is on the search nowadays.
I was trying to use the mouseout event on a navigation menu. The parent div had a submenu composed of a list of uls elements. When I tried to navigate to the div children elements the mouseout event was fired. This was not my desired output.
From the docs

mouseout is also delivered to an element if the cursor enters a child
element, because the child element obscures the visible area of the
element.

And that was the issue.
The mouseleave event did not have this issue. Just using it made things work for me.
https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseleave_event