Justifying $\lim \limits_{x \to 0} f(x) = \lim \limits_{bx \to 0} f(bx)= \lim \limits_{(x - 7) \to 0} f(x-7)$

Question: How do you justify such limit equalities as these?
$\lim \limits_{x \to 0} f(x) = \lim \limits_{bx \to 0} f(bx)= \lim \limits_{(x - 7) \to 0} f(x-7)$
I am familiar with the $\epsilon-\delta$ definition of the limit, I just don't know what it is that makes these statements equivalent:
$$ \forall \epsilon \ \exists \delta> 0 \ \forall x: |x| < \delta \implies |f(x) - l| < \epsilon$$
$$ \forall \epsilon \ \exists \delta> 0 \ \forall x: |bx| < \delta \implies |f(bx) - l| < \epsilon$$
$$ \forall \epsilon \ \exists \delta> 0 \ \forall x: |x - 7| < \delta \implies |f(x - 7) - l| < \epsilon$$
Comment: I'm not an expert, but I have a guess. It seems to me, the thing is that $bx$ and $x-7$ are surjections. Consider some statement (or rather predicate) $P$, let's say $\forall x: P(bx)$. Since $bx$ is a surjection, I may conclude, that if the statement was true for all $x$, it should be true for all $bx$, e.g $\forall bx: P(bx)$. Renaming $bx \rightarrow x$ we get again $\forall x: P(x)$.
Comment: Your notation is non-standard. You should rather write $\lim_{x\to 0}f(bx)$ and $\lim_{x\to 7}f(x-7)$. The expression under limit notation is always of the form $\text{variable} \, \to\, \text{value}$ and not $\text{expression} \, \to\, \text{value} $.
Comment: @ParamanandSingh I infer this poster is being introduced to limits, and part of the point of this problem is to learn to manipulate the variables in a basic $\varepsilon-\delta$ proof.  To justify what you've written, you also need to know that $\lim_{x \to c} f(g(x)) = f(g(c))$ when $f$ and $g$ are continuous.  That's true, of course, but I'm guessing the poster hasn't gotten there yet.
Comment: @RobertShore: yeah I also think so. That's why there is so much hue and cry over putting context into questions. But still few askers pay heed to it.
Comment: This one certainly made a good faith effort to do so.
Comment: @RobertShore: yeah there is a clear indication of familiarity with $\epsilon, \delta$. I gave my +1 based on this context.
Answer: For the first equivalence, substitute $u_1=bx$.  For the second equivalence, substitute $u_2=x-7$.  Then you're just saying:
$$\lim_{x \to 0} f(x) = \lim_{u_1 \to 0} f(u_1) = \lim_{u_2 \to 0} f(u_2).$$
Make these substitutions in an $\varepsilon-\delta$ proof and you'll see they flow right through.
Comment: Your statement mentioning the equality of limits is vacuosly true as the variable symbol is dummy. The limit is for a function $f$ at a point $c$
Comment: @ParamanandSingh That's precisely the point.
Comment: OK got it. +1 there.


Deletando dados automaticamente depois de determinado tempo

Question: Exemplo:
Tenho uma tabela com três campos: id int pk, nome varchar, categoria int.
O campo categoria poderá receber 2 valores: 1 e 2;
Por default sempre quando um dado for inserido ele terá uma categoria 1.
O que eu quero é o seguinte.
Quando um dado for inserido, ele tem até 10 dias para ser alterado para 2. Caso contrário, o mesmo será excluído.
Tem alguma maneira de eu fazer isto?
Grato!
Comment: Você é administrador do banco?
Comment: @Ricardo Sim, eu sou.
Answer: Usa create-event.
Ficaria mais ou menos assim:
Criar a procedure:

CREATE PROCEDURE delete_rows_links()
    BEGIN
       DELETE FROM minhatabela WHERE categoria = 1 AND data < CURRENT_DATE()-10;
     END

CREATE EVENT myevent
    ON SCHEDULE EVERY 5 SECOND (vc escolhe)
    DO
      CALL delete_rows_links();

No link tem mais definições onde vc pode aprender mais.
Comment: Ricardo essa `delete_rows_links` é uma _procedure_? Sei que não é o ponto principal da resposta, mas se tu colocar o código de exemplo dela agregaria muito valor a sua resposta.
Comment: Coloquei um modelo lá, mas ele teria que ajudar em relação ao melhor nome para ele, colocar uma coluna data na tabela para controlar a data de inclusão, fazer seus próprios ajustes, mas já deu uma melhorada sim.
Answer: Grave a data inicial e final que ele inseriu a categoria e deixe o servidor programado para verificar se está entre o período de 10 dias, se não passou ele remove o dado.
Você pode programar no servidor um script com crontab da seguinte maneira,  ele irá pingar seu script de acordo com o período que você programar, e neste script, você faz a verificação da data:
Será executado:

Uma vez ao ano: 0 0 1 1 *.
A cada mês: 0 0 1 * *.
Uma vez por semana: 0 0 * * 0.
Uma vez por dia:  0 0 * * *.
A cada hora: 0 * * * *.

0 0 * * 0 php /caminho/completo/do/seuscript.php
o seuscript:
<?php

$mysqli = new mysqli("localhost", "root", "senha", "banco");

/* verifica se está conectado */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "DELETE FROM evento
          WHERE status =1
          AND now() NOT BETWEEN data_inicial AND data_final";
$stmt = $mysqli->prepare($query);

E para gravar o período de 10 dias:

$mysqli = new mysqli("localhost", "root", "senha", "banco");

/* verifica se está conectado */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$nome = $_POST['nome'];
$dataInicial = new DateTime();
$dataFinal   = new DateTime('+10 days');

$query = "INSERT INTO evento (nome, categoria, status, data_inicial, data_final) VALUES(?,null, 1, ?, ?) ";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $nome, $dataInicial, $dataFinal);


About the proof that lebesgue measure is a premeasure.

