Dúvida com Gatilho de Update em Tabela

Question: Tenho duas tabelas, perguntas e respostas, é gostaria de atualiza as mesmas de acordo com o que for selecionado: Banco Sql Server 2005
Problema:
<code>--usuário excluindo a pergunta (não está gravando a data da exclusão é não está excluindo as perguntas)
update TB_PERGUNTA set EXCLUIR_PERGUNTA = 'S' where IDPERGUNTA = 4 and IDUSUARIO = 1

--moderador excluindo a pergunta (não está gravando a data da exclusão é não está excluindo as perguntas)
update TB_PERGUNTA set BLOQUEIO_PERGUNTA = 'S' where IDPERGUNTA = 4 and IDMODERADOR = 7
</code>
<code>Create table [TB_PERGUNTA]
(
    [IDPERGUNTA] Integer NOT NULL, UNIQUE ([IDPERGUNTA]),
    [IDCATEGORIA] Integer NOT NULL,
    [IDUSUARIO] Integer NOT NULL,
    [IDMODERADOR] Integer NOT NULL,
    [TITULO_PERGUNTA] Text NULL,
    [DESCRICAO_PERGUNTA] Text NULL,
    [BLOQUEIO_PERGUNTA] Char(1) NULL,
    [DESCRICAO_BLOQUEIO] Text NULL,
    [EXCLUIR_PERGUNTA] Char(1) NULL,
    [DATA_PERGUNTA] Datetime NULL,
    [DATA_EXCLUIR] Datetime NULL,
Primary Key ([IDPERGUNTA])
)
go

Create table [TB_RESPOSTA]
(
    [IDRESPOSTA] Integer NOT NULL, UNIQUE ([IDRESPOSTA]),
    [IDPERGUNTA] Integer NOT NULL,
    [IDUSUARIO] Integer NOT NULL,
    [IDMODERADOR] Integer NOT NULL,
    [RESPOSTA] Text NULL,
    [RESPOSTA_SELECIONADA] Char(1) NULL,
    [NOTA_RESPOSTA] Numeric(3,2) NULL,
    [BLOQUEIO_RESPOSTA] Char(1) NULL,
    [DESCRICAO_BLOQUEIO] Text NULL,
    [DATA_RESPOSTA] Datetime NULL,
    [DATA_EXCLUIR] Datetime NULL,
Primary Key ([IDRESPOSTA],[IDPERGUNTA])
)
go
</code>
Tenho a Trigger:
<code>--gatilho para atualiza a tabela de pergunta é resposta no caso de exclusão pelo usuário
--ou pelo moderador
CREATE TRIGGER TGR_TB_PERGUNTA_UPDATE
 ON [dbo].[TB_PERGUNTA]
 FOR UPDATE
AS
BEGIN
   DECLARE @EXCLUIRPERGUNTA CHAR
   DECLARE @BLOQUEIOPERGUNTA CHAR
   DECLARE @IDPERGUNTA INT
   DECLARE @IDUSUARIO INT
   DECLARE @IDMODERADOR INT

   --se o excluirpergunta receber (S) então o usuário está bloqueando a pergunta se (N) está abrindo a pergunta
   SELECT  @EXCLUIRPERGUNTA  = EXCLUIR_PERGUNTA  FROM TB_PERGUNTA INSERTED
   --se o bloqueiopergunta receber (S) então o moderador está bloqueando a pergunta se (N) está abrindo a pergunta
   SELECT  @BLOQUEIOPERGUNTA = BLOQUEIO_PERGUNTA FROM TB_PERGUNTA INSERTED
   --pega o ID da pergunta
   SELECT  @IDPERGUNTA       = IDPERGUNTA        FROM TB_PERGUNTA INSERTED
   --pega o id do usuário
   SELECT  @IDUSUARIO        = IDUSUARIO         FROM TB_PERGUNTA INSERTED
   --pega o id do moderador
   SELECT  @IDMODERADOR      = IDMODERADOR       FROM TB_PERGUNTA INSERTED

    --pergunta excluida pelo usuário
   IF ( @EXCLUIRPERGUNTA = 'S')
    BEGIN
      --excluir a pergunta
     UPDATE TB_PERGUNTA  SET  EXCLUIR_PERGUNTA = 'S',
            DESCRICAO_BLOQUEIO = 'Excluido pelo usuário' ,
            DATA_EXCLUIR = CONVERT(VARCHAR, GETDATE(), 20)
            WHERE IDPERGUNTA = @IDPERGUNTA AND IDUSUARIO =  @IDUSUARIO

          --excluir todas as respostas referente a pergunta
     UPDATE TB_RESPOSTA SET BLOQUEIO_RESPOSTA = 'S',
            DATA_EXCLUIR = CONVERT(VARCHAR, GETDATE(), 20),
            DESCRICAO_BLOQUEIO = 'Excluido pelo usuário'  WHERE IDPERGUNTA = @IDPERGUNTA
    END

    --pergunta bloqueada pelo moderador
   IF ( @BLOQUEIOPERGUNTA = 'S')
    BEGIN
     --excluir pergunta
     UPDATE TB_PERGUNTA  SET BLOQUEIO_PERGUNTA = 'S',
          DESCRICAO_BLOQUEIO = 'Está pergunta foi bloqueada pelo moderador',
          DATA_EXCLUIR = CONVERT(VARCHAR, GETDATE(), 20)
          WHERE IDPERGUNTA = @IDPERGUNTA AND IDMODERADOR =  @IDMODERADOR

          --excluir respostas
     UPDATE TB_RESPOSTA SET BLOQUEIO_RESPOSTA = 'S',
         DATA_EXCLUIR = CONVERT(VARCHAR, GETDATE(), 20),
         DESCRICAO_BLOQUEIO = 'Excluido pelo moderador'
         WHERE IDPERGUNTA = @IDPERGUNTA

    END

    --pergunta aberta pelo usuário
   IF ( @EXCLUIRPERGUNTA = 'N')
    BEGIN
      --pergunta aberta pelo usuário
     UPDATE TB_PERGUNTA  SET  EXCLUIR_PERGUNTA = 'N',
            DESCRICAO_BLOQUEIO = 'Excluido pelo usuário' ,
            DATA_EXCLUIR = null
            WHERE IDPERGUNTA = @IDPERGUNTA
            AND IDUSUARIO =  @IDUSUARIO

       --abre todas as respostas
     UPDATE TB_RESPOSTA SET BLOQUEIO_RESPOSTA = 'N',
           DATA_EXCLUIR =null,
           DESCRICAO_BLOQUEIO = null
           WHERE IDPERGUNTA = @IDPERGUNTA
    END

    --pergunta aberta pelo moderador
   IF ( @BLOQUEIOPERGUNTA = 'N')
    BEGIN
     --abre a pergunta pelo moderador
     UPDATE TB_PERGUNTA  SET BLOQUEIO_PERGUNTA = 'N',
            DESCRICAO_BLOQUEIO =null,
            DATA_EXCLUIR =null
            WHERE IDPERGUNTA = @IDPERGUNTA
            AND IDMODERADOR =  @IDMODERADOR

      --abre todas as respostas pelo moderador
     UPDATE TB_RESPOSTA SET BLOQUEIO_RESPOSTA = 'N',
           DATA_EXCLUIR = null,
           DESCRICAO_BLOQUEIO =null
           WHERE IDPERGUNTA = @IDPERGUNTA
           AND IDMODERADOR =  @IDMODERADOR
    END

END
</code>
Answer: Repare que você está gerando uma recursiva com está trigger, veja:
Exemplo a variável @BLOQUEIOPERGUNTA está como "S", neste caso você irá gerar um update novamente na tabela assim ativando novamente a trigger, isso poderá ocasionar problemas, será necessário utilizar o comando TRIGGER_NESTLEVEL, que verifica quantas vezes a trigger foi executada por ela mesma, segue exemplo para sua trigger:
<code>   DECLARE @EXCLUIRPERGUNTA CHAR
   DECLARE @BLOQUEIOPERGUNTA CHAR
   DECLARE @IDPERGUNTA INT
   DECLARE @IDUSUARIO INT
   DECLARE @IDMODERADOR INT
   --Caso a trigger esteja chamando a si mesma a execução é interrompida com o comando RETURN
   IF ( SELECT TRIGGER_NESTLEVEL ( ) ) >= 2
     return

   --se o excluirpergunta receber (S) então o usuário está bloqueando a pergunta se (N) está abrindo a pergunta
</code>
Comment: Muito bom, perfeito, era isso mesmo. muito grato!

Dúvida com Gatilho de Update em Tabela


What is the intuition behind the line integral for the center of mass?

Question: We define, for a density function $\rho(x,y)$, the following to be the center of mass for a wire defined by the curve $C$.
$$\bar{x}= \frac{1}{M_\text{Total}}\int_Cx\rho(x,y)ds$$
$$\bar{y}= \frac{1}{M_\text{Total}}\int_Cy\rho(x,y)ds$$
Where does this formula come from? I'm not clear why we're integrating over the function $x\rho(x,y)$ or $y\rho(x,y)$ and why multiplying the result by the reciprocal of total mass would give us the coordinate for the center of mass.
Comment: What is $C{{}}$?
Comment: @LordSharktheUnknown sorry, I should've clarified that. I edited my post to reflect that $C$ is the curve for which a given piece of wire is defined.
Answer: Consider a lever...
Place two masses $m_1$ and $m_2$ on opposite ends of a lever of length $L$---where should the fulcrum be placed for this lever to balance?
Letting $d_1$, $d_2$ be the distances from the point masses to the fulcrum, Archimedes tells us that
$$m_1 d_1 = m_2 d_2.$$
In modern terms, we would say that the masses are applying equal and opposite torque to the system under the influence of gravity.
Introduce a coordinate system and let $x_1, x_2$ be the positions of the point masses and $\bar{x}$ be the position of the fulcrum. Our equation becomes
 \begin{align*}0 &= m_1 (x_1 - \bar{x}) + m_2 (x_2 - \bar{x}) \\
 (m_1 + m_2) \bar{x} &= m_1 x_1 + m_2 x_2 \\
\bar{x} &= \frac{1}{m_1 + m_2} \left( m_1 x_1 + m_2 x_2 \right).
\end{align*}
We can repeat this argument for $n$ point masses $m_1, \dots, m_n$ located at $x_1, \dots, x_n$ to find that
 $$\bar{x} = \frac{1}{\sum_{i=1}^n m_i} \sum_{i=1}^n m_i x_i.$$