Question: let $\lambda^n$ be $n$-dimensional Lebesgue measure. I am having trouble understanding the proof that this "mapping" is a premeasure on the set of half open rectangles $\lambda^n ([a,b))= \prod_{i=1}^n(b_i-a_i)$. The proof uses induction over the dimension $n$. I understood how it was shown that $\lambda$ is a premeasure. So now assume $\lambda^n$ is a premeasure the goal is to show $\lambda^{n+1}$ is too, which can be simply reduced to showing that $\lambda^{n+1}$ is $\sigma$-additive.
Let $I_j=I_1^j \times I_j^n \in \mathcal J^1 \times \mathcal J^n=\mathcal J^{n+1}$ be mutually disjoint and $\bigcup_{j \in \Bbb N}I_j=I\in \mathcal J^{n+1}$(disjoint union). Ok so now to the first thing I can't understand : Since $I \in \mathcal J^{n+1}$ we know that $$\bigcup_{j\in\Bbb{N}}I_j^d \in \mathcal J^d, \ d=1,n$$
What does he mean by this, and what does $d=1,n$ mean?
Define $\hat{I}_1^d=I_1^d$ and $\hat{I}_{j+1}^d=I_{j+1}^d \setminus (I_1\cup \ldots\cup I_j^d)$. The $\hat{I}_j^d$ are disjoint and
$$\bigcup_{j=1}^NI_j^d=\bigcup_{j=1}^N\hat{I}_j^d$$
for all $N \in \Bbb{N}$ and $d=1,n$ (I still don't get what this notation is, the second union is disjoint).
Now since $\mathcal J^d$ is a semi-ring each $\hat{I}_j^d$ is a finite union of disjoint union of disjoint rectangles. Hence there are disjoint sets $\widetilde{I}_k^1\in \mathcal J^1$ and $\widetilde{I}_l^n\in \mathcal J^n$ such that(all union below are disjoint)
$$I=\bigcup_{j \in \Bbb{N}}(I_j^1 \times I_j^n)=\text{why?}\bigcup_{k \in \Bbb{N}}\bigcup_{l \in \Bbb{N}}(\widetilde{I}_k^1 \times \widetilde{I}_l^1)=\bigcup_{k \in \Bbb{N}}\widetilde{I}_k^1 \times \bigcup_{l \in \Bbb{N}}\widetilde {I}_l^n \in \mathcal J^1 \times \mathcal J^d $$
Is $ \mathcal J^d$ a typo?
Also why is $\lambda^{n+1}(\bigcup_{k \in \Bbb{N}}\widetilde{I}_k^1 \times \bigcup_{l \in \Bbb{N}}\widetilde {I}_l^n )=\lambda^1(\bigcup_{k \in \Bbb{N}}\widetilde{I}_k^1) \cdot \lambda^n (\bigcup_{l \in \Bbb{N}}\widetilde {I}_l^n) $? (this is just stated without any proof and doesn't really seem direct)
And finally why is $$\sum_{j\in \Bbb{N}}\mathop{\sum\sum}_{(k,l):(\widetilde{I}_k^1 \times \widetilde{I}_l^n)\subset (I_j^1 \times I_j^n)}\lambda^{n+1}(\widetilde{I}_k^1 \times \widetilde{I}_l^n)=\sum_{k \in \Bbb{N}}\sum_{l \in \Bbb{N}} \lambda^{n+1}(\widetilde{I}_k^1 \times \widetilde{I}_l^n)$$
Such hardness much handwavery.
Comment: What book are you working from?
Comment: @Potato This is from measures integrals and martingales by Schilling however the proof changed from the second to third editions so the one on Google books is different that's why I didn't mention it.
Answer: In the following we use
$\bigsqcup_{j \in \mathbb{N}}I_j$
to denote the disjoint union of $I_j,j\in\mathbb{N}$. We go through the stated parts of the proof and consider OPs questions.

Let
  $I_j=\color{blue}{I_j^1} \times I_j^n \in \mathcal J^1 \times \mathcal J^n=\mathcal J^{n+1}$
  be mutually disjoint and $\bigsqcup_{j \in \mathbb N}I_j=I\in \mathcal J^{n+1}$.

We split the $(n+1)$-dimensional interval $I_j$ into a one-dimensional and an $n$-dimensional part in order to prepare for the inductive step. Note that we have $I_j=\color{blue}{I_j^1} \times I_j^n$ and not $I_1^j$.

Since $I \in \mathcal J^{n+1}$ we know that $$\bigcup_{j\in\mathbb{N}}I_j^d \in \mathcal J^d, \ d=1,n$$

The usage of $d=1,n$ is just a shorthand for
\begin{align*}
\bigcup_{j\in\mathbb{N}}I_j^1 \in \mathcal J^1\qquad\text{and}\qquad\bigcup_{j\in\mathbb{N}}I_j^n \in \mathcal J^n\tag{1}
\end{align*}
which follows from the representation $I_j=I_j^1 \times I_j^n \in \mathcal J^1 \times \mathcal J^n=\mathcal J^{n+1},j\in \mathbb{N}$.
The representation in (1) is not a disjoint union, but we need mutually disjoint intervals to ease further calculations. So, we introduce:

Define $\hat{I}_1^d=I_1^d$ and $\hat{I}_{j+1}^d=I_{j+1}^d \setminus (I_1\cup \ldots\cup I_j^d)$. The $\hat{I}_j^d$ are disjoint and
  \begin{align*}
\bigcup_{j=1}^NI_j^d=\bigsqcup_{j=1}^N\hat{I}_j^d\tag{2}
\end{align*}
  for all $N \in \mathbb{N}$ and $d=1,n$.

... which again is a short-hand for
\begin{align*}
\bigcup_{j=1}^NI_j^1=\bigsqcup_{j=1}^N\hat{I}_j^1\qquad\text{and}\qquad \bigcup_{j=1}^NI_j^n=\bigsqcup_{j=1}^N\hat{I}_j^n
\end{align*}
From now on we recall that $d=1,n$ is a short-hand notation. This way the author can write a single statement regarding $d$ and we consider them to be two statements, one with $d=1$ and one with $d=n$. For instance the statement $\mathcal J^d$ is a semi-ring is to read as $\mathcal{J}^1$ and $\mathcal{J}^n$ are semi-rings.

Now since $\mathcal J^d$ is a semi-ring each $\hat{I}_j^d$ is a finite union of disjoint union of disjoint rectangles. Hence there are disjoint sets $\widetilde{I}_k^1\in \mathcal J^1$ and $\widetilde{I}_l^n\in \mathcal J^n$ such that
$$I=\bigsqcup_{j \in \mathbb{N}}(I_j^1 \times I_j^n)=\text{why?}\bigsqcup_{k \in \mathbb{N}}\bigsqcup_{l \in \mathbb{N}}(\widetilde{I}_k^1 \times \color{blue}{\widetilde{I}_l^n})=\bigsqcup_{k \in \mathbb{N}}\widetilde{I}_k^1 \times \bigsqcup_{l \in \mathbb{N}}\widetilde {I}_l^n \in \mathcal J^1 \times \color{blue}{\mathcal J^d} $$

Note that we have $\bigsqcup_{k \in \mathbb{N}}\bigsqcup_{l \in \mathbb{N}}(\widetilde{I}_k^1 \times \color{blue}{\widetilde{I}_l^n})$ and not $\bigsqcup_{k \in \mathbb{N}}\bigsqcup_{l \in \mathbb{N}}(\widetilde{I}_k^1 \times \color{blue}{\widetilde{I}_l^d})$.
Is $\color{blue}{\mathcal J^d}$ a typo? Yes, it is a typo in the book and should be read as $\color{blue}{\mathcal J^n}$.
Ad why?: See the start of chapter 6 and recall that property (S3) of the definition of a semi-ring $\mathcal{S}$ tells us that the difference $S\setminus T$ of each two elements $S,T\in\mathcal{S}$ can be represented as finite disjoint union of elements of $\mathcal{S}$.

The complete statement of the last paragraph reads as:
Since $\mathcal J^d$ is a semi-ring, the property (S3) shows that each $\hat{I}_j^d$ is a finite union of disjoint union of disjoint rectangles. Hence there exist disjoint sets $\widetilde{I}_k^1\in \mathcal J^1$ and $\widetilde{I}_l^n\in \mathcal J^n$ such that
$$I=\bigsqcup_{j \in \mathbb{N}}(I_j^1 \times I_j^n)=\bigsqcup_{k \in \mathbb{N}}\bigsqcup_{l \in \mathbb{N}}(\widetilde{I}_k^1 \times \widetilde{I}_l^n)=\bigsqcup_{k \in \mathbb{N}}\widetilde{I}_k^1 \times \bigsqcup_{l \in \mathbb{N}}\widetilde {I}_l^n \in \mathcal J^1 \times \mathcal J^n $$

The equality chain holds due to the paragraph above addressing the property (S3) and the relationship (2).

Sigma-additivity of $\lambda^{n+1}$:
The following equality chain is valid essentially due to the sigma-additivity of $\lambda^{n+1}$:
  \begin{align*}
\lambda^{n+1}\left(\bigsqcup_{j \in \mathbb{N}}I_j\right)
&=\lambda^{n+1}\left(\bigsqcup_{k \in \mathbb{N}}I_j^1\times\bigsqcup_{k \in \mathbb{N}}I_l^n\right)\\
&=\lambda^{1}\left(\bigsqcup_{k \in \mathbb{N}}I_j^1\right)
\cdot\lambda^{n}\left(\bigsqcup_{k \in \mathbb{N}}I_j^n\right)\tag{3}\\
&=\sum_{k\in\mathbb{N}}\sum_{l\in\mathbb{N}}\lambda^1(\widetilde{I}_k^1)\cdot\lambda^n(\widetilde{I}_l^n)\\
&=\sum_{k\in\mathbb{N}}\sum_{l\in\mathbb{N}}\lambda^{n+1}(\widetilde{I}_k^1\times\widetilde{I}_l^n)
\end{align*}

Note that as stated in the book (3) is valid due to the very definition of $\lambda^{n+1}$ as a product on $\mathcal J^{n+1}$: If $I=I^1\times I^{n+1}\in(\mathcal J^{1}\times\mathcal J^{n})=\mathcal J^{n+1}$ then
\begin{align*}
\lambda^{n+1}(I)=\lambda^{n+1}(I^1\times I^n)=\lambda^{1}(I^1)\cdot\lambda^{n}(I^n)
\end{align*}
The last equality should now be in reach.


How to take total derivative of $F^2 (x, \lambda \dot x)$ with respect to a scalar?

Question: I have a function  $F^2 (x, \lambda \dot x)$, which is a scalar function:

$F^2 (x, \lambda \dot x): \mathbb{R}^n \rightarrow \mathbb{R}$
$\lambda$  is a scalar.  $\lambda \in \mathbb{R}$
$x \in \mathbb{R}^n$

From what my colleague writes on the board,
$\frac{d }{d \lambda} F^2 (x, \lambda \dot x)= \frac{\partial F^2 (x, \lambda \dot x)}{\partial \dot x} * \dot x$
and
$\frac{d^2 }{d \lambda ^2}F^2 (x, \lambda \dot x) = \dot x^T \frac{\partial^2 }{\partial  \dot x^2} F^2 (x, \lambda \dot x) * \dot x$.
I am trying to justify his math by using this definition of the total derivative:
$\frac{d }{d \lambda} F^2 (x, \lambda \dot x)=\frac{\partial }{\partial \lambda} F^2 (x, \lambda \dot x)+\frac{\partial }{\partial \lambda \dot x} F^2 (x, \lambda \dot x)\frac{\partial }{\partial \lambda} \lambda \dot x$
By using that definition of the total derivative, then we seem to be saying the following:
1) $\frac{\partial }{\partial \lambda} F^2 (x, \lambda \dot x)=0$  (and this is because $\lambda$ is a scalar)
2) $\frac{\partial }{\partial \lambda \dot x} F^2 (x, \lambda \dot x) = \frac{\partial }{ \lambda  \partial \dot x} F^2 (x, \lambda \dot x)= \frac{\partial }{\partial  \dot x} F^2 (x, \lambda \dot x) $
Now, I am just looking for a little help with the math here.  Are the justifications 1) and 2) correct?  If not, then how does my colleague justify this?
As a final question, why is it not true that $\frac{\partial }{\partial  \dot x} F^2 (x, \lambda \dot x)= 2 F (x, \lambda \dot x) * \lambda$?  When I apply the chain rule, as I am accustomed to doing, I am getting $\frac{\partial }{\partial  \dot x} F^2 (x, \lambda \dot x)= 2 F (x, \lambda \dot x) * \lambda$.  I am assuming the reason we do not apply the chain rule here is because we are taking the total derivative and not the partial derivative.  Is that true?
Thank you very much for helping me, I know this is basic stuff!
Comment: First, you should write the function as $F(x,y)$, and then consider $G(x,\dot x,\lambda) = F^2(x,\lambda\dot x)$. Now think chain rule. In response to your second main question, let's review. If I have a function $f(x)$ and I set $h(x) = f^2(x)$, then the chain rule tells you that $h'(x) = 2f(x)f'(x)$. You forgot the main part of the chain rule.
Comment: You're still forgetting the "primary" application of the chain rule. If you take $\frac{\partial}{\partial y} F^2(x,y)$, you get $2F(x,y)\frac{\partial F}{\partial y}$.
Comment: OKay, that is a good suggestion @TedShifrin!
Comment: For the second main question (why the total derivative is not $2F(x,\lambda \dot x ) * \lambda$): In your comment above, does $f'(x)$ denote the partial or total derivative in this case?
Comment: In that case, it should be $\frac{\partial}{\partial \dot x} F^2 (x, \dot x) = 2F(x,\dot x) \frac{ F_{\dot x} (x, \dot x)}{\lambda}$, since $\frac{\partial}{\partial \dot x} F(x, \lambda \dot x) =\frac{ F_{\dot x} (x, \dot x)} {\lambda}$, right?
Comment: Where did the $\lambda$ come from in the first equation? There are no $\lambda$s on the left-hand side. No, $\frac{\partial}{\partial\dot x} F(x,\lambda\dot x) = F_2(x,\lambda\dot x)\cdot\lambda$. I prefer to use $2$ to denote partial differentiation with respect to the second variable, because it's too confusing to write $\dot x$ there.
Comment: If you want the $\lambda$ derivative, you get $2F(x,\lambda\dot x)F_2(x,\lambda\dot x)\dot x$.
Answer: $$\frac{d}{d\lambda}F^2(x,\lambda\dot x)=\frac{\partial}{\partial x}F^2(x,\lambda\dot x)\cdot\frac{\partial}{\partial\lambda} x + \frac{\partial}{\partial\lambda\dot x}F^2(x,\lambda\dot x)\cdot \frac{\partial}{\partial\lambda}\lambda\dot x =\frac{\partial}{\partial\lambda\dot x}F^2(x,\lambda\dot x) \cdot \dot x$$ since $x$ is independent of $\lambda$. Note that we derivate $F^2$ along the coordinates and multiply this with the according inner derivative.
Edit:
As MasterYoda correctly derived in his answer
$$\frac{\partial}{\partial\lambda\dot x}F^2(x,\lambda\dot x) = \frac{1}{\lambda}\frac{\partial}{\partial\dot x}F^2(x,\lambda\dot x)\,.$$
A slightly different way to see this, is by considering the function $f(\cdot):=F^2(x,\cdot)$. Note, the partial derivative of $F^2$ with respect to the second component equals the (total) derivative of $f$. Then, the chain rule gives
$$\frac{\partial}{\partial\dot x}F^2(x,\lambda\dot x)= \frac{\partial}{\partial\dot x}f(\lambda\dot x)=\lambda f'(\lambda\dot x)=\lambda \frac{\partial}{\partial\lambda\dot x}F^2(x,\lambda\dot x)\,.$$
Now, rearrange.
Comment: Yes but what happens to the $\lambda$ in the denominator of the last thing that you wrote?
Comment: @nundo I've edited the answer.
Answer: Interpreting what your colleague wrote, it appears $F^2$ is itself a function and not the square of $F$, correct? If not, simply replace $F^2$ with $G$. Otherwise, applying chain rule to $F^2$ would be
$$\begin{align}
\frac{d}{d\lambda}F^2(x,\lambda\dot x) &= \frac{\partial F^2(x,\lambda\dot x)}{\partial\lambda} + \frac{\partial F^2(x,\lambda\dot x)}{\partial x}\frac{\partial x}{\partial \lambda} + \frac{\partial F^2(x,\lambda\dot x)}{\partial\lambda\dot x}\frac{\partial \lambda\dot x}{\partial \lambda} \\&= \frac{1}{\lambda} \frac{\partial F^2(x,\lambda\dot x)}{\partial\dot x}\dot x
\end{align}$$
To answer 1), notice the first term is zero because $F^2$ is not a function of $\lambda$ alone. Instead $\lambda$ is tied to $\dot x$. Also second term is zero because $dx/d\lambda=0$ due to independence of $\lambda$. As for your colleague making the claim that 2) $\partial/\partial\lambda\dot x = \partial/\partial\dot x$ may be wrong. You can wave your hand and say that $\lambda\dot x$ is in the same direction as $\dot x$, which may be true, but I think doing that would make the result be off by a scaling factor $1/\lambda$. Here is my long but mathematically appropriate (I think) justification: Let $y = \lambda\dot x$
$$\frac{\partial}{\partial\lambda\dot x} = \frac{\partial}{\partial y} = \frac{d\dot x}{dy}\frac{\partial}{\partial\dot x} = \frac{d(y/\lambda)}{dy}\frac{\partial}{\partial\dot x} = \frac{1}{\lambda}\frac{\partial}{\partial\dot x}$$
Now for the second derivative. For derivatives of vectors it is simplest to do it element wise. So let $\dot x_i$ be the $i^{th}$ element of the vector $\dot x$.
$$\begin{align}
\frac{d^2}{d\lambda^2}F^2(x,\lambda\dot x) &= \frac{d}{d\lambda} \left[\frac{1}{\lambda} \frac{\partial F^2(x,\lambda\dot x)}{\partial\dot x}\dot x_i\right] \\ &= \frac{1}{\lambda} \frac{\partial F^2(x,\lambda\dot x)}{\partial\dot x}\frac{d\dot x_i}{d\lambda} + \frac{1}{\lambda}\frac{d}{d\lambda} \left[\frac{1}{\lambda} \frac{\partial F^2(x,\lambda\dot x)}{\partial\dot x}\right]\dot x_i \\ &= \frac{1}{\lambda^2}\frac{\partial^2 F^2(x,\lambda\dot x)}{\partial\dot x^2}\dot x_i^2 \\ &\implies \boxed{\frac{d^2}{d\lambda^2}F^2(x,\lambda\dot x)=\frac{1}{\lambda^2}\dot x^T\frac{\partial^2 F^2(x,\lambda\dot x)}{\partial\dot x^2}\dot x}
\end{align}$$
Comment: That's correct, $F^2$ itself is a function.  It is a square of the scalar output of $F$, since $F$ is a scalar function.
Comment: I am pretty sure that $\frac{1}{\lambda} \frac{\partial F^2(x,\lambda\dot x)}{\partial\dot x}\dot x$ is actually incorrect, because that $\lambda \dot x$ cannot be separated - it's like one variable.  I think it should technically be $\frac{\partial F^2(x,\lambda\dot x)}{\partial \lambda \dot x}\dot x$.