One-dimensional case
Now consider a continuous density distribution $\rho(x)$ along an interval $I=[a,b]$. Take a partition of $I$ by $a=x_0<x_1< \dots<x_{n-1}< x_n=b$ and approximate with a Riemann sum, noting that the mass on each sub-interval is approximately the density at a point times the length of each interval. In effect, we are approximating by collapsing the mass on each interval into a point mass.
$$\bar{x} \approx \frac{1}{\sum_{i=1}^n \rho(x_i)\cdot(x_i - x_{i-1})} \sum_{i=1}^n x_i \cdot\rho(x_i) \cdot(x_i - x_{i-1})$$
which becomes exact upon taking the limit $n \to \infty$:
$$\bar{x} = \frac{1}{\int_I  \rho(x) ~\mathrm{d}x} \int_I x \rho(x) ~\mathrm{d}x = \frac{1}{M_{total}} \int_I x \rho(x) ~\mathrm{d}x .$$
Notice that we are integrating the $x$-coordinate against density and then dividing by the total mass to find the center of gravity.
On to your case
Instead of $\bar{x}$ being a point on which our one-dimensional mass rests, we view $\bar{x}$ as being a line on which our bent wire balances. In effect, the torque about this line from a point mass (under the effect of gravity) depends on the $x$-coordinate  and the mass located there.
Parametrize the curve $C$ with $\mathbf{r}(t)=( x(t), y(t))$ with $t \in [a,b]$, letting $\mathbf{r}(t)$ be suitably nice, i.e., one-to-one and smooth. Again, take a partition $a=t_0 < t_1 < \dots < t_{n-1} < t_n = b$. The mass of wire associated with each sub-interval $[t_{i-1}, t_i]$ will be approximately the length $\Vert \mathbf{r}(t_i) - \mathbf{r}(t_{i-1}) \Vert$ times the density $\rho ( \mathbf{r}(t_i) )$, with an $x$-coordinate of approximately $x(t_i)$. This leads to the Riemann sum
\begin{align*}\bar{x} &\approx \frac{1}{\sum_{i=1}^n \rho(\mathbf{r}(t_i))\cdot \Vert \mathbf{r}(t_i) - \mathbf{r}(t_{i-1}) \Vert } \sum_{i=1}^n x(t_i)\cdot\rho(\mathbf{r}(t_i)) \cdot \Vert \mathbf{r}(t_i) - \mathbf{r}(t_{i-1})\Vert \\
&= \frac{1}{\sum_{i=1}^n \rho(\mathbf{r}(t_i))\cdot \frac{\Vert \mathbf{r}(t_i) - \mathbf{r}(t_{i-1}) \Vert}{t_i - t_{i-1}} } \sum_{i=1}^n x(t_i)\cdot\rho(\mathbf{r}(t_i)) \cdot \frac{\Vert \mathbf{r}(t_i) - \mathbf{r}(t_{i-1})\Vert}{t_i - t_{i-1}}.
\end{align*}
Again, this becomes exact upon taking the limit $n \to \infty$:
$$\bar{x} = \frac{1}{\int_a^b \rho(\mathbf{r}(t)) \Vert \mathbf{r}'(t) \Vert ~\mathrm{d}t} \int_a^b x(t) \cdot \rho(\mathbf{r}(t))\cdot \Vert \mathbf{r}'(t) \Vert ~\mathrm{d}t.$$
Letting $\mathrm{d}s$ be the "arc-length element" $\Vert \mathbf{r}'(t) \Vert ~\mathrm{d}t$, we write this integral in the more familiar form
$$\bar{x} = \frac{1}{\int_C \rho(x,y) ~\mathrm{d}s} \int_C x \rho(x,y) ~\mathrm{d}s = \frac{1}{M_\text{total}} \int_C x \rho(x,y) ~\mathrm{d}s.$$
Repeating this argument for $\bar{y}$ gives
$$\bar{y} = \frac{1}{\int_C \rho(x,y) ~\mathrm{d}s} \int_C y \rho(x,y) ~\mathrm{d}s = \frac{1}{M_\text{total}} \int_C y \rho(x,y) ~\mathrm{d}s.$$
Comment: Nicely explained! (I took the liberty to change $*$ into $\cdot$.)
Answer: The intuition is that the first moment, in any direction, about the centre of mass $(\bar{x},\bar{y})$ should be zero. In the $x$-direction, this means
$$
\int_C (x-\bar{x})\rho(x,y)\,ds = 0
\Leftrightarrow
\bar{x} \! \underbrace{\int_C \rho(x,y)\,ds}_{=M_\text{Total}} = \int_C x\rho(x,y)\,ds
\Leftrightarrow
\bar{x} = \frac{1}{M_\text{Total}}\int_C x\rho(x,y)\,ds.
$$
Similarly for the $y$-direction.


Analyzing limits problem Calculus (tell me where I'm wrong).

Question: I came accross: $$\lim_{x \to\ 0}\frac{x\cos x - \log (1 + x)}{x^{2}}$$
I tried the following please tell me where I 'm wrong:
$$\lim_{x \to\ 0}\frac{x\cos x - \log (1 + x)}{x^{2}} $$
$$\text{(Dividing by }x)$$
$$=\displaystyle\lim_{x \to\ 0}\dfrac{ \cos x - \dfrac{\log (1 + x)}{x}}{x} $$
$$=\lim_{x \to\ 0}\frac{\cos x - 1}{x} $$
$$=\lim_{x \to\ 0}\frac{-2\sin^{2} \dfrac{x}{2}}{x} $$
$$=\lim_{x \to\ 0}\frac{-2x\sin^{2}\dfrac{x}{2}}{(\dfrac{x}{2})^{2}\times 4} $$
$$\lim_{x \to\ 0}\dfrac{-x}{2}=0$$
But Answer given is $\dfrac{1}{2}$
Please Help.
Comment: You cannot, in general, choose to carry on the limit *of only one part of the exrpession while leaving the rest unchanged* . May I ask how did you know $\;\lim\limits_{x\to0}\frac{\log(1+x)}x=1\;$ ?
Comment: @Ayushakj Thank you. You *still cannot* take the limit **only of that expression** and leave the rest unchanged
Comment: What did you do from the third to fourth lines?
Comment: @Joanpemo $\lim\limits_{x\to0}\dfrac{\log(1+x)}x$ = $\lim\limits_{x\to0}\dfrac{x - \dfrac{x^{2}}{2} + \dfrac{x^{3}}{3} - \cdots}{x}$ = $\lim\limits_{x\to0} 1 - \dfrac{x}{2} + \dfrac{x^{2}}{3} \cdots = 1$ This is given in my book.
Comment: Please consider using \log and \cos to get $\log$ and $\cos$ instead of $log$ and $cos$.
Answer: The mistake is simple and somewhat common for beginners. The fact is that when you are evaluating the limit of a complex expression (i.e. consisting of many sub-expressions which are somewhat simple individually) then in general it is not possible to replace a sub-expression by its limit in a step during overall evaluation of limit.
Thus when you replace the sub-expression $(\log(1 + x))/x$ with its limit $1$ as $x \to 0$ you have done something wrong. This is not permitted by any of rules of limits.
However there are two situations when it is permitted to replace a sub-expression by its limit. Let $C$ be a complicated expression whose limit as $x \to a$ needs to be evaluated. And let $S$ be one of the simple sub-expressions in $C$ whose limit as $x \to a$ is already known to be $L$.
1) You can replace sub-expression $S$ by its limit $L$ if the whole expression $C$ can be written as $C = R \pm S$ where $R$ is (rest of the) expression obtained when you literally remove $S$ from $C$. I call this situation as $S$ occurs in additive manner in the overall expression $C$.
2) You can replace sub-expression $S$ by its limit $L$ if $L \neq 0$ and if the whole expression $C$ can be written as $C = R \times S$ or $C = R/S$ where $R$ is (rest of the) expression obtained when you literally remove $S$ from $C$. I call this situation as $S$ occurs in multiplicative manner in the overall expression $C$. Also note that in this case $L$ must be non-zero. If $L = 0$ then you are out of luck.
These rules are almost always used (perhaps without knowing that such rules exist) during evaluation of a limit in step by step fashion. The best part about these two rules is that the replacement of $S$ by its limit $L$ is done without knowing anything about the rest of expression $R$. The replacements are valid irrespective of the fact that $R$ has a limit or not.
In the current question $$C = \dfrac{\cos x - \dfrac{\log(1 + x)}{x}}{x}, S = \frac{\log(1 + x)}{x}, L = 1$$ and when we remove $S$ from $C$ literally we get $$R = \frac{\cos x}{x}$$ Clearly we don't have $C = R \pm S$ or $C = R/S$ or $C = R\times S$ and hence it is not possible to replace $S$ by its limit $L = 1$.
At the same time if we write $C$ as $$C = \frac{\log(1 + x)}{x}\cdot\dfrac{\dfrac{x\cos x}{\log(1 + x)} - 1}{x}$$ then we can replace the first factor by $L = 1$ and $$R = \dfrac{\dfrac{x\cos x}{\log(1 + x)} - 1}{x}$$ and it is sufficient to calculate limit of $R$ and multiply it by $L$ to get the answer. However such a split does not help us because the expression $R$ does not seem to be any simpler compared to original $C$.

Note: The rules which I have mentioned above for replacing sub-expressions by their limits are something which I have explicitly written in my blogs and many answers on MSE. I have myself not found them in any textbooks but at the same time I have seen many solved examples in various textbooks which make use of these rules implicitly. They are easy to prove and I found it worthwhile to mention them explicitly for benefit of readers so that at least they can avoid the replacements which are not valid. A more formal version of these rules along with proofs is discussed in this question.
Comment: @Mathbg: your way is same as the one used here that's how both you and the asker here get the same expression $(\cos x - 1)/x$ after replacing $(\log(1+x))/x$ by its limit $1$.
Comment: I never thought about these rules in this way, I prefer indded take the limit all at once at the final step but it's a very nice pointing out!
Comment: @gimusi : for simple problems it does not matter, but for complicated expressions writing each sub-expression till the last step is clumsy and you need to write more. Replacing a sub expression early on with its limit simplifies the overall thing as well as reduces typing effort.
Comment: Can you please look into the following link (it's the same question) and tell me (maybe post an answer there) what's the error? Not sure but I think my solution does follow your way (or am I missing something?) but still here's an error. Link : https://math.stackexchange.com/q/2723256/322461
Comment: @ParamanandSingh Yes, but if you note, there's a small difference in what I did. What I did was somewhat $C=R+S\times T$ and then is we say that $C-R=C'$ then $C'=S\times T$ and we can replace $T$ by its limit (going by point (2) in your answer). What's wrong here?
Comment: @Mathbg: perhaps you did not get my point. The sub-expression $T$ (based on your comment) must occur in the overall original expression $C$ (and not $C'$) in either additive or multiplicative manner.
Comment: @Mathbg: what you are suggesting will work if your goal is to find limit of $C'=C-R$ and not for $C$.
Comment: Oh oh okay, got your points. Fine, that's cool. Thank you!
Answer: $\frac{\log(1+x)}{x}\neq 1$ it's undefined. And you can not directly take limit for only one part inside .
Comment: Exactly... The OP needs to use Taylor in this case
Comment: Yes you are right
Comment: ...Or l'Hospital's rule.
Comment: sure... But Taylor is more insightful: you really see the asymptotical interplay between the various parts. Hopital is a great trick, but you lose the whole "growth" part
Comment: Ya but many a times it's like officially banned in case of exams
Comment: @b00nheT Thank you. I think you're right and that is why many times students are asked to try it this or that way.
Comment: @ArchisWelankar Thank you. In my particular experience I've never seen such a thing. It may happen in weekly home assignments or papers, but never in exams once it has been studied. I wouldn't understand to ban in a final such a wonderful tool, either.
Comment: I personally love that method ;)
Answer: With l'Hospital:
$$\lim_{x\to0}\frac{x\cos x-\log(1+x)}{x^2}\stackrel{\text{l'H}}=\lim_{x\to0}\frac{\cos x-x\sin x-\frac1{1+x}}{2x}\stackrel{\text{l'H}}=$$
$$=\lim_{x\to0}\frac{-2\sin x-x\cos x+\frac1{(1+x)^2}}2=\frac{-0-0+1}2=\frac12$$
With Taylor series:
$$\frac{x\cos x-\log(1+x)}{x^2}=\frac1{x^2}\left(x-\frac{x^3}2+\ldots -x+\frac{x^2}2-\frac{x^3}3\ldots\right)=\frac12-\frac56 x+\ldots\xrightarrow[x\to0]{}\frac12$$
Comment: You can reduce the second expression by extracting known simple limits to $\frac12+\lim_{x\to0}\frac{\cos x-1}{2x}$.
Answer: we have $$cos(x)-1=\cos(x/2)^2-\sin(x/2)^2-1=-2\sin(x/2)^2-1$$


Student test statistic and self normalizing sum.

Question: I study the asymptotic distribution of self normalizing sums which are defined as
$S_n/V_n$ where
$S_n=\sum_{i=1}^n X_i$ and $V_n^2 = \sum_{i=1}^n X_i^2$
for some i.i.d RV's $X_i$.
Motivation to study such sums comes from the fact that the classical Student $T_n$ statistic could be expressed as:
$T_n(X)= \frac{\sum_{i=1}^n X_i}{\sqrt{\frac{n}{n-1}\sum_{i=1}^n (X_i-\overline X)^2}} = \frac{S_n/V_n}{\sqrt{\frac{1}{n-1}(n - (S_n/V_n)^2)}}$
From the paper I study (http://arxiv.org/pdf/1204.2074v2.pdf) I know that:

If $T_n$ or $S_n/V_n$ has an asymptotic distribution, then so does the other, and they coincide.

but it do not seem trivial for me. Can someone explain it?
I'm not sure if it is only showing that the denominator is equal 1 in probability and using the Slutsky-Theorem?
https://de.wikipedia.org/wiki/Slutsky-Theorem
Comment: Can you add a reference to the "paper I study"?
Comment: I added it above. The statement is at the very beginning of the section 1. Introduction.
Answer: The authors reference a 1969 paper by Efron. The relevant section in Efron appears to be a reference to what at that time was an unpublished paper by Logan, Mallows, Rice and Shepp (see p.16, last paragraph of Efron).
However, the article you are reading give the actual paper, published in 1973 :Limit distributions of self-normalized sums. They reference back to Efron's 1969 paper, where he uses Fisher's finding that the t-statistic is asymptotically normal under the 0-mean hypothesis as long as the vector of random variates have rotational symmetry.
Answer: The authors' claim can be proved using the Skorohod representation theorem. To prove one direction: if the ratio $R_n:=S_n/V_n$ converges in distribution to a limit $R$, then there exist variables $R_1^*, R_2^*, \ldots$ and $R^*$ with the same distributions as $R_1, R_2,\ldots$ and $R$ respectively such that $R_n^*\to R^*$ almost surely. The identity
$$
T_n = \frac{R_n}{\sqrt{\frac{1}{n-1}(n - R_n^2)}}\tag1$$
(note you have a typo in your formula) then shows that the correspondingly defined $T_n^*$ converges a.s. to $R^*$, and therefore $T_n$ converges in distribution to $R$.
Conversely, we can rearrange (1) to solve for $R_n$:
$$
R_n = {T_n\over\sqrt{\frac 1n(n-1+T_n^2)}}\tag2
$$
(please check my algebra). In view of (2) it is clear that if $T_n$ converges a.s. to a limit $R$, then so does $R_n$.


Unmarshalling file with problems. Part 2

Question: I have done what @Perception said me about URI of the schema, but now I have another exception. Does anyone know what is the problem? Lots of thanks.
I have this code from method Git60Manager.doImportMod1GtFile that unmarshall a file using a xsd template:
String schema = "///META-INF/templates/git60_data_mod1_def.xsd";
isr = new InputStreamReader(GIT60FileMod1.class.getResourceAsStream(schema));
Unmarshaller unmarshaller = new Unmarshaller(isr, main);

this is the xsd file:
<xs:annotation>
<xs:documentation xml:lang="en">
  GIT60 schema Mod 1 (Data)
</xs:documentation>
</xs:annotation>

<xs:include id="git60_mod1_def.xsd" schemaLocation="./git60_mod1_def.xsd" />

<xs:element name="mainData" type="GIT60FileMod1Data" jrb:length="100" />

<xs:complexType name="GIT60FileMod1Data">
    <xs:sequence>
        <xs:element name="git60Tax" type="GIT60FileTaxMod1" minOccurs="1" maxOccurs="unbounded"/>
    </xs:sequence>
</xs:complexType>

And this is the exception when I run the application, before I got a java.net.MalformedURLException:
 java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:61)
at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
at com.samelan.gitim.core.service.io.account.impl.GIT60Manager.doImportMod1GtFile(GIT60Manager.java:1256)
at com.samelan.gitim.core.service.managers.GtFileProcessorManagerTest.testProcFilesNewTemplateGit60(GtFileProcessorManagerTest.java:717)
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:592)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