Beginner Bluetooth Stack Advice

Question: Hay peeps
I'm relatively new to Bluetooth and its inner workings and am trying to still understand some of the concepts and procedures. My question relates to the Bluetooth stack.
I understand there is a Bluetooth stack on the OS side such as Linux Bluez, Windows, Androids Bluedroid etc... but do peripheral devices implement a stack within themselves for example I connect a Bluetooth mouse to a Linux system, Linux of course implements the Bluez stack does the mouse them implement a Bluetooth stack?
I am trying to understand which device will implement security in this situation would it be the Linux with its Bluez or the mouse peripheral.
Thanks
Answer: Yes, But the difference is that peripheral devices wont support all the profiles and features compared to a Bluetooth stack in OS like Linux or android.
Bluetooth is one of the wireless protocols. Protocol is a procedure or system of rules to follow. So both devices should follow the same protocol for communication. If one of these devices is not following the required protocol, then the other device can't communicate with it. It is like a common language between two people. To follow these protocols all device should have stack. Bluetooth mouse and keyboard also will have Bluetooth stack.
Bluetooth is divided into core protocols and profiles. Core and some profiles are needed for all devices for scanning, pairing etc Example GAP, GATT. Some profile are for a particular use case. For Keyboard and Mouse is is HID profile. For steaming HiFi audio it is A2DP. For voice communication it is HFP. Each peripheral device will implement only the required profiles for their use case because of memory and cost constraints.
The OS will generally implement all the profiles because it needed to connect to most of the peripheral devices. For example A2DP to connect with Bluetooth headset, HID/HOGP to connect with mouse, SPP/OBEX for file transfer over Bluetooth.
Security is implemented in GAP in BREDR and SMP in BLE. These are implemented in all the devices.
Bluetooth stacks are implemented in different ways too. Some places it is entirely implemented in Bluetooth controller(Mostly along with application all in single chip), But in some place it is split between host CPU(In OS) and Bluetooth controller(In firmware). Bludroid and Bluez are the upper part running in the Host CPU(Above HCI). There will be a lower part of the stacks(Above HCI) running in the Bluetooth controller attached to the Device.
The best place to start learning about Bluetooth is Bluetooth SIG website

Beginner Bluetooth Stack Advice


dhclient.conf - append to system hostname

Question: I'm running a Raspbian on a bunch of Raspberry Pis. They each have a unique hostname set in /etc/hostname and the dhcp client correctly registers that name with my router.
The problem I'm running into stems from having these Pis connected to the same network, and then same DHCP server, via ethernet and WiFi - There is a race-like condition that means the rest of the network, when using names to address these Pis, can't deterministically prefer the ethernet connections over the WiFi.
I'd like to make the Pis report a different hostname to the network DHCP server when obtaining a lease based on which interface they connect with. This seems to be possible in a static way by adding a lines like the following to /etc/dhcp/dhclient.conf.
interface "wlan0" {
  send host-name "MyHostname-1234-WiFi";
}

The problem I'm looking to solve is how to define that line programmatically. Something like this:
interface "wlan0" {
  send host-name "<hostname>-WiFi";
}

Looking into the docs for dhclient.conf(5), it suggests I can use the concat function from dhcp-eval(5) but I'm not having success. I'm trying this:
interface "wlan0" {
  send host-name concat(gethostname(), "-WiFi");
}

Answer: Just like in the related option statement, you have to explicitly mark expressions using an = sign:
  send host-name "static-value";
  send host-name = concat(gethostname(), "dynamic-value");

If you dhclient call in verbose mode (dhclient -cf myconfig.conf -v) it will tell you about the syntax error it otherwise silently ignores.


Calculate package latency when DPDK cycles overflow

Question: the following code used to calculate package latency:
TICK_PER_SECOND = rte_get_tsc_hz();

us_cycles = TICK_PER_SECOND / 1000 000;

register uint64_t received_cycles = rte_get_timer_cycles();

//sent_cycles will be recorded at somewhere
uint64_t latency = received_cycles > sent_cycles ? received_cycles - sent_cycles :
                       0xffffffffffffffff - sent_cycles + received_cycles;

uint64_t latency_us = latency / us_cycles

but sometimes latency_us will be a huge number like: 8384883669867977 us
is there some error calculation when the code handle cpu's cycles overflow?
should replace 0xffffffffffffffff with UINT64_MAX?
latency_us should be a normal value.
Comment: Yes. Try a couple of sample cases. Suppose, for instance, that your counter was 8 bits, and a packet was sent at cycle 253 and received eight cycles later at cycle 5. What is the 8-bit unsigned result of 5-253?
Comment: What was your reasoning behind that ternary calculation? Why not just `latency = received - sent`?
Comment: I think if cpu cycles overflow, received cycles will be smaller then send cycles., so i use the ternary calculation. Do you mean  just "received - send"  can also  handle this case?
Comment: Thank you. Sneftel. i try it and review subtraction for uint series. Perhaps the problem is not with calculation errors. i try to print received and sent cycles, like this:received_cycles:37510546898993433, sent_cycles: 37510546898993467. they are so closed. maybe there is some logci error in my code. anyway thank you!
Answer: rte_get_timer_cycles() (uint64_t) has incremental values but surely it will overflow after some time (around every 2 hours depending on your cpu speed) and start from 0 when it reaches the value near UINT64_MAX. so,
uint64_t latency = received_cycles > sent_cycles ? received_cycles - sent_cycles :
UINT64_MAX - sent_cycles + received_cycles;

should do just fine as you guessed


Problemas com filter() do dplyr

Question: Oi, gente.
Bom, eu fui tentar replicar um código que fiz no computador do trabalho no meu notebook. Em determinado momento, eu faço uma filtragem de dados com o dplyr utilizando os sinais "<" e ">". Quando fiz o código no meu notebook, a filtragem não funcionou, ele pega todos os valores. O dado está assim:

O código esta assim:
pilo12h<-piloexpression %>% select(GeneSymbol,FC12h,QV12h) %>% filter(FC12h>1.5 , QV12h< 0.01)

O problema é que ele está selecionando de QV12h maiores que 0,01, sendo que eu quero apenas os menores que isso, que são os significativos para mim. Eu uso esse mesmo código no computador do trabalho, e ele funciona perfeitamente.
Comment: Bem-vindo ao SOF Português Lukas! Para ajudar as pessoas que querem te ajudar, dê uma olhada neste [link](https://pt.stackoverflow.com/a/264276/80049) que detalha como podemos fazer uma pergunta reproduzível. Sua questão é bem ampla, que tal começar por compartilhar uma parte dos dados (`dput(head(data, 20))` e a função que usou?
Comment: Pode importar como csv mas use o argumento `stringsAsFactors = FALSE` da função `read.csv`.
Comment: Veja se este link te ajuda: https://pt.stackoverflow.com/questions/328859/como-dividir-os-dataframes-de-uma-lista-com-base-em-uma-vari%C3%A1vel-de-grupo-comum
Comment: Edite sua pergunta e coloque o código que você está usando. Dessa forma será mais fácil tentar reproduzir o seu problema
Comment: Pessoal, descobri o erro. Não sei por que, mas o R estava importando os meus dados como character, até os numéricos. Então, dava esse erro na hora de filtrar  os valores. Eu resolvi isso importando os dados como .xls, ao invés de .csv, como eu estava fazendo. Obrigado pela ajuda, ;)
Answer: Resposta por @Lukais Iohan Carvalho:
"Pessoal, descobri o erro. Não sei por que, mas o R estava importando os meus dados como character, até os numéricos. Então, dava esse erro na hora de filtrar os valores. Eu resolvi isso importando os dados como .xls, ao invés de .csv, como eu estava fazendo. Obrigado pela ajuda, ;) "

Problemas com filter() do dplyr


Did I set up memache correctly?

Question: I have applied memcache by via instructions from this page to our production server. The difference in numbers don't look stellar.
My question: Did I configure memcache improperly? Can I increase the CACHESIZE to perhaps get a better overall performance?
Settings.php
In settings.php, I've included this bit of text as recommend by the README.txt inside the memcache module.
/**************************************************
 * MEMCACHE
 **************************************************/
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['lock_inc'] = 'sites/all/modules/memcache/memcache-lock.inc';
$conf['memcache_stampede_protection'] = TRUE;
$conf['cache_default_class'] = 'MemCacheDrupal';

// The 'cache_form' bin must be assigned to non-volatile storage.
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

// Don't bootstrap the database when serving pages from the cache.
$conf['page_cache_without_database'] = TRUE;
$conf['page_cache_invoke_hooks'] = FALSE;

$conf['memcache_servers'] = array('server:11211' => 'default');

Memcache Conf
The memcache system conf has been left it's default:
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS=""

Benchmarks
I ran a battery of apache benchmark tests and these are the numbers
With memcache active
Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        1    1   0.4      1       4
Processing:     4   50   8.6     52      62
Waiting:        4   50   8.6     52      62
Total:          7   51   8.2     53      63

Without / Before / Baseline
Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        1    1   0.5      1       4
Processing:     3   50   8.4     52      61
Waiting:        3   50   8.4     52      60
Total:          7   51   7.9     53      62

Answer: I did end up increasing the RAM in the conf file. Since I've noticed no  evictions. In fact the eviction stat is at 0 at the moment.

Did I set up memache correctly?


SQL Server Log File

Question: I have a little issue about logging files. I want to export this string called test, but i dont know why i cant do that.
I know that command_string should not have more than 8000 characters. I don't understand why this doesn't work. Can anyone help me with that?
DECLARE @LogFilePath varchar(max)
DECLARE @teste varchar(max) = 'columnsToSelect = [street],[locality],[postalCode1],[postalCode2],[isMainAddress]'

SET @LogFilePath = 'C:\Users\epascoal\Documents\Logs\Log_ImportToSQ.txt'

SET @cmd ='echo '+ @teste +' >>'+@LogFilePath
exec master..xp_cmdshell @cmd

This works with smaller strings.
Question:How can i write large strings into a logfile?
Thanks in advance.
Answer: echo on command line has no 'out' parameter, and it wouldn't recognize it anyway without the parameters being properly escaped.
You can try actually redirecting it:
SET @cmd ='echo '+ @teste +' > '+@LogFilePath
exec master..xp_cmdshell @cmd

Redirecting like this is supposed to work.
Comment: Sorry, i mean it '>>' not 'out'. The problem here is that i cant write big strings.. like @teste is.

SQL Server Log File


Alternative characterization of complete metric space

Question: Let $(X,d)$ be a metric space. It is complete if every Cauchy sequence for $d$ on $X$ is convergent.
I've heard an alternative definition of completeness for $(X,d)$: it is complete iff the following condition holds:
Let $\{x_n\}\subset X$ be a sequence of points which leaves every compact set of $X$ (we say $\{x_n\}$ goes to infinity), then $\displaystyle{\lim_{n\rightarrow \infty}d(x,x_n)=\infty}$ for every point $x\in X$.
Is this alternative characterization right?
Where can I find a proof of the equivalence of the two characterizations?
Thank you!
Comment: A compact metric space is always complete, and in a compact space there is no sequence that eventually leaves each compact set, so the two *are* equivalent for compact metric spaces.
Comment: yes you're right
Answer: Consider $X = \mathbb R$ in the discrete metric. Then a set is compact if and only if it is finite. Now, take for example $x_n$ an enumeration of $\mathbb Q$. Then $x_n$ leaves eventually every finite subset of $\mathbb R$.
Also note that $d(x,x_n) \to 1$ for all $x \in \mathbb R$.
Comment: Yes, $d$ is the discrete metric.
Comment: Simpler: $x_n=n$. It would be a good idea to note explicitly that $X$ is complete. (But +1.)
Comment: @BrianM.Scott Right.
Answer: They are not alternative (First condition on metric space does not imply second)
Consider $(X,d)$, cone over $(S^1,d_0)$ where for $x\neq y\in S^1$,
$d_0(x,y)=\infty$ That is as a set $X$ is a unit ball in ${\bf
R}^2$. Here $$ d(re^{i\theta },r_2 e^{i\theta_2})=r+r_2 $$ for
$\theta\neq \theta_2$ and $$ d(re^{i\theta },r_2
e^{i\theta_2})=|r-r_2| $$ for $\theta =\theta_2$
Note that $X$ is closed so that it is complete. But
$\{x_n=e^{i\theta_n} \}$ where $\theta_n$ is distinct does not
convergent subsequence since $d(x_n,x_m)=2$ for $n\neq m$ So it is
not in any compact set. But $d(x,x_n)\leq 2$ for all $x\in X$


Header causing scrollview to not scroll to edit text when keyboard appears

Question: What I would like is when a user clicks on one of the edit texts for the screen to resize and scroll up so the it focuses on the that edit text.
The manifest is setup for adjust resize:
  <activity
     android:name=".ui.login.LoginActivity"
     android:label="@string/app_name"
     android:theme="@style/AppThemes"
     android:windowSoftInputMode="stateHidden|adjustResize"/>

The XML layout for the login screen:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="matrix"
        android:src="@drawable/main_background" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:orientation="vertical"
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <EditText
                    android:id="@+id/login_fragment_email_edit_text"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="7dp"
                    android:background="@color/white"
                    android:hint="@string/email"
                    android:inputType="textEmailAddress"
                    android:padding="8dp"
                    android:singleLine="true"
                    android:textSize="20sp"/>

                <EditText
                    android:id="@+id/login_fragment_password_edit_text"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/white"
                    android:hint="@string/password"
                    android:inputType="textPassword"
                    android:padding="8dp"
                    android:singleLine="true"
                    android:textSize="20sp" />

                <Button
                    android:id="@+id/login_fragment_register_button"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginBottom="7dp"
                    android:layout_marginTop="10dp"
                    android:background="@android:color/transparent"
                    android:minHeight="0dp"
                    android:text="@string/register"
                    android:textAllCaps="false"
                    android:textSize="16sp" />

                <Button
                    android:id="@+id/login_fragment_forgot_password"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginBottom="15dp"
                    android:layout_marginTop="5dp"
                    android:background="@android:color/transparent"
                    android:minHeight="0dp"
                    android:text="@string/forgot_your_password"
                    android:textAllCaps="false"
                    android:textSize="16sp" />

                <Button
                    android:id="@+id/login_button"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom"
                    android:background="@drawable/yellow_selector"
                    android:minHeight="0dp"
                    android:paddingBottom="7dp"
                    android:paddingTop="7dp"
                    android:text="@string/login"
                    android:textAllCaps="true"
                    android:textSize="18sp" />

            </LinearLayout>

        </LinearLayout>

    </ScrollView>
</RelativeLayout>

What's going wrong is when I uncommented the header for the screen, it doesn't scroll up but with it commented out it works as intended...what am I missing?
Comment: I saw your site. You're all rounder. ha in all the fields.
Comment: :) try to be at least
Comment: Keep it up....and how can i download your songs???
Comment: send me a github issue and I'll toss up a download https://github.com/isuPatches/RockThePatch
Comment: Can you post the code for your edit text?
Comment: Right now it's purely that xml..there's nothing in the Fragment/Activity tapping into those views until I get the scrolling behavior correct
Answer: Try scrolling to the view:
ScrollView scrollView = (ScrollView)findViewById(R.id.scrollview);
EditText editText = (EditText)findViewById(R.id.editText);
int[] coordinates = new int[2];
editText.getLocationOnScreen(coordinates);
scrollView.smoothScrollTo(coordinates[0],coordinates[1]);