Answer: GIT60FileMod1.class.getResourceAsStream(schema) is returning null.  It's happening because it can't find that resource.  It's worth skimming to documentation for this method.
Different things will happen if the class is run on it's own or if it's packaged into a JAR file.  Specifically, the root where it starts and how things are packaged will change.


Active admin redirects after login

Question: When an admin logs in, it automatically redirects to the main home page (i.e. not the admin dashboard).  I'm not sure why it does this or how to change it...
routes.rb
ActiveAdmin.routes(self)

  devise_for :admin_user, ActiveAdmin::Devise.config

  get "guidelines/topic"
  get "guidelines/topichospital"
  get "guidelines/topicspecialty"
  get "guidelines/favourite"
  get "profiles/show"
  get "guidelines/show"

root :to => 'guidelines#index'

my application_controller.rb has been changed to redirect after user login (but shouldn't be admin login) - is this the problem?
include PublicActivity::StoreController
  protect_from_forgery

def after_sign_in_path_for(resource)
 favourites_path
end

hide_action :current_user

Comment: what's in your controller where the `login` action is placed?
Comment: Oh, sorry, as I said i have never used devise. Try to find out where the login action for the Admin is and change the redirection path there.
Comment: have added from application controller - is that it?  Am using devise
Comment: in the `def after_sign_in_path_for` method you should write instead of `favourites_path` where you want it to redirect you to. I have never used devise, so i'm not sure if this is correct but try to replace the `favourites_path` with `admin_root_path`. Look at all of your routes with rake routes, and change the direction with the `_path` suffix in your method
Comment: but isn't this just redirecting after user login?  I want normal user login to redirect to favouries_path
Answer: Thanks to Zippie I found the answer.  In admin_controller.rb I added:
def after_sign_in_path_for(resource)
     admin_dashboard
end

Comment: To do this Rails 4.1 and ActiveAdmin 1.0.0.pre, use config.root_to in the active_admin initialiser.
Answer: I had to do this:
class ActiveAdmin::Devise::SessionsController
  def after_sign_in_path_for(resource)
    admin_dashboard_path
  end
end

to fix the issue.
It also opens some possibilities for customization if you need it.
Answer: if resource.class == User
  root_path
elsif resource.class == AdminUser
  admin_root_path
else
end

Active admin redirects after login


What beats does the horn typically play on in a 2/4 march?

Question: Wikipedia states:

French Horns tend to always carry the rhythmic backup of a march. For example, in cut-time marches, they are typically assigned upbeats (the + of 1 and 2) to provide the "pah" for the stylistic "oom-pah" sound. In 6/8 marches, French horns play on beat 1, the 'li' of 1, beat 2, and the 'li' of 2 (1-la-li 2-la-li). In other words, the measure would be one eighth note, then an eighth rest, then two eighth notes, an eighth rest, then a final eighth note.

However, what beats would the horn normally play on in a 2/4 march, the other major type? Is it the second?
Answer: 2/4 is isomorphic to cut time, and as the article excerpt states, they idiomatic french horn rhythm would occur on both of the upbeats in the measure.
In other words, the second and fourth eighth notes of a 2/4 bar.
Comment: In other words: off-beat
Comment: But it is not impossible to play the first and third eighth notes of a 2/4 bar once in a while.


How do we interpret the covariance matrices $\textbf{U}$ and $\textbf{V}$ in the Matrix Variate Normal Distribution?

Question: Consider the Matrix Normal Distribution. My first question is: how do we interpret the entries $\textbf{X}_{ij}$ of the random matrix $\textbf{X}(n\times p)$? My second question is: how do we interpret the so called covariance matrices $\textbf{U}$ and $\textbf{V}$? Finally, my third question is: how do we calculate the matrices $\textbf{U}$ and $\textbf{V}$?
Any help would be appreciated.
Answer: In the context of the Matrix Normal Distribution, the entries $X_{ij}$ are samples from the Gaussian distribution with mean $M_{ij}$. To fully characterise their variance though, we need two matrices $U$ and $V$ to set the joint distribution of the row and column vectors of the random matrix $X$. These two covariance matrices provide information about how the rows (via $U$) and columns (via $V$) covary with each other, thus capturing the dependencies within the matrix $X$. A higher value in the diagonal elements of $U$ implies greater variance within each row vector, while non-zero off-diagonal elements imply the covariance between different pairs of row vectors. (the analogy holds for $V$ but for columns) To that effect, if the row vectors were independent $U$ would be diagonal. (and similarly, if the column vectors were independent, $V$ would be diagonal)
To aid our understanding: let's start with a simple multivariate normal distribution, i.e. begin with just with a $k$-dimensional mean vector $\overrightarrow{\mu}$ and covariance matrix $\Sigma$ that is of dimensions $k \times k$. Then let's say we want to generate three rows of $k$ length in one go, i.e. our $X$ has dimensions $3 \times k$. In that case, $V = \Sigma$ and $U = I_{3 \times 3}$, $U$ controlling the covariance between the three rows and $V$ controlling the covariance between columns. Because we want just three independent rows, our covariance $U$ is an identity matrix.
Bringing this now altogether: The entry $X_{ij}$ is sampled independently from a Gaussian distribution with mean $M_{ij}$ and variances $U_{ii}$ (for the rows) and $V_{jj}$ (for the columns) and covariances $U_{ij}$ (across the rows) and $V_{ij}$ (across the columns).
Finally about the calculation of $U$ and $V$: They don't have a closed form so we cannot estimate them directly. That said, we can estimate the likelihood associated with any particular pair $U$ and $V$ so we can generate maximum likelihood estimates for them given a sample of matrix $X^1, X^2, \dots, X^n$ to find reasonable estimates. Both Python and R have packages estimating that likelihoood (for example scipy.stats.matrix_normal and matrixNormal respectively). I have also seen the paper: An expectation–maximization algorithm for the matrix normal distribution with an application in remote sensing by Glanz & Carvalho who use EM exactly based on that principle.
Comment: "*Should not $U_{ij}$ be a covariance matrix?*" The Kronecker product of $U_{ij}$ with $V$ is a (scaled) covariance matrix. (cause the Kronecker product of a scalar $\alpha$ and a matrix $B$ is just $B$ scaled by $a$). Look for example at this extreme case where $U$ is an identity matrix and $V$ is a scalar:
`library("matrixNormal"); set.seed(3); n = 6; p = 1; U = I(n); V = 2; M = matrix(rep(0,n*p), ncol=p);  A = sapply(1:1000, function(x) matrixNormal::rmatnorm(M=M, U=U, V=V));
paste0("Row variance is: ", apply(A,1, var),"." ); print("Row correlation is: ");print(cor(t(A)))` (cont.)
Comment: Our variance per row is fully controlled by $V$ scaling them so is $\approx 2$. Similarly, our rows are uncorrelated with each other because of $U$ is an identity matrix.
Comment: Thanks for the contribution. However there is still one question: how do we calculate the matrices $\textbf{U}$ and $\textbf{V}$? I did not understand why $\textbf{U} = \textbf{I}_{3\times 3}$ and $\textbf{V} = \Sigma$ in the proposed example.
Comment: As far as I understand, the covariance between vectors is a matrix.
Comment: Ooops sorry I forgot the calculation part. I will add commentary tonight.
Comment: Once again, thank you very much. In the particular example that you have proposed, how did you reach the exhibited result?
Comment: You're welcome. Sorry, I don't understand what you mean by this question, I just said we want to generate a random $3 \times k$ matrix $X$.
Comment: I am still a little bit confused when you say "because we want just three independent rows, our covariance $\textbf{U}$ is an identity matrix". As far as I know, when we calculate covariance between random vectors, the result is a covariance matrix. How can you associate a scalar such as $\textbf{U}_{ij}$ to the covariance between the $i$-th row and the $j$-th row? Should not $\textbf{U}_{ij}$ be a covariance matrix? It seems I am missing the interpretation of covariance between random vectors. Could you please elucidate this concept to me?
Answer: The $i$th column of $X$ has a covariance matrix $V_{ii}U$, and the $j$th row of $X$ has a covariance matrix $U_{jj}V$. Hence, you can think of $U$ as the covariance of the columns, and of $V$ as the covariance of the rows, both up to a constant. I would not go any further than this when interpreting them. They are "factors" of the true interpretable matrix $V \otimes U$.
$U$ has a closed form given $V$, and viceversa, so they are estimated iteratively. See https://doi.org/10.1080/00949659908811970
Comment: Thank you very much.
Comment: +1, I was trying to find that paper, and I remember reading it (long time ago) but couldn't locate it - I thought I was on disco biscuits about the whole thing. (I have since realised that it is also referenced in the relevant Wikipedia article which only adds insult to my (bibliographic) injury).


public file name encoding on windows

Question: I have to deploy a drupal 7 site built on Linux on a windows machine. Some (image) files are referenced via the public file mechanism. Some of them have special characters in their names, encoded in UTF-8 (AFAIK)
Files directly referenced are correctly handled by apache, for example:
http://localhost/lv/sites/all/themes/bizz/images/1.pr%C3%A9sentation.jpg
But the ones that are referenced via drupal public files cannot be accessed; for example http://localhost/lv/?q=sites/default/files/styles/large/public/2.teint%C3%A9_60_380X448_2.png&itok=RvL-USAY returns a 404
The file exists in the filesystem (as 2.teinté_60_380X448_2.png and as 2.teint├®_60_380X448_2.png [that was the name I got in the zip export file]) I tried 2.teinté_60_380X448_2.png (UTF-8 as latin-1) too, but without more luck.
Is there a way to get drupal finds these files without editing all posts ?
Comment: Do you check if /sites/default/files are given read and modify permission for IIS_IUSRS e.g. running C:\inetpub\wwwroot\Drupal>icacls sites\default\files /grant BUILTIN\IIS_IUSRS:(OI)(CI)(M)
Comment: It runs under apache
Comment: @Bastein Durel sorry I read your first sentence and automatically thinks that you are having problem with files on IIS under windows machine
Answer: I was wrong, 2.teinté_60_380X448_2.png works, now I only have to write a script that converts all filenames to utf8, and use it as latin-1, great :/

public file name encoding on windows


How to find the latest binlog of MariaDB by shell script?

Question: I want to find the latest mysql binary log in /var/log/mysql/, but I found the name of binlog is mariadb-bin.0000*, and we also have mysql-bin.index, so it's really hard for me to use shell script to distinguish them. My idea is finding binlogs by their file type, which is "Mysql replication log", then sort them by modification time, but I don't know how to do it.
Can anyone help me with that?
Answer: ls -1t /var/log/mysql/mariadb-bin.* will return you the list of files sorted, most recent first. That might be mariadb-bin.index.
If you want the last binlog only, you can combine it with grep -v (wich will exclude what you grep) and head.
ls -1t /var/log/mysql/mariadb-bin.* | grep -v "mariadb-bin.index" | head -n 1
Comment: I tried this one, but it shows mariadb-bin.index, not the binlog I want. In my case, the modification time of binlog and mariadb-bin.index is the same, so I want to distinguish them by their file types.
Comment: ah you wrote it's mysql-bin.index in your initial post. Then you should use ` ls -1t /var/log/mysql/mariadb-bin.* | grep -v "mariadb-bin.index" | head -n 1`
Comment: But what if there are many binlogs, which the number exceeds the limit?
Comment: I edited my comment just before yours


Remover itens um array que contém somente 1 caracter

Question: Tenho um seguinte array:
$arr = array('estrela', 'não', 'é', 'up','.','Evitem', 'estrelar',
'abobrinha', 'coisa', 'fugaz', 'de', 'interesse', 'praticamente',
'individual', 'conversa mole','.','Só', 'porque', 'é', 'engraçado',
'não','quer','dizer','que','é','importante','e', 'útil', 'para',
'todos', '.', 'O', 'objetivo', 'do', 'recurso', 'é',
'destacar', 'algo', 'importante','para','as', 'pessoas',
'que', 'não', 'são', 'frequentes', 'no', 'chat', 'abusar',
'dele', 'acaba', 'com', 'sua', 'utilidade', 'Ajam', 'como',
'comunidade', ',', 'pense', 'no', 'que', 'é', 'realmente',
'útil', 'para', 'todos', 'Também', 'não' ,'quer', 'dizer',
'que', 'nada', 'edianamente', 'fútil', 'não', 'pode', 'só', 'sejam',
'mais', 'seletivos', '.');

Gostaria de remover todos os itens do array que possui apenas 1 caracter. Por exemplo é, . , O, ,,etc; sendo letra ou até mesmo algum carácter especial como ,(virgula).
Como posso remover itens do array que contém somente 1 carácter dentre eles letras e caracteres especiais?
Answer: Você pode verificar o tamanho dos caracteres em um loop, e remover caso o valor seja um carácter.
Código:
<?php
    $arr = ["gato", "g", "stack", "ba", "t", "foo", "à", "é", "bar"];

    foreach($arr as $key => $value) {
        if (mb_strlen($value) == 1) {
            unset($arr[$key]);
        }
    }

    print_r($arr);

Saída:
Array
(
    [0] => gato
    [2] => stack
    [3] => ba
    [5] => foo
    [8] => bar
)

Saída com o seu array informado como entrada de dados:
Array
(
    [0] => estrela
    [1] => não
    [3] => up
    [5] => Evitem
    [6] => estrelar
    [7] => abobrinha
    [8] => coisa
    [9] => fugaz
    [10] => de
    [11] => interesse
    [12] => praticamente
    [13] => individual
    [14] => conversa mole
    [16] => Só
    [17] => porque
    [19] => engraçado
    [20] => não
    [21] => quer
    [22] => dizer
    [23] => que
    [25] => importante
    [27] => útil
    [28] => para
    [29] => todos
    [32] => objetivo
    [33] => do
    [34] => recurso
    [36] => destacar
    [37] => algo
    [38] => importante
    [39] => para
    [40] => as
    [41] => pessoas
    [42] => que
    [43] => não
    [44] => são
    [45] => frequentes
    [46] => no
    [47] => chat
    [48] => abusar
    [49] => dele
    [50] => acaba
    [51] => com
    [52] => sua
    [53] => utilidade
    [54] => Ajam
    [55] => como
    [56] => comunidade
    [58] => pense
    [59] => no
    [60] => que
    [62] => realmente
    [63] => útil
    [64] => para
    [65] => todos
    [66] => Também
    [67] => não
    [68] => quer
    [69] => dizer
    [70] => que
    [71] => nada
    [72] => edianamente
    [73] => fútil
    [74] => não
    [75] => pode
    [76] => só
    [77] => sejam
    [78] => mais
    [79] => seletivos
)

Talvez tenha que adaptar, porque vai depender da codificação que estiver usando, e outras coisas também pode influenciar nos resultados, mas já ajuda um pouco você.
Veja funcionando aqui.
Answer: Boa tarde. É só iterar o array e checar cada um dos valores pela função strlen, que retorna o tamanho da string. Caso ela retorne 1, você pode remover o elemento e trocalo por uma string vazia, ou o quê você preferir. No código eu também utilizei a função trim() para o caso de você querer remover strings como "   é {espaço em branco}"
Veja no código abaixo:
for ($i = 0; $i < count($arr); $i++) {
if(strlen(trim($arr[$i])) == 1)) {
$arr[$i] = "";

 }
}