Comment: I've tried that a few times...the issue I'm finding with that route is that it doesn't scroll the first time when the keyboard first pops up
Comment: @isuPatches - are you using full screen mode?
Comment: http://stackoverflow.com/questions/19859474/scrollview-not-working-when-keyboard-is-showing-in-android/22067230#22067230
Comment: So my app theme inherits from  `
Comment: So I tried a few things and what did work is adding a postDelayed of 1700-2000ms and then scrolling.  the issue seems to be as the keyboard is opening the scroll won't work but when it is open it's fine.  I'm still trying to wrap my head around a way to dynamically wait for that to happen.


Significance of a period in a time seiries

Question: I have a time series sampled in days and when I plot the amplitude vs time it looks like the signal is oscialating at an annual frequency. The series is 15 years long.
Is there a test I can use to test the significance of this frequency in the data? Meaning, test what is the probablity the oscilation is random.
I have used fft and autocorrelation to validate the existence of the period but these tests don't give a probablity measure as far as I know.
Answer: If I understood correctly you want to determine whether or not your series is plain white noise. If that's the case, the Ljung-Box test for autocorrelation should give you what you want.
Answer: To test the significance of the annual frequency, you need a probability model. As Digio pointed out, Ljung-Box test would work to test for the existence of autocorrelation in the ts. But it wouldn't be clear if that's the annual or seasonal pattern in the data.
I am sure there are many ways to approach this problem. But if I were you, I would build a model, e.g., ARMA with an annual trend, and see if the coefficient for that annual trend is significant or not. I could also use information criterion to compare two models, one with an annual trend, the other one without an annual trend.
Hope it helps.


iOS - Set Model class to be delegate of another Model class

Question: I have a CLLocationManager singleton which implements a protocol, so I can tell another model class (ServerConnection) that an updated location of the user has been found.
In my AppDelegate in the method, didFinishLaunching, I write
ServerConnection* serverConnection = [[ServerConnection alloc] init];
[LocationManager sharedLocationSingleton].delegate = serverConnection;
[[LocationManager sharedLocationSingleton] getUsersLocation];

This doesn't work and the delegate method in my ServerConnection class isn't called. However, if I try having my AppDelegate class be the listener, as in the following line, it works fine.
// self refers to AppDelegate
[LocationManager sharedLocationSingleton].delegate = self;

Here, my AppDelegate implements the required delegate method and the method is called when the user's location is updated, as it should.
Why is my above method failing, where I try to set the delegate to be serverConnection?
Tutorials online usually point to using a UIViewController or the AppDelegate as the "listener", but in my case, I want a separate model class to be the listener. How do I do that?
Below is my LocationManager singleton class with the protocol
@class LocationManager;

@protocol LocationManagerDelegate <NSObject>
@required
-(void)LocationManagerUpdated:(LocationManager*) locationManager
                  withValue:(CLLocation*) location;
@end

@interface LocationManager : NSObject <CLLocationManagerDelegate>

@property (strong, nonatomic) CLLocationManager* locationManager;
@property (strong, nonatomic) CLLocation* location;
@property (weak, nonatomic) id <LocationManagerDelegate> delegate;

+(LocationManager*)sharedLocationSingleton;
-(void) getUsersLocation;

@end

My header file for Server connection is.
#import <Foundation/Foundation.h>
#import "LocationManager.h"

@interface ServerConnection : NSObject <LocationManagerDelegate>
@end

This works when AppDelegate is set to be the listener, but not my model object ServerConnection. How do I fix this?
Thanks!
Comment: what is `ServerConnection` interface definition?
Answer: There should be no problem in doing what you are trying to do (i.e., having a non-controller class instance to act as a delegate).

This works when AppDelegate is set to be the listener, but not my model object ServerConnection.

Does your ServerConnection class implement the LocationManagerDelegate protocol? (I mean implement as opposed to just declare it in its interface).
Check the LocationManager method in charge for calling the delegate method (LocationManagerUpdated:) and add there a NSLog trace to check that the delegate object is correctly set when you try and send it the message.
EDIT:
ServerConnection* serverConnection = [[ServerConnection alloc] init];
[LocationManager sharedLocationSingleton].delegate = serverConnection;
[[LocationManager sharedLocationSingleton] getUsersLocation];

after you comment, it is clear that the issue stems from instantiating serverConnection in a stack variable and not in a property.
Your approach of making the delegate property a strong property is not correct since it leads to retain cycles. What you need to do is defining a strong serverConnection property in the class that executes the code I pasted above (the app delegate?).
If you don't mind my being rash, if you define the delegate as a strong property, what you are doing is fixing a bug by adding a second bug that hides the first one.
Comment: Thanks! Fixed this by changing my property declaration of the delegate from weak to strong
Comment: setting a delegate as a strong property is recipe for disaster, since it will cause a cyclic dependency:http://stackoverflow.com/questions/8449040/why-use-weak-pointer-for-delegation
Answer: It looks like serverConnection is not retained anywhere and because delegate property is specified as weak, it is released and set to nil.
Check getUsersLocation method and see if delegate is nil at the moment you are trying to call LocationManagerUpdated:withValue:
Comment: Thanks! I fixed it by making the delegate property strong instead of weak
Comment: You should not make delegate property strong. I would suggest to think about other solution. The question is, why don't you retain `serverConnection` anywhere. Maybe you don't need this `delegate` property and just make `serverConnection` as private property of your `LocationManager`


Adicionar Compilação da Biblioteca JNI com maven ou ant tasks

Question: Estou criando um projeto Java com métodos nativos (JNI) sem ter que criar três projetos separados para isso. O meu objetivo é compilar tudo o que preciso de uma única vez.
Uso apenas uma DLL/SO nesse projeto gerada por um único arquivo em C.
Como adicionar esta etapa de compilação e mover a biblioteca para a pasta dist no pom do maven ou no ant tasks?
A minha indiferença por maven ou por ant tasks é que pretendo usar o netbeans para compilar isso, por tanto o que for mais fácil de adaptar será o que estou procurando.
Answer: O Maven possui o Native Maven Plugin e o NAR Plugin for Maven. Ambos possuem goals para trabalhar com compiladores C/C++, gerar headers com javah, etc.
Caso você precise de uma solução "faça você mesmo", esse artigo (um pouco antigo) possui uma receita de bolo interessante. As classes são compiladas chamando o comando make através do AntRun e ele te mostra como carregar e empacotar corretamente as bibliotecas nativas no Maven (contemplando o cenário em que você deseja fazer build para múltiplas plataformas).
Answer: Eu uso o nar-maven-plugin para trabalhar com JNI, C e java num único projeto maven. Este plugin ficou por um tempo sem manutenção mas agora existe um grupo que retomou o desenvolvimento do projeto.
Este plugin cria automaticamente os cabeçalhos JNI a partir de métodos Java com a palavra reservada native, antes da compilação do código Java. Ele também cria automaticamente uma classe Java para carregar a DLL gerada, ajustando o nome da DLL de acordo com a versão (seguindo o padrão Maven). O plugin gera dois artefatos para um projeto JNI: o arquivo JAR e a DLL; assim é mais fácil manter casado o código C e Java.
Veja estes dois artigos, em português:
1 - JNI: Java e C++ Num Único Projeto Maven
2 - C++ e Maven: nar-maven-plugin
Acho que o primeiro artigo é exatamente o que você procura. Ambos possuem código fonte para download.
Comment: Bem vindo as Stack Overflow. Procure contextualizar melhor a sua resposta, inserindo partes relevantes dos links que possam resolver o problema. Da maneira que está, caso os sites externos saiam ou dar ou mudem o link, sua resposta se tornará inútil.


generating POJOs from JSON Schema for non-object types

Question: I am trying to generate POJOs from the JSON Schema of XMBC.
I do this with jsonschema2pojo.
However, nothing gets generated. It doesn't even bring me an error.
This is a reduced sample json schema I am trying to generate from:
{
  "description": "JSON-RPC API of XBMC",
  "id": "http://xbmc.org/jsonrpc/ServiceDescription.json",
  "methods": {
    "Addons.ExecuteAddon": {
      "description": "Executes the given addon with the given parameters (if possible)",
      "params": [
        {
          "name": "addonid",
          "required": true,
          "type": "string"
        },
        {
          "default": "",
          "name": "params",
          "type": [
            {
              "additionalProperties": {
                "default": "",
                "type": "string"
              },
              "type": "object"
            },
            {
              "items": {
                "type": "string"
              },
              "type": "array"
            },
            {
              "description": "URL path (must start with / or ?",
              "type": "string"
            }
          ]
        },
        {
          "default": false,
          "name": "wait",
          "type": "boolean"
        }
      ],
      "returns": {
        "type": "string"
      },
      "type": "method"
    }
  },
  "notifications": {
    "Application.OnVolumeChanged": {
      "description": "The volume of the application has changed.",
      "params": [
        {
          "name": "sender",
          "required": true,
          "type": "string"
        },
        {
          "name": "data",
          "properties": {
            "muted": {
              "required": true,
              "type": "boolean"
            },
            "volume": {
              "maximum": 100,
              "minimum": 0,
              "required": true,
              "type": "integer"
            }
          },
          "required": true,
          "type": "object"
        }
      ],
      "returns": null,
      "type": "notification"
    }
  },
  "types": {
    "Addon.Content": {
      "default": "unknown",
      "enums": [
        "unknown",
        "video",
        "audio",
        "image",
        "executable"
      ],
      "id": "Addon.Content",
      "type": "string"
    }
  },
  "version": "6.14.3"
}

I must admin that my knowledge of JSON is very terse, maybe it is just a simple fault of mine. But can anyone help me how I can generate Java objects from such a JSON Schema?
Answer: The JSON Schema doesn't support method. JSON schema defines json data structure, it would not be used to define your methods. Most important attribute in JSON schema is properties.
It's good to generate POJO data models from a JSON schema, but not business logic. You can learn the JSON schema from those examples.


how do you add functionality to a button without using javascript in HTML

Question: I have added a button to my HTML code and i want to add some functionality to it so that when i press it, it performs a task but the problem is i do not know any javascript so how can i do it without using javascript.
i tried creating a function with a function name that i assigned to the button during assigning the onclick option. i created the function inside the head tag in the html code.
Comment: Please add your code in a sample to let us understand better what you're trying to do.
Comment: If you really are not prepared to use JS you can't sensibly use a button element. You could look into anchor elements (a) or input elements with type checkbox - they enable you to do a little bit without JS, but TBH you need to learn a bit of JavaScript.
Comment: You could use a  to trigger a server action. On server, you may have more options available.
Comment: also onclick is a handler for manipulation using JS
Comment: Hi Lucky, welcome! Please show some [reprex] of what you created so we can help you with your specific problem. Don't make us guess what you did...
Comment: "_i want to add some functionality_" **What functionality?** You might find [ask] helpful in writing a good question.
Answer: depends on the what type of task you want it to perform, you can simply go to different links by using anchor tags, or navigate to different parts by having ids using id. Also you can use CSS to trigger different styles on the state of your buttons. your question is very vague it doesn't looks like you are facing any issue.


Get Java json in raw format (only enclosing strings with quotes) with gson

Question: Imagine I have the following JsonObject
{"name":"Test Name","id":13,"isimportant":true}
I would like to add this to mysql, so I would iterate through the members with
void test(JsonObject jsonobject) {
        String names="";
        String values="";
        Set<Entry<String, JsonElement>> entrySet = jsonobject.entrySet();
        for(Map.Entry<String,JsonElement> entry : entrySet) {
            String key=entry.getKey();
            names+="`"+key+"`,";
            values+="\""+jsonobject.get(key).getAsString()+"\",";
        }
        ... create an insert query from the `names` and `values` strings
        ... and add to database
}

To make sure the strings are processed correctly, I enclose all the values with quotes, so this would result in a query like
INSERT INTO TestTable (name,id,isimportant) VALUES ("Test Name","13","true")

I would prefer only to have quotes on the actual string variables, i.e.
INSERT INTO TestTable (name,id,isimportant) VALUES ("Test Name",13,true)

using the same formatting as in the original json.
How can this be achieved? I generally use the gson library, i.e. JsonObjects rather than JSONObjects.
Comment: why not parsing them to their respective types ?
Comment: because the actual code contains a lot more variables and it would be a lot easier to just use the formatting from the existing json
Answer: Think I found a solution using getAsJsonPrimitive
            if (entry.getValue().getAsJsonPrimitive().isString())
                values+="\""+jsonobject.get(key).getAsString()+"\",";
            else
                values+=jsonobject.get(key).getAsString()+",";

Since JsonPrimitive still contains the quotes where applicable, one can just do
            values+=entry.getValue().getAsJsonPrimitive().toString()+",";

which does exactly what I require.


Existence of law

Question: How do you prove that it exists a probability space $(A,\mathcal{A}, \mathcal{P})$ and a random variable $X$ such that
$$
\mathcal{P}_{X} = f d\mathcal{L}
$$
with $f(x) = \exp\left(-\frac{x^{2}}{2}\right)$
My question is not specific to the Gaussian law, I can ask the same thing for any law.
For the answer a ref will be enough, thanks and regards.
Answer: Take space $(A,\mathcal A,\mathcal P)=(\mathbb R,\mathcal B(\mathbb R),\mathcal P)$ where $\mathcal P$ is prescribed by $B\mapsto\int_Bfd\mathcal L$.
Then prescribe random variable $X:A\to\mathbb R$ by $a\mapsto a$ (i.e. the identity function).
Then $\mathcal P_X=\mathcal P=fd\mathcal L$.
Comment: The least I can say is that you answered to the question ! It was not what I had in my mind, but it's my fault so I accept your answer ^^.

Existence of law


Root Test: What happens if $\lim\limits_{n\rightarrow \infty} \sqrt[n]{|a_n|} =1$?

Question: Root Test: For a series $\sum\limits_{n=1}^\infty a_n$, let $\ell = \lim\limits_{n\rightarrow \infty} \sqrt[n]{|a_n|}$.  Series is convergent if $\ell <1$ and divergent  if $\ell \geq 1$. I have the question about $\ell =1$. Some of the standard calculus book mention that the root test fails for $\ell =1 $ and some other mention it is divergent in this case. Your thought please.
My thought: $\lim\limits_{n\rightarrow \infty} \sqrt[n]{|a_n|} \geq 1$ imples that
$|a_n| \geq 1$ for sufficiently large $n$ which means $\lim\limits_{n\rightarrow \infty} |a_n|\geq 1 \neq 0$. Therefore divergent by the Divergence test.
Comment: You can't say anything. It can converge or diverge ! For example $\sum_{n}1^n$ diverge, but $\sum_{n}\frac{1}{n^2}$ converge
Comment: Please, provide examples.
Comment: I gave you example :)
Comment: No text says $l=1$ implies divergence.
Comment: @zhw: Look at the book Introduction to Analysis, by Edward Gaughan, page no. 185.
Comment: I don't have that book, but I tend to doubt it says what you claim. Can anyone check this? Anyway, the examples you've been given here show the $l=1$ case is indeterminate.
Comment: I checked 5th edition of the book, and the relevant theorem says: If, for infinitely many $n$, $\sqrt[n]{|a_n|}\geq1$, then $\sum_{n=1}^{\infty}a_n$ diverges. This not only is a true statement, but also assumes something fairly different from $\sqrt[n]{|a_n|}\to1$.
Answer: Hint. One may observe that $\displaystyle\sum_{n\geq1} \frac{1}{n}$ and $\displaystyle\sum_{n\geq2} \frac{1}{n\log^2 n}$ behave differently, the former is divergent, the latter is convergent, in both cases
$$
\lim\limits_{n\rightarrow \infty} \sqrt[n]{|a_n|} =1.
$$
Comment: @Mr.MBB. Just apply https://en.wikipedia.org/wiki/Cauchy_condensation_test. and you obtain $\sum\frac{1}{n^2}$, which converges
Comment: It's easier to look at $\sum 1/n^2$ in place of your second series.
Comment: Please prove a proof of your second example.
Answer: If $a_n=\frac{1}{n}$ then the series diverges but $\sqrt[n]{a_n}$ converges to $1$.
If $a_n=\frac{1}{n^2}$ then the series converges but $\sqrt[n]{a_n}$ converges to $1$.


Did Novell Netware ever come in 64-bit?

Question: I need to know for my script, was there ever a 64-bit version of Netware? I am going to guess no.
Answer: Hm, I would be pretty sure.
http://en.wikipedia.org/wiki/Novell_NetWare
NetWare 6.5 was released in August 2003 - last version that is, the next onwe was named Open Enterprise Server and a different product. It's version 2 has 64 bit as feature, so it is quite samfe to assume that Netware did not have it.
Answer: 64bit Netware did exist inside Novell as a project for some time around 1999/2000, and got to be pre-alpha stage code before the project was dropped. Novell has now ported most of the Netware services that were Netware centric over to Linux, and most of the Netware services are now available in OES2 which runs atop SLES (Suse Linux) which is available in 64bit.

Did Novell Netware ever come in 64-bit?


How to create custom bundle of "User" entity using GUI?

Question: Is it possible to create custom bundle from "user" entity without programming? Only using drupal administration? Are there any modules that could help to create such bundles?
I would like to achieve, that some user roles would have custom fields. I have found this module for creating fields per user role, but maybe it would be better to create custom user bundle.
Answer: I had the same requirement recently and was able to achieve this using the Profile2 module.  Basically you set up profiles and add custom fields to that particular profile.  Then you create a user using that profile.  Works great but if you are pulling a view of these you must reference the profile in a relationship.
Profile2
https://drupal.org/project/profile2
Comment: Also you can set each profile to be set to a particular role upon creation.
Answer: If you are trying to restrict certain fields to particular user roles then Field Permission module is the perfect one.

The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

If you want to group certain fields under user entity then you might be looking for Profile2 module.

The module is aimed to provide a simple, but extensible solution
  providing a similar end user interface like the core profile module by
  default. Multiple profile types may be created via the UI (e.g. a
  general profile + a customer profile), whereas the module provides
  separated permissions for those.


Como carregar JS corretamente com Ember?

Question: Tô tentando configurar esse template http://wrapbootstrap.com/preview/WB0048JF7 em um projeto com Ember, entretanto, a biblioteca principal nifty.js não está carregando o elemento .mega-dropdown (menu topo) e o elemento #mainnav (menu lateral). Meu ember-cli-build.js está assim:

/*jshint node:true*/
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    // Add options here
  });

  // Use `app.import` to add additional libraries to the generated
  // output files.
  //
  // If you need to use different assets in different
  // environments, specify an object as the first parameter. That
  // object's keys should be the environment name and the values
  // should be the asset to use in that environment.
  //
  // If the library that you are including contains AMD or ES6
  // modules that you would like to import into your application
  // please specify an object with the list of modules as keys
  // along with the exports of each module as its value.

  // Bootstrap 3.3.6
  app.import({
    development: 'vendor/nifty/plugins/bootstrap/css/bootstrap.css',
    production:  'vendor/nifty/plugins/bootstrap/css/bootstrap.min.css'
  });

  app.import({
    development: 'vendor/nifty/plugins/bootstrap/css/bootstrap.css.map',
    production:  'vendor/nifty/plugins/bootstrap/css/bootstrap.min.css.map'
  }, { destDir: 'assets' });

  // fonts
  app.import('vendor/nifty/plugins/bootstrap/fonts/glyphicons-halflings-regular.eot', { destDir: 'fonts' });
  app.import('vendor/nifty/plugins/bootstrap/fonts/glyphicons-halflings-regular.svg', { destDir: 'fonts' });
  app.import('vendor/nifty/plugins/bootstrap/fonts/glyphicons-halflings-regular.ttf', { destDir: 'fonts' });
  app.import('vendor/nifty/plugins/bootstrap/fonts/glyphicons-halflings-regular.woff', { destDir: 'fonts' });

  /*****************************
  ***    Nifty Styles
  ******************************/

  // Themify Icons
  app.import({
    development: 'vendor/nifty/themify-icons/css/themify-icons.css',
    production:  'vendor/nifty/themify-icons/css/themify-icons.min.css'
  });

  // fonts
  app.import('vendor/nifty/themify-icons/fonts/themify.eot', { destDir: 'fonts' });
  app.import('vendor/nifty/themify-icons/fonts/themify.svg', { destDir: 'fonts' });
  app.import('vendor/nifty/themify-icons/fonts/themify.ttf', { destDir: 'fonts' });
  app.import('vendor/nifty/themify-icons/fonts/themify.woff', { destDir: 'fonts' });

  // Page Load Progress Bar
  app.import({
    development: 'vendor/nifty/plugins/pace/pace.css',
    production:  'vendor/nifty/plugins/pace/pace.min.css'
  });

  // Magic Checkbox
  app.import({
    development: 'vendor/nifty/plugins/magic-check/css/magic-check.css',
    production:  'vendor/nifty/plugins/magic-check/css/magic-check.min.css'
  });

  // Theme style
  app.import({
    development: 'vendor/nifty/css/nifty.css',
    production:  'vendor/nifty/css/nifty.min.css'
  });

  /*****************************
  ***    Nifty Scripts
  ******************************/

  app.import({
    development: 'vendor/nifty/plugins/pace/pace.js',
    production:  'vendor/nifty/plugins/pace/pace.min.js'
  });

  // jQuery
  app.import({
    development: 'vendor/nifty/plugins/jquery/jquery-2.2.4.js',
    production:  'vendor/nifty/plugins/jquery/jquery-2.2.4.min.js'
  });

  // Bootstrap 3.3.6
  app.import({
    development: 'vendor/nifty/plugins/bootstrap/js/bootstrap.js',
    production:  'vendor/nifty/plugins/bootstrap/js/bootstrap.min.js'
  });

  // Nifty Admin
  app.import({
    development: 'vendor/nifty/js/nifty.js',
    production:  'vendor/nifty/js/nifty.min.js'
  });

  return app.toTree();
};

esse trecho que quero que seja executado

77375    $(document).ready(function(){
77376        $(document).trigger('nifty.ready');
77377    });

..
77454    $(document).on('nifty.ready', function(){
77455        megadropdown = $('.mega-dropdown');
77456        if(megadropdown.length){
77457            megadropdown.niftyMega();
77458            $('html').on('click', function(e) {
77459                if (!$(e.target).closest('.mega-dropdown').length) {
77460                    megadropdown.removeClass('open');
77461                }
77462            });
77463        };
77464    });

Não sei como fazer com que o Ember de carga, mas, se executo no console $('.mega-dropdown').niftyMega(); o menu passa a funcionar..
Como posso fazer o ember carregar o js para que tudo fique clicavel igual ao template do exemplo??????
Answer: Você pode executar o código $('.mega-dropdown').niftyMega(); no hook didInsertElement() do seu componente.


Items inside a CSS Grid fill the row height?

Question: I have found many answers showing how to set a CSS Grid (using display: grid) rows to match the tallest item in the grid, but what I'm looking to do is size the items inside the grid to match the grid.
For example, here's a sample row in the grid.  See how the first item is flush to the grid, while the other 2 items are shorter and have white space below them (since their title are shorter)?  How can I get all the items to fit the grid itself?

The code for the grid:
.video-grid {
 display: grid;
 grid-gap: 20px;
 grid-template-columns: repeat(3, 1fr);
}

Comment: If you think your question is not a duplicate @steve please provide a [mcve].
Answer: You can set display: flex; flex-direction: column to your grid items and make the part you want to fill all the available height grow with flex: 1. A similar approach was used in this article.
Answer: use justify property in the second and third child to stretch them in the full div, or make a parent div for these the second and third child respectively, and then make the inner children i.e the second and third child have the display as grid.
You can see the correct commands here
Comment: All three children are already stretched to the whole height (look at the white background area). The problem is to make their content take all their height, so that the gray footers stick to their bottom.


Variables injected or set in a Twig file are undefined after the first position of an entity reference field

Question: I have a Paragraph setup that has an entity reference field allowing an editor to select multiple nodes to use in a display.
Based on the count of nodes, I want to trigger a class. I figured a way to do this was with hook_preprocess_node() in the theme:
$referringItem = $node->_referringItem;
    if (!empty($referringItem)) {
      $referringEntity = $referringItem->getEntity();

      if (
        !empty($referringEntity)
        && ($referringEntity instanceof NodeInterface || $referringEntity instanceof Paragraph)
       ) {
        $referringEntityType = $referringEntity->getType();
        $referringEntityTypeId = $referringEntity->getEntityTypeId();
      }
    }

if ($referringEntityType == 'homepage_feature') {
        $count = $referringEntity->get('field_items')->count();

        // Default.
        $variables['top_image'] = FALSE;
        $variables['right_image'] = FALSE;

        // Should this be count is only 1 AND it is the first delta item in field_feature?
        // If not, any single item Homepage Feature will get top-image which may not be
        // desired.
        if ($count == 1) {
          $variables['top_image'] = TRUE;
        }
      }

The logic above might be too involved. Basically I am looking back to see what paragraph type was used, so I can pass new variables to the template.
What I noticed is that even though the code is hit for every node listed, the variables only exist in the first node. I dumped them in the template and it is correct there, but they are undefined in the other nodes.
In Twig, I tried dumping the variable at the top of the template:
{{ top_image }}
I can see it in the first record 1 above the markup, and then it never shows again.
How can I ensure the variables are passed to the template, correctly, every time?
Edit:
Looks like using the same node with the same view mode in different paragraphs or entity references on the same page can cause this to happen.
Is the solution then to add cache tags/context to the node being rendered to account for what parent is outputting it?
Comment: @leymannx, yes, there could be a solution in preprocess, but the node preprocess is too late. Perhaps it's possible in the parent paragraph preprocess hook, retreiving there the information like you said and add it to the node reference field including the cache keys.
Comment: You can't count on the property `_referringItem` being present in preprocess, because this is added by the field formatter for internal use and when the node is rendered you might have a new instance of the node object. A solution might be extending the field formatter, add the information you want to the build array of the field elements and add cache keys (tags/context won't help in this case and you need to add the cache keys in the field formatter, preprocess is too late).
Comment: Where are the keys added? The only place I see it is EntityReferenceFormatterBase::view. So this formatter would be applicable to Paragraphs and change that from Rendered Entity to the new one?
Comment: Where exactly do you want the class being added? Isn't it also that when dumping a variable multiple times with Kint and they all have the same output that Kint sometimes only shows one value? And: Why don't you simply load the paragraph and from there the field and count its items?
Comment: The class is added on the node, but the class (there are others) is entirely dependent upon where it is in the list (multi reference paragraph) or if its just a single entry. So the information has to get communicated somehow. The Paragraph type also allows for multiples. The thought is, using the node and view mode and altering the CSS classes based on that.
Comment: It's not the revision based reference field used to reference paragraphs. To reference nodes you use at the moment `EntityReferenceEntityFormatter`, which is based on the class you've mentioned and inherits view() which sets this property. When you extend this class and assign a new id and label in the annotations you can add the plugin in UI when configuration the view mode of the paragraph.
Comment: OK, then preprocess node, check view mode, load paragraph field, foreach through all paragraphs, check type, if right type, load field, count items, add class. No?
Comment: Wow 4k4, that seemed to do the trick. I'll update the question with what I did.
Answer: Based on the comments to the question, I extended the EntityReferenceEntityFormatter class and modified one part in the viewElements method (the rest is the same):
  $view_builder = $this->entityTypeManager->getViewBuilder($entity->getEntityTypeId());
  $elements[$delta] = $view_builder->view($entity, $view_mode, $entity->language()->getId());

  try {
    $parent = $items->getParent();
    $parent_entity = $parent->getValue();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->id();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->bundle();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->getEntityTypeId();
    $elements[$delta]['#cache']['keys'][] = 'context_aware';

    // Add special information for different paragraph types.
    if ($parent_entity->getEntityTypeId() == 'paragraph') {
      if ($parent_entity->bundle() == 'homepage_feature') {
        $elements[$delta]['#style_flags']['top_image'] = FALSE;
        $elements[$delta]['#style_flags']['right_image'] = FALSE;

        if ($parent_entity->get('field_items')->count() === 1) {
          $elements[$delta]['#style_flags']['top_image'] = TRUE;
        }
      }
    }
  } catch (\Exception $e) {
    // Add logging
  }

Later on, down in preprocess_node:
// ONLY for the homepage handling of featured content.
      if ($referringEntityType == 'homepage_feature') {
        $variables['top_image'] = $variables['elements']['#style_flags']['top_image'];
        $variables['right_image'] = $variables['elements']['#style_flags']['right_image'];
      }

I was able to then add the same node in the same paragraph type multiple times with the correct information. The correct classes are now applied.
Edit:
Just to add to this too, be sure to set your cacheable dependencies so any change to what holds references will not require a cache clear:
$parent = $items->getParent();
$entity->addCacheableDependency($parent);

Edit 2:
Thanks to extra guidance from 4k4, I injected the renderer service and reduced down to:
    $parent = $items->getParent();
    $parent_entity = $parent->getValue();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->id();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->bundle();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->getEntityTypeId();
    $elements[$delta]['#cache']['keys'][] = 'context_aware';

    if ($this->paragraphDisplaySettings->isApplicable($parent_entity)) {
      $elements[$delta]['#style_flags'] = $this->paragraphDisplaySettings->getSettings($parent_entity);
    }

    $this->renderer->addCacheableDependency($elements[$delta], $parent);

paragraphDisplaySettings is a custom service object that aids in evaluating different flags to pass through from the original code just to keep it cleaner and leaner. It's working great.
Comment: Adding the tags is a good idea, but I would attach them to the render array `$renderer->addCacheableDependency($elements['delta'], $parent);` Otherwise you get again a dependency on the object instance as discussed before. The risk is lower now because of the added cache keys, but I think the render array is a cleaner solution.
Comment: Where is the `$renderer` object? I don't see that mentioned in `EntityReferenceEntityFormatter` or parent classes.
Comment: `$renderer = \Drupal::service('renderer');` see https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays
Comment: Ah okay, so I should inject the service to my formatter?
Comment: That works. Thanks again for your help, this was very insightful.


To find limits of double integral in Polar

Question: Question is to find the volume of region that lies under the paraboloid $z=x^{2} + y^{2}$ and above triangle in XY PLANE enclosed by the lines $y=x$, $x=0$ and $x+y=2$.
I can clearly see from graph that limits of $\theta $ are from $\pi/4$ to $\pi/2$.But how do i find out $r=f(\theta)$ limits. Thanks
Answer: Subtract the equation of the top portion from the bottom portion of the solid. In this case,$x^2+y^2-0=x^2+y^2$. Rewrite it in polar coordinates: $x^2+y^2=r^2$.
Hence, volume is $\displaystyle\int_{\frac{\pi}{4}}^\frac{\pi}{2}\displaystyle\int_{0}^{\frac{2}{\cos\theta+\sin\theta}}r^2\cdot r \ drd\theta$.
Note: $\frac{2}{\cos\theta+\sin\theta}$ is the equation of $x+y=2$ in polar coordinates. I separated $rdrd\theta$ term to emphasize the correcting factor is included.
Answer: Hint: Look at the vertices of the triangle in question. You have their $(x,y)$ coordinates. What are their $(r,\theta)$ coordinates?


Rare Events Model with a discrete index as the dependent variable?

Question: I'm looking for a rare events model where the dependent variable is a discrete index, which means I cannot use the rare events logit model (Gary King).  My dependent variable is an index of integers that range from 0 to 15, but the median is 0 and the mean is about 0.25, which implies that getting a value of 1 or more is pretty rare for this dataset.
Any ideas on a model that would be better than simply running an OLS on the indexed dependent variable?  And if you could recommend an R package that can get this job done, then all the better!
Comment: Is your dependent variable continuous or discrete?  You refer to it as continuous twice, but then describe it as an index of integers that range from 0 to 15, which would be discrete.
Comment: Multinomial logit/probit seems like it would work. I've done it in stata, but haven't tried it in R.
Comment: Procedures like logit and probit underestimate the probability of rare events, which is why I'm looking for a model that is designed for such rare occurrences in the data.  Essentially, I'm looking for a model like the rare events logit that does not require the dependent variable to be binary.
Comment: Sorry about that -- it's a discrete index.  I was trying to make it clear that it is not binary data, like the rare events logit model.
Comment: Is your index really just indexing an event, or is it a count of some sort?  (Does 4=2*2?)
Answer: No matter what model you use very rare events are a problem because you may never see them in your data or if you do you will not see many unless you look for events over a very long time period.  I don't think it is ever a good idea to just conjure up a model that will give some answer that may be accurate when the model is correct but could be sensitive to departures from the model.  For very rare events the model assumptions may be difficult or impossible to check.  It would help if there is a physical basis for the choice of the form of the point process.  Maybe a Poisson model would be appropriate or maybe you have apriori reason to believe there is overdispersion in which case a negative binomial might be more appropriate.
Comment: I ended up going with a negative binomial, which I was leaning toward at the beginning.  I appreciate your post, and I'll give you  the check since I ended up using a NB.
Answer: You could maybe try ordinal logistic regression,  treatment of that along the lines of Gary Kings rare event logistic regression should be possible!
Some other similar posts with relevant answers is:  Rare event ordinal logit with discrete response $Y_t \in \{1,2,3\}$ Strategy to deal with rare events logistic regression


Processes in uninterruptable sleep killing server

Question: I have a opensuse 11 64 bit server with some issues I'm not sure how to solve. I'm getting hundreds of these in the porocess list:
<code>4     0  3105     1  20   0  55420  3488 646312 Sl   ?          0:02 /usr/lib/udisks/udisks-daemon
1     0  3106  3105  20   0  46700   800 685268 S    ?          0:25  \_ udisks-daemon: polling /dev/sr0
4     0 21303  3105  20   0  13296   728 -      D    ?          0:00  \_ udisks-helper-ata-smart-collect /dev/sdb 1
0     0 21847  3105  20   0  13296   436 scsi_b D    ?          0:00  \_ udisks-helper-ata-smart-collect /dev/sdb 1
0     0 22399  3105  20   0  13296   440 -      D    ?          0:00  \_ udisks-helper-ata-smart-collect /dev/sdb 1
0     0 22935  3105  20   0  13296   436 -      D    ?          0:00  \_ udisks-helper-ata-smart-collect /dev/sdb 1
0     0 23474  3105  20   0  13296   440 -      D    ?          0:00  \_ udisks-helper-ata-smart-collect /dev/sdb 1
0     0 24023  3105  20   0  13296   440 -      D    ?          0:00  \_ udisks-helper-ata-smart-collect /dev/sdb 1
0     0 24559  3105  20   0  13296   436 -      D    ?          0:00  \_ udisks-helper-ata-smart-collect /dev/sdb 1
0     0 25100  3105  20   0  13296   436 -      D    ?          0:00  \_ udisks-helper-ata-smart-collect /dev/sdb 1
0     0 25639  3105  20   0  13296   440 -      D    ?          0:00  \_ udisks-helper-ata-smart-collect /dev/sdb 1
</code>
Generally over 300 or so over a couple of days, the load averages can get as high as 300 or so BUT the server is still responsive ~ I suspect the load averages are being reported incorrectly for some reason.  I know the only way to get rid of these processes is to reboot, but I'm trying to figure out how to prevent them from appearing. I've disabled the smartd daemon, I've unmounted the /dev/sdb partition. I don't know what's calling the udisk helper...
any thoughts on how to track this down and prevent it from happening?
[BTW - I have tested the disk manually, it is fine - not failing.]
Answer: Sounds like a bug.  See the following thread:
http://ubuntuforums.org/showthread.php?t=1573929&page=2
Comment: The workaround does seem to work. [would be nice of there was an actual fix though]
Answer: Usualy this is a problem related a hardware resource that the process is trying to access, maybe can be a driver/module related to the disk controller or its firmware version. Try to check some bugs/issues are reported for your hw
Answer: While I cannot add anything to your main problem, I would like to note that the load average is not, in fact, incorrect. Load is defined as the average number of processes waiting for resources (not necessarily CPU), and each process in "D" state counts as one toward the machine's load.


integers solution (x,y)

Question: How many tuple (x,y) positive integer solution to
$13/x^2 + 1996/y^2 = 2/1997$
I've done many algebraic manipulation to the equation but can't find any thing.
How I find the solution?
Answer: $$  2 x^2 y^2 = 1996 \cdot 1997 x^2 + 13 \cdot 1997 y^2,$$
$$  2 x^2 y^2 - 1996 \cdot 1997 x^2 - 13 \cdot 1997 y^2 = 0,$$
$$  4 x^2 y^2 - 2 \cdot 1996 \cdot 1997 x^2 - 2 \cdot 13 \cdot 1997 y^2 = 0,$$
$$ ( 2 x^2 - 13 \cdot 1997) ( 2 y^2 - 1996 \cdot 1997 ) = 13 \cdot 1996 \cdot 1997^2 = 2^2 \cdot  13 \cdot 499 \cdot 1997^2$$

integers solution (x,y)


Cycle index of cyclic group

Question: How to show that the cycle index for the cyclic group $C_n$ (the group of rotations of regular $n$-gon) is
$$P_{C_n} (t_1 , \ldots ,t_n)= \frac{1}{n} \sum_{d\mid n} \phi (d) t_d^{\frac{n}{d}},$$ where $\phi$ is the Euler function.
Answer: Steps

First you can write $C_n=\left \{Id,r,\cdots,r^{n-1}\right \}$ with $r$ is the elementary rotation of the $n$-gon.
Given $0\leq k\leq n$ let $d=\gcd(k,n)$ you can easily see that $\bigl\langle r^k\bigr\rangle=\bigl\langle r^d\bigr\rangle$, and actually $r^d$ and $r^k$ has the same type: they consist of $d$ cycles of length $\frac{n}{d}$
For every $d$ a divisor of $n$ the number of permutations with the same type as $r^d$ is exactly $\varphi(\frac{n}{d})$ which comes from the number of integers $k$ such that $\gcd(n,k)=d$ and $0\leq k\leq n$
Conclude
Comment: $\bigl\langle x\bigr\rangle$ denotes the group generated by $x$.
Comment: First, it's equal to the number of integers $0\leq k\leq n$ such that $d=\gcd(k,n)$, this is the same as the number of $0\leq k'\leq \frac n d $ such that $1=\gcd(k',\frac n d)$ and this the definition of Euler's totient function.
Comment: What is the meaning of this $=$ statement in the second point.
Comment: Hey can you elaborate the third point a bit? I didn't get how there are exactly $\phi(\frac{n}{d})$ many permutations with same type as $r^d$.

Cycle index of cyclic group


Java Entry Validation

Question: I'm working on a server/client battleship game using sockets. Part of the project requires entry validation on the client side for entering tile locations. A user is supposed to enter a letter A-E and a number 1-5, and right now if you type in something invalid, it seems to freeze. Any help would be much appreciated, thanks in advance!
            do{
            System.out.println("------------------------------------------------------------------------------------------------");
            System.out.println("Please type in a board position in the format of a letter followed by number, such as 'A1'. ");
            Scanner sc = new Scanner(System.in);
            String BoardChoice = sc.next();
            if(BoardChoice.equals("A1" ) || BoardChoice.equals("B1" ) || BoardChoice.equals("C1" ) || BoardChoice.equals("D1" ) || BoardChoice.equals("E1" ) ||
               BoardChoice.equals("A2" ) || BoardChoice.equals("B2" ) || BoardChoice.equals("C2" ) || BoardChoice.equals("D2" ) || BoardChoice.equals("E2" ) ||
               BoardChoice.equals("A3" ) || BoardChoice.equals("B3" ) || BoardChoice.equals("C3" ) || BoardChoice.equals("D3" ) || BoardChoice.equals("E3" ) ||
               BoardChoice.equals("A4" ) || BoardChoice.equals("B4" ) || BoardChoice.equals("C4" ) || BoardChoice.equals("D4" ) || BoardChoice.equals("E4" ) ||
               BoardChoice.equals("A5" ) || BoardChoice.equals("B5" ) || BoardChoice.equals("C5" ) || BoardChoice.equals("D5" ) || BoardChoice.equals("E5" ))
            {
                flagtoo = false;
                writer.writeUTF(BoardChoice);
            }
            else
            {
                System.out.println("Invalid Input Please re-enter!");
            }
            }while(flagtoo);

Comment: not sure but maybe move `Scanner sc = new Scanner(System.in); `  before the `do` statement
Comment: `String BoardChoice = sc.next();  ` should be `String BoardChoice = sc.nextLine();` otherwise you're never reading to the end of the buffer
Comment: Yep! turns out that's all it was. Thanks!
Comment: FYI: you could simply you validation by using something like `BoardChoice.matches("[A-E][1-5]")`, which will return `false` if the input is not valid
Comment: "That's all it was"... which one?  There are two suggestions in the comments.
Comment: The above code works for me as is, running on Windows in Command Prompt.  Perhaps reopening a new Scanner might fail on some platforms.  (It's not the right thing to do, though.)
Answer: I would suggest you test each character separately by breaking them out with charAt, and please respect variable naming conventions. Something like
boolean valid = false;
String boardChoice = sc.nextLine(); // <-- not next
if (boardChoice.length() == 2) {
    char col = boardChoice.charAt(0);
    char row = boardChoice.charAt(1);
    // The parenthesis here are just for clarity.
    valid = ((col >= 'A' && col <= 'E') && (row >= '1' && row <= '5'));
}

Answer: My suggestion on the other hand will suggest to implement regex with a pattern that allows you to match 1st char alpha(no matter capitalization) followed by a number,
both in a range from a → e and 1 → 5
    Scanner sc = new Scanner(System.in);

    System.out.println("Please type in a ....y number, such as 'A1'. ");

    do {
        inp = sc.nextLine();
        if (inp.matches("^[a-eA-E1-5]{0,2}")) {
            inpArr[k++] = inp;

        } else {
            System.out.println("invalid input");
        }
    } while (k < numberOfElements);

    System.out.println(Arrays.toString(inpArr));

Java Entry Validation


Leibniz test $\sum\limits_{n=1}^\infty \sin\left(\pi \sqrt{n^2+\alpha}\right)$

Question: I am given a series:
$$\sum\limits_{n=1}^\infty \sin\left(\pi \sqrt{n^2+\alpha}\right)$$
And in the description of the problem it is said that I must show by Leibniz test that it is convergent. How can I even get the $(-1)^n$ symbol out of the starting series?
Comment: Use that $\sqrt{n^2+\alpha}-n\to 0$. You might need a stronger result that estimates how fast that goes to zero.
Answer: Your series is convergent.
As $n$ tends to $+\infty$, we may write
$$
\begin{align}
u_n &:=\sin \left( \pi \sqrt{n^2+\alpha^2 }\right)\\
&=\sin \left( \pi n \:\sqrt{1+\frac{\alpha^2}{n^2}}\right)\\
&=\sin \left( \pi n \:\left(1+\frac{\alpha^2}{2n^2}+\mathcal{O}\left(\frac{1}{n^4}\right)\right)\right)\\
&=\sin \left( \pi n +\frac{\pi\alpha^2}{2n}+\mathcal{O}\left(\frac{1}{n^3}\right)\right)\\
&=(-1)^n\sin \left(\frac{\pi\alpha^2}{2n}+\mathcal{O}\left(\frac{1}{n^3}\right)\right)\\
&=\frac{\pi\alpha^2}2\frac{(-1)^n}{n}+\mathcal{O}\left(\frac{1}{n^3}\right)
\end{align}
$$
giving the convergence of the initial series $\displaystyle \sum u_n$.
Comment: @mlata You may check that $\sin(\pi n+a)=(-1)^n\sin a$.
Comment: In the before last step you put $(-1)^n$ as the amplitude $\sin$, but how did you lost the $\pi \alpha$?
Answer: Write $$\begin{align}
\sqrt{n^2+\alpha}&=n + \left(\sqrt{n^2+\alpha}-n\right)\\
&=n+\frac{\alpha}{\sqrt{n^2+\alpha}+n}
\end{align}
$$
Now $\sin (n\pi + x)=(-1)^n\sin(x)$. Letting $$x_n=\frac{\alpha}{\sqrt{n^2+\alpha}+n}$$ we see that it is positive and decreases to zero, and thus that $\sin(x_n\pi)$ is positive and decreases to zero.
You might have to slightly alter the argument if $\alpha$ can be negative, but deal with that as a special case.


How to have an environment specific drush.yml?

Question: I'm using Drush 9. With the old drushrc.php I could easily include a local.drushrc.php that dynamically set the site url. How can I do it now?
This is similar to How can i set site url dynamically in Drush-9?. However I don't want to pass the url in every Drush command. I think of something like below in ../drush/drush.yml:
drush:
  paths:
    config:
      - ${env.home}/local.drush.yml

But I'd need another variable that point to the Drupal site directory (sites/default in a monosite, sites/CURRENT-SITE in a multisite). Does such a variable exist?
Answer: Here's what I do on my sites and it works:
Step 1: sites/default/drush.local.yml
options:
  uri: 'https://dev.example.com'

You can name this file however you want. Also, since this file varies from env to env, I ignore it with .gitignore. At the same time, I commit an example.drush.local.yml.
Step 2: drush/drush.yml

One level above Drupal installation, .i.e. where Drupal's index.php  is located, I have my composer.json and vendor directories.
In this directory, I create a directory named drush and in it, I place a drush.yml with these contents:

drush:
  paths:
    config:
      - web/sites/default/drush.local.yml

After this, I running drush st from that directory, will show you that the drush.local.yml has been detected and the site URI is set correctly.
Comment: Great answer, I was wondering how to do it in the last few days.
Comment: This the correct answer. I have read a few posts on using drushrc.php and sites.php, but they did not work for me with Drupal 9.X. +1 Thanks
Comment: I second that, and what is awesome is you can use environment variables in the yml using `${env.VAR_NAME}`. I wanted this to be in my repo, so I created a file for each like `env-${env.DEPLOY_ENV}.drush.yml` so `env-stage.drush.yml` and within each file put the domain name I wanted to use. You could also try `uri: 'https://${env.VIRTUAL_HOST}'` and a single drush file if you for example had access to your URI in that manner. That would make it super dynamic.
Answer: Reading https://github.com/drush-ops/drush/blob/master/examples/example.drush.yml it seems you can put a site specific drush.yml in a sites directory. It is merged with the global file(s).
PS! I haven't tested this myself.
Comment: Ok, I've figured this out: For `sites/default/drush.yml` to be recognized by drush you have to run drush from the drupal root folder.   This used to not be a problem in drush 8 with sites/default/drushrc.php
Comment: Tested but it didn't work. I agree that it should have worked.
Comment: Try checking your own `example.drush.yml` file in case you have an older version. [The local config filename used to be different](https://github.com/drush-ops/drush/commit/cf00e0536e86801adcce08a9443e71ddf99733bc).
Comment: I'm already on Drush 9.3.0. The file `sites/default/drush.yml` is not automatically detected. I thought this was a problem with lightning, but I try with a standard distribution and I have the same result.
Comment: Confirming that I'm on Drush 9.5.2  and the documentation suggests that the first place it checks is sites/default/drush.yml but this doesnt seem to be the case, because it is not picking up the default --uri option i have configured in that file  `options:  uri:  http://mysite.test` when I run `drush uli`.  Not sure what's wrong.
Comment: Even adding ```drush:
  paths:
    config:
      - ../web/sites/default/drush.yml```  into /drush/drush.yml doesnt seem to help
Comment: Hang on, this is weird. this config ^, ^^ just started working without explanation after a clean site install.  maybe drush cleared its own cache or something?


SQL OPENQUERY UPDATE

Question: I am trying to update Oracle table from SQL server. I have setup a linked server, and i am able to update this table using following query.
UPDATE OPENQUERY(LNK_SRV, 'SELECT BOGNUMBER, BOGDATA FROM DATA.BOGTAB')
SET BOGNUMBER = 009
WHERE BOGDATA = 'LIVE'

Now the above query will be very slow as you can imagine, as entire data from table DATA.BOGTAB is not filtered and the where clause is SQL server query.
I want to optimize the above query, so that it is fast and the one way i see to do it is executing this update statement on remote server by creating a dynamic query and executing it.
I think it will help if the where clause is somehow embeded in the query which will be executed on remote server, as it will give a filtered dataset.
Can anybody please help me figure out how i can dynamically create a query and execute this update statement. Thanks!
Answer: Tried a few thing and i have got a solution for this...
DECLARE @VC_DYN_QUERY NVARCHAR(255)
SET @VC_DYN_QUERY = 'UPDATE DATA.BOGTAB SET BOGNUMBER = 009 WHERE BOGDATA = ''LIVE'''
EXECUTE (@VC_DYN_QUERY) AT LNK_SRV