Espero que tenha ajudado =)
Comment: @AckLay sem problema =)
Answer: Você pode utilizar a função array_filter.
Exemplo de uso:
$filtrado = array_filter($arr, function($item) {
    if(strlen($item) <= 1) {
        return false;
    }
    return true;
});

Comment: Por exemplo, se isso `strlen($item) <= 1` for verdadeiro ele já retorna `true`, então porque criar dois retornos? Entende o que quero dizer?
Comment: Porquê `strlen($item) <= 0` ? Tem como explicar melhor?
Comment: Foi um erro de digitação. Deveria ser ```<= 1```. Editei a resposta para ficar de acordo.
Comment: Acho que sua abordagem é boa, mas ainda dá para otimizar.
Comment: A função array_filter é escrita em C, somente a sua função de callback é php. Não consigo ver uma forma de otimizar mais este código.
Comment: Cuidado com [microotimizações](http://pt.stackoverflow.com/questions/29507/at%c3%a9-que-ponto-a-otimiza%c3%a7%c3%a3o-prematura-%c3%a9-um-problema/29519#29519)
Comment: Concordo que pode ser usado também, mas eu preferi deixar o exemplo mais simples. Não se preocupe que eu nao tenho problemas com criticas :)
Answer: Se está preocupado com performance ("Estou procurando algo também em questão de performance.") não deve utilizar o strlen(), utilize o empty() ou isset(), em seu lugar, a diferença é minuscula, mas existe.
function remover_palavra_curta(string $string) : bool{
   return isset($string[1]);
}

$arr = array_filter($arr, remover_palavra_curta);

Em comparação, obtive este resultado, em ordem de isset, strlen e o mb_strlen.
array(3) {
  [0]=>
  float(0.77282905578613)
  [1]=>
  float(0.81824898719788)
  [2]=>
  float(1.5776748657227)
}

Utilizei este método aqui para isto. O 0 é o isset, o 1 é o strlen e o 2 é o mb_strlen.

O isset e o strlen tem problema com o é por exemplo, uma vez que:
$texto = 'é';
var_dump( strlen($texto) === 2 );

Resposta, como esperado:
bool(true)

Isso também ocorre com o isset(), o $texto[1] também existe. Para corrigir isto apenas utilizando o mb_strlen, ou poderia utilizar o ctype_alpha($texto[1]), mas o ganho de performance seria totalmente anulado, sendo mais rápido o uso do mb_strlen.

Para ter o que quer deve abrir mão de performance e utilizar o mais lento, mb_strlen, ele remove todos o é assim como o ., como deseja, portanto:
function remover_palavra_curta(string $string) : bool{
   return mb_strlen($string) >= 2;
}

Comment: `mb_strlen($string) > 2` retorna valores com tamanho 2 certo?
Comment: Eu queria editar aquele meu comentário, mas ultrapassei o tempo de edição então acabei deletando. Mas é isso mesmo, em questão de performance.
Comment: Seria `>=` na verdade, mas é isso. Para que torne `true` quando for `>= 2` e `false` quando não, assim removendo o que for menor do que `2`.


Module not found: Error: Can't resolve 'crypto' in 'C:\

Question: ERROR MESSAGE:
Compiled with problems:X

ERROR in ./node_modules/@solana/spl-name-service/dist/utils.js 16:17-34

Module not found: Error: Can't resolve 'crypto' in 'C:\Users\...\node_modules\@solana\spl-name-service\dist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
    - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "crypto": false }

Where the problem started:

I tried using getParsedNftAccountsByOwner() from:
https://github.com/NftEyez/sol-rayz
Then, I got this error message.

My project:

getParsedNftAccountsByOwner()
React, Typescript project
Libraries used: @solana/web3.js | @nfteyez/sol-rayz
webpack 5.67.0

Even though I was able to resolve these errors in a few minutes, the 'crypto' one is different:
Stream problem:
ERROR in ./node_modules/cipher-base/index.js 3:16-43

Module not found: Error: Can't resolve 'stream' in 'C:\Users\...\node_modules\cipher-base'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
    - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "stream": false }

assert problem:
ERROR in ./node_modules/@solana/spl-name-service/dist/utils.js 14:33-50

Module not found: Error: Can't resolve 'assert' in 'C:\Users\...\node_modules\@solana\spl-name-service\dist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "assert": require.resolve("assert/") }'
    - install 'assert'
If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "assert": false }

What I have done so far:

I tried performing the two suggestions from the error message, and it didn't work

I tried the first two solutions already:
"compilerOptions": {
"baseUrl": "./",
"paths": {
"crypto": [
"node_modules/crypto-js"
]
}

Module not found: Error: Can't resolve 'crypto'

I tried this solution:
"browser": {
"crypto": false
}

https://github.com/tensorflow/tfjs/issues/494#issuecomment-481636128

I tried this solution: node-polyfill-webpack-plugin

https://stackoverflow.com/a/65556946/18007508
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")
module.exports = {
        // Other rules...
        plugins: [
            new NodePolyfillPlugin()
        ]
    }

My Code:
webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")
module.exports = {
  entry: "./src/components/index.tsx",
  target: "web",
  mode: "development",
  output: {
    path: path.resolve(\__dirname, "build"),
    filename: "bundle.js",
  },
  resolve: {
    extensions: [".js", ".jsx", ".json", ".ts", ".tsx"],
    fallback: {
      "crypto":require.resolve('crypto-browserify') ,
    }
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        loader: "awesome-typescript-loader",
      },
      {
        enforce: "pre",
        test: /\.js$/,
        loader: "source-map-loader",
      },
      {
        test: /\.css$/,
        loader: "css-loader",
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(\__dirname, "src", "components", "index.html"),
    }),
    new MiniCssExtractPlugin({
      filename: "./src/yourfile.css",
    }),
    new NodePolyfillPlugin()
  ],
};