This will just execute the dynamic query that we prepare on remote server, this is will be a lot faster, as there is no heavy data that we transfer over the network, or we do not have any expensive comparison in where clause on SQL server.
Hope somebody benefits from this, like i did. Thanks!

SQL OPENQUERY UPDATE


Specifying composites of morphisms in a localisation of a triangulated category

Question: I am reading the book Triangulated Categories by Neeman. I have come across  a sentence and I'm not really sure what it is trying to say. For those with access to the book, it is Remark 2.1.23.
Let $\mathcal{D}$ be a triangulated category with triangulated subcategory $\mathcal{C}$. Denote by $\text{Mor}_{\mathcal{C}}$ the class of morphisms whose mapping cone is in $\mathcal{C}$. In the usual way we can form the Verdier localisation which I will denote by $\mathcal{D}/\mathcal{C}$ with a quotient functor $Q : \mathcal{D} \rightarrow \mathcal{D}/\mathcal{C}$. The morphisms are given by roofs (or spans) and the composite of two composable spans is given by taking the homotopy pullback of their summits.
A composite of spans then looks something like this (diagram taken from the text)
http://tinypic.com/r/2up360i/9
where $P$ is the homotopy pullback of $f_{2}$ and $g_{1}$. Here $v'$, $f_{1}$, and $f_{2}$ are in $\text{Mor}_{\mathcal{C}}$, and
$$Q(g_{2})Q(f_{2})^{-1} Q(g_{1})Q(f_{1})^{-1} = Q(g_{1})Q(u')Q(v')^{-1}Q(f_{1})^{-1}.
$$
The text then remarks that,