package.json
{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@headlessui/react": "^1.4.3",
    "@heroicons/react": "^1.0.5",
    "@nfteyez/sol-rayz": "^0.9.1",
    "@nfteyez/sol-rayz-react": "^0.9.1",
    "@solana/spl-name-service": "^0.1.3",
    "@solana/wallet-adapter-base": "^0.9.2",
    "@solana/wallet-adapter-react": "^0.15.2",
    "@solana/wallet-adapter-react-ui": "^0.9.4",
    "@solana/wallet-adapter-wallets": "^0.14.2",
    "@solana/web3.js": "^1.32.0",
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.4.0",
    "@types/node": "^16.11.19",
    "assert": "^2.0.0",
    "axios": "^0.25.0",
    "browser": "^0.2.6",
    "crypto": "^1.0.1",
    "crypto-browserify": "^3.12.0",
    "crypto-js": "^4.1.1",
    "install": "^0.13.0",
    "node-polyfill-webpack-plugin": "^1.1.4",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-redux": "^7.2.6",
    "react-router": "^6.2.1",
    "react-router-dom": "^6.2.1",
    "react-scripts": "5.0.0",
    "redux": "^4.1.2",
    "redux-thunk": "^2.4.1",
    "store": "^2.0.12",
    "stream": "^0.0.2",
    "stream-browserify": "^3.0.0",
    "styled-components": "^5.3.3",
    "three": "^0.136.0",
    "web-vitals": "^2.1.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@types/react": "^17.0.38",
    "@types/react-dom": "^17.0.11",
    "@types/react-redux": "^7.1.22",
    "@types/react-router-dom": "^5.3.2",
    "@types/styled-components": "^5.1.20",
    "autoprefixer": "^10.4.2",
    "awesome-typescript-loader": "^5.2.1",
    "css-loader": "^6.5.1",
    "html-webpack-plugin": "^5.5.0",
    "mini-css-extract-plugin": "^2.5.0",
    "postcss": "^8.4.5",
    "source-map-loader": "^3.0.1",
    "tailwindcss": "^3.0.15",
    "typescript": "^4.5.4",
    "webpack-dev-server": "^4.7.3"
  }
}

Answer: I think that because your create react app (CRA) does not recognize your webpack.config.js. Your setting for polyfills is correct. Setting up node-polyfill-webpack-plugin itself is enough to load all node core polyfills.
In order to modify the webpack.config.js in CRA, you have to run
   npm run eject

this will create a config directory and inside you will have webpack.config.js which has almost 1000 lines of code. Inside that file, setting up node-polyfill-webpack-plugin should be enough.
Comment: there are major consequences to eject, I would recommend reading about it before you do it


Converting $\sin(A)+\cos(B)$ to a product?

Question: Similar to,
$$ \sin(u) + \sin(v) = 2 \sin \left(\frac{u+v}{2}\right) \cos \left(\frac{u-v}{2}\right)$$
$$ \cos(u) + \cos(v) = 2 \cos \left(\frac{u+v}{2}\right) \cos \left(\frac{v-u}{2}\right)$$

Are there combination laws for expressions such as:
$$ \sin(A) + \cos(B)$$

where $A,B$ are some real angles?
Comment: Use $\cos B=\sin(B+\frac{\pi}2)$.
Comment: Thank you very much
Answer: From the comment by @Andrei
$$ \sin(A) + \cos(B) =  \sin(A) + \sin( \frac{\pi}{2} -B)= 2 \sin \left( \frac{A-B}{2} + \frac{\pi}{4} \right) \cos \left( \frac{A+B}{2} - \frac{\pi}{4} \right)$$


Standard ML binary tree type

Question: I'm studying ML in class and I've run into a homework problem I am stuck on. I've spent all day yesterday searching but made little progress and we did not talk about this in class, so I am hoping you guys can help me.
We are given:
datatype which = STRING of string | INT of int

Part 1. We are told we need to create another datatype named whichTree for a binary tree containing the values of type which where data is only at the leaves of the tree.
Part 2. We need to create a whichSearch function having type whichTree -> int -> bool returning true or false based on whether the int is in the tree.
This is what I have so far:
datatype which = STRING of string | INT of int;
datatype whichTree = Empty | Node of int*whichTree*whichTree;

val t1 = Node(6, Node(4,Empty,Empty), Node(15, Node(11,Empty,Empty), Node(24,Empty,Empty)));
val t2 = Node(157,Empty,Empty);
val t3 = Node(102,t1,t2);

fun whichSearch (i, Empty) = false
| whichSearch (i, Node(entry, left, right)) =
    if i = entry then true
    else whichSearch (i, left)
    orelse whichSearch (i, right);

The problem I am now facing is this:

My whichTree does not contain the type which. I am not sure how I can fix that.
I should have my whichSearch function of type whichTree -> int -> bool but it is int * whichTree -> bool and am working on trying to figure out how to fix things. I am not sure how I would go about fixing this as I have to specify a value for i in whichSearch to search for. I'm searching on this but any tips would be great.

Can anyone help? If so thank you! And thank you to the guys who already responded.
Answer: Based on what you've come up with, I think I should point out a few rules in the Standard-ML language that you are breaking, which I hope will make it easier for you to procede:

Each name you introduce, be it a type, function or variable, can only mean one thing (as long as they are in the same scope in the program).

You break this by first defining a datatype which and then defining a function by the same name.
You also break it by first defining a datatype whichTree and then defining another datatype by the same name.
You actually also break it on the 3rd line, by introducing two new datatype constructors (STRING and INT) that were already introduced on the 1st line. Remember that when you use these datatype declarations, you're not only defining a type name but also the constructors for the type.

If you wish to introduce a datatype constructor taking two parameters, which it looks as though you want to do on line 3, you should use an asterisk * between the types, not the arrow operator ->.

I would also agree with Victor, you should think in general terms about what a binary tree actually is, conceptually. Then translate this into Standard-ML.

Edit after the code in the question was rewritten: Your new code is much better. As you point out, you stand now with two questions:

How do you make the tree a tree of which values? Well, your tree is currently a tree of int values, so doesn't it make sense that you should change int for which? But you also state that your tree datatype should be "a binary tree containing the values of type "which" where data is only at the leaves of the tree". This is distinct from what you've currently coded, which keeps an int at every non-leaf node. The non-leaf nodes are determined by the recursive case in the datatype declaration, while the leaf nodes are determined by the non-recursive case.
A function of type (A * B) -> C (where A, B and C are types) can be rewritten to be of type A -> B -> C. Both are valid and usable in Standard-ML, but the second form is usually preferred in functional programming languages because it allows a technique known as currying, which means "partial function application". To make the change, you basically write parameters in a different way: Instead of myFunction(a, b), you write myFunction a b -- both where you define the function and where you use it.

Note that I suggest you handle point 2 later, first focus on getting the datatypes correct and getting a working search function, then you can change its type when you know it's otherwise correct.
Comment: I redid things on paper and found a few other tutorials I use. I am on the right track now. The real issue is I do not know much about datatype declarations other than what I've learned yesterday and today. I am getting closer and will have to search on how to define one datatype by another as you are suggesting.
Comment: I expanded my answer based on your amended question. Remember that on Stack Overflow, you are supposed to give votes to helpful answer and accept an answer at the end.
Answer: Forget about ML. Using pen and paper (or marker and white board), can you explain how a binary tree containing your data in the leaves would look like? Can you explain in broad terms how you would search for an element in the tree? (hint: a search needs to traverse nodes by deciding whether to go left or right, so you need to keep some information in the tree nodes to help the search algorithm decide).
Once you ave the representation and algorithms laid out as english sentences, translating them to SML will be easier.
Comment: The issue i was having was figuring out how to create trees in ML. I am aware that my old code looked very strange but I was guessing. I'm on the right track now and have my code looking left and right. Thank you for the advice. In a few hours hopefully I can do the same things to correct my types and then all will be well :)

Standard ML binary tree type


Proof that $g(p)$ unbiasedly estimable only if it is a polynomial (Binomial Distribution)

Question: In Lehmann-Casella (Theory of Point Estimation) they state without proof that if $T \sim Bin(n,p)$, then $g(p)$ is estimable only if it is a polynomial in $p$ of degree $\leq n$. How does one go about proving this?
Here is their somewhat justification:

In fact, it follows from Equation (1.2) that a function $g(p)$ can be U-estimable only if it is a polynomial of degree $\leq n$. Let $\delta(k)$ be the estimator. Then $g(p)$ has to satisfy Eqn 1.2:
$$(1.2) ~~~~~~~\sum_{k=0}^n \delta(k) {n \choose k} p^k (1-p)^{n-k} = g(p), ~\forall 0 < p < 1.$$
Comment: https://stats.stackexchange.com/questions/87107 shows the method.
Answer: The left-hand-side of $(1.2)$ is a weighted sum of polynomials with degree $n$, which is itself a polynomial of degree (no greater than) $n$.  If you want to see this more clearly then you can use the binomial theorem to write it in its explicit form:
$$\begin{align}
LHS
&\equiv \sum_{k=0}^n \delta(k) {n \choose k} p^k (1-p)^{n-k} \\[12pt]
&= \sum_{k=0}^n \delta(k) {n \choose k} p^k \sum_{i=0}^{n-k} {n-k \choose i} (-p)^i \\[12pt]
&= \sum_{k=0}^n \sum_{i=0}^{n-k} {n-k \choose i} {n \choose k} (-1)^i \delta(k) p^{k+i} \\[12pt]
&= \sum_{k=0}^n \sum_{r=k}^n {n-k \choose r-k} {n \choose k} (-1)^{r-k} \delta(k) p^r \\[12pt]
&= \sum_{r=k}^n \Bigg[ \sum_{k=0}^n {n-k \choose r-k} {n \choose k} (-1)^{r-k} \delta(k) \Bigg] p^r. \\[12pt]
\end{align}$$


Can I chain commands together with gm for node.js?

Question: Can I chain two or more commands together when using gm, the GraphicsMagick library for node?
Specifically, I've got an image that I'd like to add text to, then put a watermark on it, but nothing I try seems to work.
I've tried using gm(image).drawText(0,0,"Text").composite(logo) ... but that tells me Unrecognized option (-draw). Similar thing when I composite first, then draw text.
I also tried writing the file, then adding the .drawText call to the end, but that didn't work.
So can I chain two or more commands together?
Answer: Yes, you can, but not in this situation. You can make some workaround calling gm twice and piping result of first call to another:
const stream = require('stream');
const passThrough = new stream.PassThrough();

gm(image).drawText(0, 0, 'Text').stream().pipe(passThrough);
gm(passThrough).composite(logo).write('./output.png', e => console.log(e || 'OK'));

To be honest gm library sucks. If you don't know anything about GraphicsMagick, gm fails to provide good enough abstraction to hide it. You are constantly forced to use constructions like .resize(240, 240, '!') which make no sense unless you know syntax of GraphicsMagick's -resize option. That's because when you call gm's method it just appends option to some GraphicsMagick command which will be called when you execute .write() method, and this is one of these situations when this approach fails. GraphicsMagick provides few commands which supports different options. Most commonly used command is convert, it supports for example -draw option which is used by .drawText() method. Another command is composite which is used for merging to images together - it doesn't support -draw option. When you use .composite() method gm uses composite command so .drawText() methods starts failing. So, you can chain methods like .drawText() and .resize(), but not .drawText() and .composite().
Comment: I'll give that a shot. I wasn't sure if the async nature of node would get in the way. GM seemed non-ideal, but because I'm watermarking timelapse shots as they're taken, it's a decent solution.
Answer: You can use toBuffer and passe it to the next gm call (this particular code is not tested but I have used a similar technic of AWS Lambda).
gm(image)
  .drawText(0, 0, 'Text')
  .toBuffer('PNG',function (err, buffer) {
    if (err) return handle(err);
    gm(buffer)
      .composite(logo)
      .write('./output.png', e => console.log(e || 'OK'));
    console.log('done!');})


Prove $\{0^k10^k10^k1 \in \{0,1\}^* \mid k \geq 0 \}$ is not context free

Question: I'm practising for my CS exam and got stuck on this problem
$$ \{0^k10^k10^k1 \in \{0,1\}^*\mid k ≥ 0\}. $$
I think I have good start however I don't know how to proceed. I assume the L is context free, and that pumping lemma applies with some pumping length $n$.
$$|w| = 3k,\quad w = uvxyz$$
Since $|vxy| \geq n$ it can't contain all characters. Considering $uv^2xy^2z$ would end up having more than $3$ zeros if anything is pumped in. However I'm not sure how t o move from here. Is that enough of a proof?
Comment: This is basically the same question as https://math.stackexchange.com/questions/330377/showing-the-following-language-is-not-contex-free
Answer: Proof that $L$ is not regular
Assume that $L$ is regular, then there exists $p$ such that for all $|w|\geq p\:, \exists x,y,z, \: y\neq \varepsilon \text{ and } \forall k, \: xy^kz \in L$.
Take $n>p$ (we're not going to be subtle here. Then $w=0^n10^n10^n1 \in L$, so we can slice it into three part $x,y,z$. Let us consider $y$

if $1 \in y$ then $xy^kz \not\in L$, for it would contains to many $1$'s

otherwise, $y=0^d$ for some $d$, but then $xy^kz = 0^{n_1} 1 0^{n_2} 1 0^{n_3} 1 \not\in L$ because the $n_i$ won't be equal anymore.

Hence we cannot apply the pumping lemma for regular languages, $L$ is therefore not regular.

Proof that $L$ is not context-free
as suggested by @posilon, we can also prove that the language is not context free by applying this pumping lemma
There exists a $p$ such that, if $|w|\geq p$ then we can slice $w = uvwxy$
such that:

$|vx| \geq 1$

$|vwx| \leq p$

$uv^n wx^n y \in L$ for all $n \geq 0$.

here again, let us consider the number of $1$'s in $vx$

if $1 \in vx$ then $uv^n wx^n y  \not\in L$, for it would contains to many $1$'s

otherwise, $v=0^d, x=0^{d'}$ for some $d,d'$, but then $uv^n wx^n y  = 0^{n_1} 1 0^{n_2} 1 0^{n_3} 1 \not\in L$ because the $n_i$ won't be equal anymore.

Hence we cannot apply the pumping lemma for context-free languages, $L$ is therefore not context-free.
Comment: I think the OP wants to show that $L$ is not context-free, so the [pumping lemma for context-free languages](https://en.wikipedia.org/wiki/Pumping_lemma_for_context-free_languages) will be useful.
Comment: You are welcome! I think that in your second proof, two occurrences of $y$ should be replaced by $v$ (at $1 \in yx$ and $y=0^d$).
Comment: you're obviously right, thanks a lot
Comment: Yes sorry, I wanted to prove that L it's not context free, updated.


use index in ItemSeperatorComponent

Question: I am trying to use the current index in ItemSeparatorComponent as shown below, however index is always empty and never returns a value, but item is successfully populated. I'd really appreciate it if anyone can point out what I'm doing wrong here?
<FlatList
          numColumns={1}
          data={messages}
          keyExtractor={(item) => item.id.toString()}
          renderItem={({item}) => <OFChatBubble message={item} />}
          ItemSeparatorComponent={(item, index) => (
            <DateSeparator item={item} index={index} />
          )}
/>

Answer: To debug correctly you can try to add a debugger like this
ItemSeparatorComponent={(item, index) => {
  debugger

  return (
    <DateSeparator item={item} index={index} />
  )
}}

Open Chrome with the source tab opened to figure out the format of data={messages}
Comment: `messages` is an array of objects - FlatList sees each object as an `item` at the `index` of this array - `renderItem` knows the index, it appears `ItemListSeparator` does not.
Answer: I'm pretty sure you just forgot the { }around the params in the arrow function you passed to ItemSeparatorComponent
The code should be:
ItemSeparatorComponent={({item, index}) => (
        <DateSeparator item={item} index={index} />
)}

Edit:
I was wrong ItemSeparatorComponent does not get the same props as renderItem. It gets highlighted:boolean, leadingItem:<an object from the data you pass in> but you still need to use { } in order to get them
Comment: I just checked it on my machine and I was wrong apparently you get an object like this:`"highlighted": false,
  "leadingItem": Object {
  },`
Comment: Hey, thanks for the response! I tried wrapping the params but this results in the properties both returning `undefined`

use index in ItemSeperatorComponent


Need help running Hello World in intelliJ IDEA IDE

Question: I've installed intelliJ idea and am trying to run hello world, but I keep getting a popup for edit configurations. I have no idea what to do next. I had this installed on another computer and it was running properly. I've attached screenshots of my workspace
My workspace image attachment, click here
I'm getting the following error when I try to run HelloWorld.java, I don't know what this means, screenshot attached
Error when running
Answer: You'll need to add a Run configuration using that Edit Configurations popup.
https://www.jetbrains.com/help/idea/2016.3/creating-and-editing-run-debug-configurations.html
https://www.jetbrains.com/help/idea/2016.3/run-debug-configuration-application.html
As for your runtime error, I can't tell from here but I'd start with putting your source files under the src/ folder.
Comment: It's weird when I have a HelloWorld.java file it's not running, when I refactor and rename the file to HelloWorld2.java, everything is working fine.

Do you know why this is happening?


To check convergence of the sequence. I know Rate of growth of an exponential function is greater than a polynomial

Question: Consider this sequence $$ a_n=(1+n)^{100}*e^{-√n}$$
Then sequence $<a_n>$ still follows that exponential term will be the dominating term being the exponent have a root?
I know exponential growth is higher than a polynomial function but here the exponential itself have a root in its power . It is the whole issue . I tried using L'Hôpital's rule & differentiate it 100 times & got a bunch of fractions but could not conclude anything. Tried using desmos to plot it ,it reaches infinity. But everyone I have asked say that it will converge to 0 because of the denominator as exponential.Then I plotted numerator & denominator separately & see where they intersect & exponential function crosses the polynomial & become dominating term .But they intersect only at 0 & 0.0001 & rest the denominator curve lags behind the numerator curve i.e. polynomial. Suggestions will be appreciated this is their graph plotted by desmos, behaviour of the two functions in the graph is same for higher values of x too as is zoomed out as it is limit in software
Comment: Your $a_n$ has no n in it? if x=n than use the series for the exponential function for exponent >100.
Comment: Apologies, I was working on it on plotting it on desmos so interchanged n by x , but edited that now
Answer: To get a sense of the end behavior of the function, we can substitute $n^2$ for $n$ as when $n^2$ approaches infinity $n$ also approaches infinity for positive values of $n$. With that we get $(1+n^2)^{100}e^{-\sqrt{n^2}}$. Rearranging and simplifying we get $\frac{(1+n^2)^{100}}{e^n}$ and keeping only the highest order terms we get $\frac{n^{200}}{e^n}$. Since, as previously mentioned, the exponential term is stronger than the polynomial term, the limit as n approaches infinity is 0.
The reason that Desmos doesn't show this is because by the time the value starts decreasing again, the values involved are too much for it to handle and so they will not be graphed (If you tell Desmos to calculate a value like $a_{1000000}$ explicitly, it simply returns an error). The numerator and denominator do, in fact, equal each other at around $n=2.12*10^6$. This can be found by taking the logarithm of both sides to get $100ln(n+1)=\sqrt{n}$ so that the numbers aren't so big.
Comment: (+1) Strictly speaking, your argument for $\lim a_n=0$ is not complete: you only proved that the *subsequence* $(a_{n^2})$ converges to $0.$ This can easily be fixed by saying that $a_n=f(\sqrt n)$ for a *function* $f$ such that $\lim_{+\infty}f=0.$
Comment: This gives me hint that if I consider the given sequence as a series instead,whose sequence off partial sum is this given $n $ then apply logarithmic test for convergence of series & if that series converge then by necessary condition of convergence say that limit ( x tends to ∞) SOPS is zero. Is this approach right?


I can not save from PhpStorm to WSL2

Question: I am new in Linux (Ubuntu 20.04 WSL) and I got a problem hopefully you can help me.
I can create a file from PhpStorm like index.php or anything, but I can not oversave an existing file. The message is

Unable to save settings. Failed to save settings.Please restart PhpStorm.

I tried switch off Windows Firewall, but did not work.
I did reset a few times WSL and reinstall PhpStorm but did not work.
The Notepad++ can save files to the shared folder (user/Jon/.azure).
Comment: Looks like it was a permission issue. Thanks your help.
Comment: Try resetting PhpStorm settings (if you reinstall PhpStorm and did not select to delete the settings then they will be preserved). `File | Manage IDE Settings | Restore Default Settings...`
Comment: I tried it, but it is not working. I am only using Windows 10 Home edition. Can be the problem?
Comment: In such case use `Help | Contact Support...` from PhpStorm and privately provide any requested information there.
Answer: try to set to login in wsl as root from CMD terminal -> ubuntu20 config --default-user root

I can not save from PhpStorm to WSL2


In windows server R2 2008 appears ati eeu maximum number of session has been surpassed error

Question: Environment:windows server 2008 R2 Enterprise (remote desktop server role)
About 100 users connect remotely to the server via mstsc
in Application Log fond a lot of error event (id:16391)
i don't know how to solve it
Please expert advice !
Comment: much connection. so license. many id. find source?
(The error event id is useless without knowing the application from where it came. Please show the entire error.)
Answer: I haven't found the solution yet but I can tell you through testing I have isolated that it occurs every time someone logs on to the server via RDP.
Maybe an issue with video settings between client and server?
Comment: This isn't an answer - it belongs in the comments.


Adicionar novas checkboxes com ajax

Question: Olá, estou com um problema em meu código, é um pouco complicado de explicar, mas irei tentar. Meu objetivo é o seguinte, ao clicar nas checkboxes, um alvo é selecionado e adicionado na textarea abaixo, até aí tudo bem. Entretanto, tenho uma outra parte do código que adiciona novas checkboxes as já existentes. Ao clicar no botão as checkboxes são corretamente adicionadas, mas, ao clicar nas novas checkboxes, nada parece acontecer. Por outro lado, se eu clico nas checkboxes já existentes, o valor das novas é corretamente adicionado na textarea.
Segue imagem do problema:

Marcar alvo 1 funcionando adequadamente
ALVO4 adicionado, mas ao marcar nada acontece
Ao marcar também o alvo1, o ALVO4 aparece corretamente.

Obs: Se o ALVO4 for marcado após o alvo1, nada acontece
script.js:
  $(document).ready(function(){
  var checkTest;
  var text;

  $('#addAlvos').click(function() {
        text = $('#textAlvo').val();
        var container = $('#listaAlvos');
        var labels = container.find('label');
        var id = labels.length+1;

        $('#listaAlvos').append('<input class="checkbox" type="checkbox" name="alvo[]" id="checkboxes-'+id+'" value="'+text+'">'+text+'');

      });

      $('.checkbox').on('click', function(){
          checkTest = new Array();
          $("input:checkbox:checked").each(function() {

              checkTest.push($(this).val());

          });
          $.ajax({
            type:'POST',
            url:'gerar_alias.php',
            dataType: 'html',
            data:{target_name: checkTest,
            success:function(html){
              $('#textarea').val(html);
              }
            });
        });
      });

HTML

            Alvo(s)

                <input class="checkbox" type="checkbox" name="alvo[]" id="checkboxes-0" value="alvo1">
                alvo1

                <input class="checkbox" type="checkbox" name="alvo[]" id="checkboxes-1" value="alvo2">
                alvo2

                <input class="checkbox" type="checkbox" name="alvo[]" id="checkboxes-2" value="alvo3">
                alvo3

              <input id="textAlvo" type="text" class="form-control" placeholder="Adicionar Alvo" aria-label="Adicionar Alvo" aria-describedby="basic-addon2">

                <button id="addAlvos" class="btn btn-success" type="button">Add</button>

                  <textarea class="form-control" id="textarea" name="textarea" placeholder="!i a"></textarea>

gerar_alias.php:
  $alvo = $_POST['target_name'];

  $multiAlvos = implode(' ', $alvo);

  echo 'Atacar '.$multiAlvos;

Espero que consigam compreender o problema, qualquer outra dúvida eu esclareço. Muito obrigado.
Answer: O bind só está sendo aplicados aos elementos que já estão carregados na tela, ou seja,depois de adicionar o elemento dinamicamente ele não é reconhecido.
Altere a seguinte linha de código
      $('.checkbox').on('click', function(){

para dessa forma
      $('#listaAlvos').on('click', '.checkbox', function(){

Assim o evento estará atrelado ao elemento com id "listaAlvos" e todo elemento adicionado dentro dele com a classe "checkbox" será reconhecido.
Comment: não resolve, aí você só está mudando o seletor e o problema é relacionado ao momento em que o trecho é executado.
Comment: Na verdade, resolveu sim, agora está funcionando adequadamente.
Comment: Muito obrigado JrD. Funcionou perfeitamente. Você não tem noção do quanto eu quebrei a cabeça pra resolver...e no final o problema era só em uma linha... Obrigado novamente.
Answer: Você só faz o bind do evento nos checkboxes que já estão presentes no carregamento da página mas não naqueles que são adicionados dinamicamente... Um atalho é utilizar um método para a rotina do evento e declarar no próprio html ou fazer o bind a cada vez que for adicionar um novo.
Veja no exemplo abaixo, passei a rotina de click para o método checkboxClick e adicionei via atributo no append do novo elemento <input class="checkbox" onclick="checkboxClick" type="checkbox" name="alvo[]"...
$(document).ready(function(){
    var checkTest;
    var text;

    $('#addAlvos').click(function() {
        text = $('#textAlvo').val();
        var container = $('#listaAlvos');
        var labels = container.find('label');
        var id = labels.length+1;

        $('#listaAlvos').append('<input class="checkbox" onclick="checkboxClick" type="checkbox" name="alvo[]" id="checkboxes-'+id+'" value="'+text+'">'+text+'');
    });

    $('.checkbox').on('click', checkboxClick );
});

let checkboxClick = function(){
        checkTest = new Array();

        $("input:checkbox:checked").each(function() {
          checkTest.push($(this).val());
        });

        $.ajax({
            type:'POST',
            url:'gerar_alias.php',
            dataType: 'html',
            data:{target_name: checkTest,
            success:function(html){ $('#textarea').val(html); }
        });
    }

Comment: Muito obrigado por responder, acabei não testando a implementação, pois a resposta do JrD foi suficiente para sanar o problema. De qualquer forma, agradeço demais a atenção.

Adicionar novas checkboxes com ajax


Conversão de float para str sem perder as duas casas decimais e mudando o separador decimal

Question: No Python, preciso converter um float para string e substituir o ponto por vírgula, sem perder as duas casas decimais. Já tentei de várias formas, mas não consegui.
Ao fazer:
>>> str(10.00).replace('.',',')

O retorno é:
'10,0'

Mas preciso que seja:
'10,00'

Alguém tem alguma ideia de como fazer isso de forma prática?
Ou seja, mantendo o padrão de formatação com duas casas decimais após a vírgula.
Pensei em criar uma função, que iria avaliar a quantidade de itens após a vírgula, e se houvesse um, concatenaria com zero, se houvesse dois números decimais, não faria nada. Mas acredito que existe um jeito mais 'inteligente' de fazer isso no python, talvez algo semelhante ao que é feito em alguns bancos de dados, exemplo: to_char(10.00, '9999999999D99').
Comment: Acho que pode ajudar: [Como limitar números decimais em Python?](https://pt.stackoverflow.com/q/176243/125486).
Answer: Se você está utilizando IDLE pode utilizar o seguinte código
>>> str(f'{float(10.00):.2f}').replace('.', ',')

Neste caso a saída será:
'10,00'

Agora se você quiser implementar um script pode utilizar o seguinte código:
n = float(input('Digite um valor real: '))
print(str(f'{n:.2f}').replace('.', ','))

OBSERVAÇÃO
Neste último caso a saída também será do tipo string. Se você pedir para exibir o tipo de variável será exibido o tipo str.
Answer: Uma opção é usar locale.format (até Python 3.6), ou locale.format_string (a partir do Python 3.7, pois nesta versão locale.format se tornou deprecated):
import locale

locale.setlocale(locale.LC_ALL, 'pt_BR.utf8')
print(locale.format_string('%.2f', 10.00)) # 10,00

Primeiro eu uso setlocale para indicar que quero usar o locale pt_BR (Português do Brasil), no qual o separador decimal é a vírgula. Depois, basta indicar o formato %.2f, que diz para formatar o número com duas casas decimais.

O interessante deste módulo é que permite um controle maior sobre a formatação, que eu acho mais adequado do que ficar fazendo replace. Por exemplo, você também pode indicar se vai ter ou não o separador de milhares, caso o valor seja maior que 1000:
import locale

locale.setlocale(locale.LC_ALL, 'pt_BR.utf8')

# sem separador de milhares
print(locale.format_string('%.2f', 12345.00)) # 12345,00

# com separador de milhares
print(locale.format_string('%.2f', 12345.00, True)) # 12.345,00

Além de poder formatar como um valor monetário (não sei se era essa a intenção):
import locale

locale.setlocale(locale.LC_ALL, 'pt_BR.utf8')

# sem separador de milhares
print(locale.currency(12345.00)) # R$ 12345,00

# com separador de milhares
print(locale.currency(12345.00, grouping=True)) # R$ 12.345,00

O detalhe é que este módulo usa bibliotecas em C para obter o formato referente ao locale, segundo a documentação:

The locale module is implemented on top of the _locale module, which in turn uses an ANSI C locale implementation if available.

Então o locale pt_BR deve estar instalado/configurado no sistema operacional para que funcione. Caso contrário, a alternativa é usar replace mesmo, conforme sugerido na outra resposta.


Find the range of the following function

Question: Find the range of the following function:
$$f(x)=\frac{x-1}{x^2-5x-6}$$
I know how to find the domain only
Please provide an explanation.
EDIT: Another question: find the range of
$$f(x)=\frac{1}{(1-x)(5-x)}$$
How would we do that?
Comment: Range should be $(-\infty,\infty)$. Apply what you have been taught in the class.
Comment: Don't add new questions to old ones. Instead, upvote/choose answers that helped you here and ask a new question **if** you get stuck after checking carefully the answers to this question, which undoubtedly can help you with then new question.
Answer: Suppose $\;r\in\Bbb R\;$ , so we want to check when
$$\frac{x-1}{x^2-5x-6}=r\iff rx^2-(5r+1)x+1-6r=0$$
The above quadratic's discriminant is :
$$\Delta=25r^2+10r+1+24r^2-4r=49r^2+6r+1$$
and certainly $\;49r^2+6r+1>0\;,\;\;\forall\;r\in\Bbb R\;$ (why? Look again at this new quadratic's discriminant)  and from here that the quadratic's a solution for any $\;r\in\Bbb R\;$ , and thus the function is onto (or what's the same: the range is $\;\Bbb R\;$ )
Answer: the range of $f(x) = \dfrac{x-1}{(x+1)(x-6)}$ is $(-\infty, \infty).$ here is the reason. show that $\lim_{x \to -1+}f(x) = \infty$ and $\lim_{x \to 6-} f(x)= -\infty$ and $f$ is continuous in $(-1, 6).$  these three conditions imply the conclusion that the range of $f$ is $(-\infty, \infty).$
Answer: From partial fractions decomposition,
$$\frac{x-1}{x^2-5x-6}=\frac{x-1}{(x+1)(x-6)} =\frac{2}{7(x+1)}+\frac{5}{7(x-6)}.$$
Both fractions are decreasing continuous functions on the domain: $(-\infty,-1)\cup (-1,6)\cup (6,+\infty)$.
In particular, it is continuous decreasing on $(-1,6)$. On another hand, $$\lim_{x\to -1_+}f(x)=+\infty, \quad\lim_{x\to 6_-}f(x)=-\infty, $$
Hence, by the intermediate value theorem, the range of $f$ is $(-\infty,+\infty)$
Answer: If we factor, we have $\dfrac{x-1}{(x+1)(x-6)}$, and since there are no holes in the graph of the function. There is a horizontal asymptote at $y=0$, but this function has a zero at $x=1$, and thus the value $y=0$ is reached. Therefore the function has range $(-\infty,\infty)$.
Comment: @RainiervanEs Right, local behavior versus global.
Comment: but when x = 6, then there's a hole
Answer:
Pure Algebraic Way of Doing This Without any Graphic Calculator

Let y = $\frac{x-1}{x^2-5x-6}$
Using Cross Multiplication
x$^{2}$y -x$\left(5y+1\right)$-6y+1=0$\Longrightarrow$x=$\frac{\left(5y+1\right)\pm\sqrt{\left\{ 5y+1\right\} ^{2}-4y\left(1-6y\right)}}{2y}$
$\Longrightarrow$$\left\{ 5y+1\right\} ^{2}-4y\left(1-6y\right)$>
0
=$\left\{ 5y+1\right\} ^{2}-4y\left(1-6y\right)$= $\left(7y+\frac{3}{7}\right)^{2}+\frac{40}{49}$>0
which is always true $\forall$ y $\in.$$\mathbb{R}$

Hence the Range is= $\mathbb{R}$


Choosing right Model exchange rate

Question: I have obtained these two plots using R, I have to fit a model and the trouble is choosing between an ARMA(0,0), and an AR3. The main issue is the autocorrelation at lag 3, is it enough significant to be considered in the analysis? The BIC of the two models is very similar. Moreover Residuals are good for both models, altough AR3 removes the little correlation at lag 3 in the residuals ACF.
Thanks.
Answer: Updated answer.
First of all, an ARMA(0,0) is a white noise process. I dont know the purpose of your work, but white noise is a model with no predictability.
On the other hand, you need to model the statistically significant lag 3 (i assume it is). Perhaps AR(3) or MA(3). Consider both models and then decide based on AIC or BIC.
Comment: Ok. I took the first difference to obtain stationarity. So, I can't make prediction if I suppose a white noise process? The aim is the prediction after a good fitting. If is not an AR3, what model do you suggest? Thanks!
Comment: The prediction that I obtain supposing a WN is quite similar to the MA(10). The order of 10 is not to high, according to parsimony criteria?
Comment: Here they are : https://ibb.co/eP5CLn (data comes from eur/usd closing exchange rates)
Comment: thanks for the useful article. Unfortunately I have not the strong correlation at lag 1, but only the third weak lag. If I suppose an ARMA(0,0), the starting series was a random walk. In the article they said that it can be suitable. Seasonality is not so strong, do you conferm?
Comment: looking at these graph of squared residuals, do you think a GARCH is necessary?  https://ibb.co/dOgdbS  Thanks
Comment: so according to you I need to add an arch. But why the all the p-values in Mcleod Li test are above the dashed line?

Choosing right Model exchange rate


What is the optimal distance function for individuals when attributes are nominal?

Question: I do not know which distance function between individuals to use in case of nominal (unordered categorical) attributes.
I was reading some textbook and they suggest Simple Matching function but some books suggest that I should change the nominal to binary attributes and use Jaccard Coefficient. However, what if the values of the nominal attribute is not 2? what if there are three or four values in that attribute?
Which distance function should I use for nominal attributes?
Comment: I found [this post](http://stats.stackexchange.com/questions/105795/understanding-chi2-and-cram%C3%A9rs-v-results) useful, on Cramer's V and Chi squared statistic.
Answer: Technically to compute a dis(similarity) measure between individuals on nominal attributes most programs first recode each nominal variable into a set of dummy binary variables and then compute some measure for binary variables. Here is formulas of some frequently used binary similarity and dissimilarity measures.
What is dummy variables (also called one-hot)? Below is 5 individuals, two nominal variables (A with 3 categories, B with 2 categories). 3 dummies created in place of A, 2 dummies created in place of B.
ID   A    B      A1 A2 A3      B1 B2
1    2    1       0  1  0       1  0
2    1    2       1  0  0       0  1
3    3    2       0  0  1       0  1
4    1    1       1  0  0       1  0
5    2    1       0  1  0       1  0

(There is no need to eliminate one dummy variable as "redundant" as we typically would do it in regression with dummies. It is not practised in clustering, albeit in special situations you might consider that option.)
There are many measures for binary variables, however, not all of them logically suit dummy binary variables, i.e. former nominal ones. You see, for a nominal variable, the fact "the 2 individuals match" and the fact "the 2 individuals don't match" are of equal importance. But consider popular Jaccard measure $\frac{a}{a+b+c}$, where

a - number of dummies 1 for both individuals
b - number of dummies 1 for this and 0 for that
c - number of dummies 0 for this and 1 for that
d - number of dummies 0 for both

Here mismatch consists of two variants, $b$ and $c$; but for us, as already said, each of them is of the same importance as match $a$. Hence we should double-weight $a$, and get formula $\frac{2a}{2a+b+c}$, known as Dice (after Lee Dice) or Czekanovsky-Sorensen measure. It is more appropriate for dummy variables. Indeed, famous composite Gower coefficient (which is recommeded for you with your nominal attributes) is exactly equal to Dice when all the attributes are nominal. Note also that for dummy variables Dice measure (between individuals) = Ochiai measure (which is simply a cosine) = Kulczynsky 2 measure. And more for your information, 1-Dice = binary Lance-Williams distance known also as Bray-Curtis distance. Look how many synonyms - you are sure to find something of that in your software!
The intuitive validity of Dice similarity coefficient comes from the fact that it is simply the co-occurrence proportion (or relative agreement). For the data snippet above, take nominal column A and compute 5x5 square symmetric matrix with either 1 (both individuals fell in the same category) or 0 (not in the same category). Compute likewise the matrix for B.
A    1  2  3  4  5        B    1  2  3  4  5
     _____________             _____________
  1| 1                      1| 1
  2| 0  1                   2| 0  1
  3| 0  0  1                3| 0  1  1
  4| 0  1  0  1             4| 1  0  0  1
  5| 1  0  0  0  1          5| 1  0  0  0  1

Sum the corresponding entries of the two matrices and divide by 2 (number of nominal variables) - here you are with the matrix of Dice coefficients. (So, actually you don't have to create dummies to compute Dice, with matrix operations you may probably do it faster the way just described.) See a related topic on Dice for the association of nominal attribures.
Albeit Dice is the most apparent measure to use when you want a (dis)similarity function between cases when attributes are categorical, other binary measures could be used - if find their formula satisfy considerations about your nominal data.
Measures like Simple Matching (SM, or Rand) $\frac{a+d}{a+b+c+d}$ which contain $d$ in the numerator won't suit you on the grounds that they treat 0-0 (both individuals do not have a  specific common attribute/category) as a match, which is obviuosly nonsense with originally nominal, qualitative features. So check the formula of the similarity or dissimilarity you plan to use with the sets of dummy variables: if it has or implies $d$ as the grounds for sameness, don't use that measure for nominal data. For example, squared Euclidean distance, which formula becomes with binary data just $b+c$ (and is synonymic in this case to Manhattan distance or Hamming distance) does treat $d$ as the basis of sameness. Actually, $d^2 = p(1-SM)$, where $p$ is the number of binary attributes; thus Euclidean distance is informationally equal worth with SM and shouldn't be applied to originally nominal data.
But...
Having read the previous "theoretical" paragraph I realized that - in spite what I wrote - the majority of binary coefficients (also those using $d$) practically will do most of the time. I established by check that with dummy variables obtained from a number of nominal ones Dice coefficient is related strictly functionally with a number of other binary measures (acronym is the measure's keyword in SPSS):
                                                       relation with Dice
    Similarities
       Russell and Rao (simple joint prob)    RR          proportional
       Simple matching (or Rand)              SM          linear
       Jaccard                                JACCARD     monotonic
       Sokal and Sneath 1                     SS1         monotonic
       Rogers and Tanimoto                    RT          monotonic
       Sokal and Sneath 2                     SS2         monotonic
       Sokal and Sneath 4                     SS4         linear
       Hamann                                 HAMANN      linear
       Phi (or Pearson) correlation           PHI         linear
       Dispersion similarity                  DISPER      linear
    Dissimilarities
       Euclidean distance                     BEUCLID     monotonic
       Squared Euclidean distance             BSEUCLID    linear
       Pattern difference                     PATTERN     monotonic (linear w/o d term omitted from formula)
       Variance dissimilarity                 VARIANCE    linear

Since in many applications of a proximity matrix, such as in many methods of cluster analysis, results will not change or will change smoothly under linear (and sometimes even under monotonic) transform of proximities, it appears one may be justified to a vast number of binary measures besides Dice to get same or similar results. But you should first consider/explore how the specific method (for example a linkage in hierarchical clustering) reacts to a given transformation of proximities.
If your planned clustering or MDS analysis is sensitive to monotonic transforms of distances you better refrain from using measures noted as "monotonic" in the table above (and thus yes, it isn't good idea to use Jaccard similarity or nonsquared euclidean distance with dummy, i.e. former nominal, attributes).
Comment: suppose I have two values of the same attribute, "ball", "nall", "pall" and I converted this to 11 01 and 00. I want to measure the Jaccard distance between 11 and 00. In this case, then is the distance 1? since a = 0 b = 2 c = 0 and d = 0? please let me know!
Comment: I miss the point of your last comment. Please ask clearly. Or use my above example data with 5 people and 2 nominal attributes and tell which individual with which you'd want me to compare and by what dis(similarity) measure.
Comment: yes you are right the values.. so one attribute has three possible values
Comment: Sorry, but I joined the community just to register that your answer is very badly structured to me. You should've elaborated the examples and concepts you approach way batter.


Integral bounds when finding surface are of hyperbolic paraboloid $z=y^2-x^2$ between cylinders by switching to cylindrical coords

Question:
I came to this problem, and had to look up cylindrical coords since we didn't cover them in any of my classes. But from everything I've read so far I'm still unsure about how they got the 4 and 2 fro the upper and lower bounds of the inner integral. Can someone please explain this?
Answer: The reason to get the 2 and the 4 in the limits of the new integral is the fact that when changing coordinates, the limits must change in the same way as they do when a simple variable change is done when solving a simple integral. However, this limits are wrong in this problem, they are 1 and 2. If you substitute these values, you will get the final answer, thing that you do not get with the limits established in your picture.
For this specific case, you are asked to do the integral of the function between the cylinders $x^2 + y^2=1$ and the cylinder $x^2 + y^2=4$. The good thing of using cylindric coordinates in problems regarding surfaces inside cyllinders is that the limits are easily got, being the radius limits the radius of the small cyllinder to the one of the big one, and then the $\theta$ angle is from zero to $2\pi$ so that you cover the full cillinder. Intuitively what happens is that the radius limits rotate a phase defined by the angle, an so you get the area between those cyllinders. As the general equation for a circle is given by $x^2+y^2=r^2$, you can get the radiuses easily, and so for your case you'll get 1 and 2.
Comment: Note also the extra r factor that is added in when the change is done in the function. This is the so-called Jacobian determinant for the cyllindrical coordinates and is needed to change the variables in multiple integrals. For more info see: https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant
Comment: Thank you for mentioning that as well.


document.createElement('div') with a class

Question: I can use createElement() to create an HTML element via JavaScript like this:
let div = document.createElement('div');

But how can I add a CSS class to my newly created div?
I tried something like this, but didn't work:
let div = document.createElement('div class=myDiv');

Comment: If your new `div` will be added to the DOM, you can also use HTML markup to describe it, and then `.insertAdjacentHTML` to create and add it. `var html = ""; targetElement.insertAdjacentHTML("beforeend", html);` That method gives you 4 positions relative to the target to which you can added to the DOM. See the docs for more info.
Comment: This question still needs to be answered. It is not a duplicate of the proposed. This question is looking to add the classname in the same line. The duplicate is just looking to add a classname in general.
Answer: Do div.classList.add

let div = document.createElement('div');
div.classList.add('test');
let text = document.createTextNode('Test');
div.appendChild(text);
document.body.appendChild(div)
.test {
  color: green;
}

You can also do by className

let div = document.createElement('div');
div.className = 'test';
let text = document.createTextNode('Test');
div.appendChild(text);
document.body.appendChild(div)
.test {
  color: red;
}
Comment: It is also possible to set the attribut "className", usefull to add many classes:

`div.className = "class1 class2"`;
Answer: You can use Element.classList.add
let div = document.createElement('div');
div.classList.add("myDiv")


Unknown profiler issue when using Typemock and CodeRush

Question: I'm using VS 2017 and Typemock version 8.6.9. I've been working with CodeRush as a test runner for a while and it worked perfectly. Now I started using their coverage tool and got the following error:
<code>*** Unknown profiler is enabled please contanct firstname.lastname@example.com with the flowing data: unknown profiler clsid = {B146457E-9AED-4624-B1E5-968D274416EC}
</code>
How can I fix it?
Answer: Disclaimer: I work at Typemock - the unit testing company
It is a well-known issue, there was a problem in the integration of coverage profilers between latest Isolator and CodeRush Code Coverage.
You are welcome to update to the latest version which includes all fixes.


Playwright python test for value in outbound request URL

Question: I'm using Playwright Python (and pytest-playwright) for some testing of my site. The page I'm testing makes calls to an analytics partner (like Google Analytics) but with just a GET request and a long query string which has the analytics data.
I'd like to verify that a certain value, e.g. foo=bar, is in the call to the analytics partner. For this example, I'll use analytics.example.com.
I have this code in my test:
import re
r = re.compile('https://analytics.example.com/.*foo=bar.*')
with page.expect_request(r, timeout=15000) as analytics_call:
    print('got expected analytics call')

When I run the test, I see the "got expected analytics call" but the test fails with a timeout message:
playwright._impl._api_types.TimeoutError: Timeout 15000ms exceeded while waiting for event "request"
I also considered using page.on("request", my_event_handler) and the event handler function is called... but then I'm not sure how to pass or fail the test based on what the event handler does.
How would one write a test that tests for a value in an outbound request?
Answer: page.expect_* return context managers that intend for you to trigger the events you're looking for within the with statement. For example:
    r = re.compile('http://example.com/.*foo=bar.*')
    with page.expect_request(r, timeout=15000) as analytics_call:
        page.goto('http://example.com/?foo=bar') # this will trigger the request we're expecting

Everything in the with block is run immediately, it's only upon trying to exit the scope of that block that the condition is waited for (if it's not already fulfilled).
Comment: Thanks for the explanation of how the `expect_*` context managers work. They aren't what I need.

Any ideas of how I can _test_ the value of the query parameter of the outbound request.
Comment: I'm not sure what you mean. If you want to verify that a certain query string parameter was set, this approach would work fine.
Comment: I'm not following – where's the test here? How would I assert something that would pass or fail? I'm not trying to execute a new action/path when this page is requested, just verifying that the expected query parameter(s) exist
Comment: You need to "record" any requests made before you want to see if they occured. In this example, we use expect_...(and therefore record requests) before then going to a URL that triggers this request.

If the request isn't seen within the timeout, this will raise a TimeoutError and the tests will fail.