In other words, to give two composable morphisms $X \rightarrow Y$ and $Y \rightarrow Z$ in $\mathcal{D}/\mathcal{C}$, and their composite, is nothing other than to give $X' \rightarrow Y'$, and $Y' \rightarrow Z'$ in $\mathcal{D}$ and maps $X' \rightarrow X$, $Y' \rightarrow Y$, and $Z' \rightarrow Z$ in $\text{Mor}_{\mathcal{C}}$ expressing the isomorphism of hte composable pair in $\mathcal{D}/\mathcal{C}$ with a composable pair in $\mathcal{D}$.

I have no idea what is meant by this remark. How does the argument to that point imply that? I am struggling to see why it is true, and struggling even more to see how it is simply a rephrasing of the equality above. How is a composite of morphisms in the quotient category determined that way, and moreover, what precisely is meant by the "expressing the isomorphism of the composable pair..."?
Any help is appreciated.
Answer: Comparing Neeman's notation to the picture, $X',Y',Z'$ become $ P, W_2, Z$ while $X,Y,Z$ are the same in both places. The vertical morphisms in the picture are the isos Neeman describes; in the picture, the isomorphism $Z'\to Z$ is trivial, but of course it could be nontrivial and we'd still have a well defined morphism. In particular $g_2$ is determined as a map in $D/C$ by the other data, so superfluous.