Is this post about DFS algorithm right?

Question:
what's wrong? I think stack no.4 has to be changed [G P E].
Is there any way i can skip vertex G when i visit vertex P?
I think there is no way. Is it wrong?
Comment: It's not clear to me what you are asking. What do you mean with "skip vertex G when I visit P"? Are you trying to code this?
Comment: When i visit P, is there any way i do not visit G and back to H.
Comment: Well, just don't visit it. I don't understand what the problem is.
Comment: It is dfs. You can not back to H if there are any neighbor of P.
Answer:
what's wrong?

Nothing.

I think stack no.4 has to be changed [G P E].

No, it shouldn't. You want the stack to have at its top the element to be topped. 'G' has to appear at the end of the Depth-first traversal, thus it's a good idea to have it at the bottom of the stack.
An element that lies in the bottom of the stack will be popped last.
An element at the top of the stack will be popped first.
Comment: i say [G E P] should be changed [G P E]. G is bottom element.
Answer: This is a variant of the standard DFS algorithm. In the standard algorithm, you would not put the unvisited neighbors of the current node all on the stack, but only the node itself, to then visit one neighbor. After having performed a DFS on that neighbor, you would backtrack and only then look at the other children. If there is still an unvisited one among them, only then it gets pushed on the stack.
But this alternative -- where all unvisited neighbors are put on the stack before deepening the traveral -- will work fine as well.
When you put a node on the stack, you should also mark it as stacked, a mark that will never be removed again during the graph traversal, even if the node is popped from the stack later. That way you can ensure that a node will never be put on the stack more than once during the whole traversal.
When arriving at node P, all the neighbors of P (i.e. G and H) have already been stacked before (H has been pulled from it, and G is still on it). As there are no other neighbors of P, this DFS algorithm pulls the next node from the stack (i.e. E) to continue the traversal.
Here is a JavaScript implementation:

class Node {
    constructor(name) {
        this.name = name;
        this.neighbors = [];
    }
    link(node) { // link nodes in both directions
        this.neighbors.push(node);
        node.neighbors.push(this);
    }
    toString() { // The string representation of the node is its name
        return this.name;
    }
    dfs() { // Main algorithm
        const stack = [this], // Start with this node on the stack
            stacked = new Set(stack); // ...and mark it as stacked

        while (stack.length > 0) { // While the stack is not empty...
            console.log('stack: ' + stack);
            const node = stack.pop(); // Pull next node from the top of the stack
            for (const neighbor of node.neighbors) {
                // Only push neighbors on the stack
                // that were never stacked before:
                if (!stacked.has(neighbor)) {
                    stack.push(neighbor); // Push on the stack,
                    stacked.add(neighbor); // ... and mark as stacked
                }
            }
        }
    }
}

// Define nodes:
const a = new Node('A'),
      e = new Node('E'),
      g = new Node('G'),
      h = new Node('H'),
      j = new Node('J'),
      m = new Node('M'),
      p = new Node('P'),
      x = new Node('X'),
      y = new Node('Y');

// Define the links between the nodes
a.link(x);
x.link(g);
x.link(h);
g.link(h);
g.link(p);
h.link(e);
h.link(p);
e.link(m);
e.link(y);
y.link(m);
m.link(j);

// Visit the nodes of the graph, starting at A
a.dfs();
.as-console-wrapper { max-height: 100% !important; top: 0; }

Note that if a graph is a tree, then a DFS traversal down the tree can never encounter a node that was already visited before, so in that case no such marking is necessary. But your graph is an undirected cyclic graph, so this extra marking is needed.
Answer: This is DFS. You can push them in the stack in any order. now issue at all.
DFS has many ways to traverse in depth.

Is this post about DFS algorithm right?


get checkbox state from controller

Question: my Grails project I have a checkbox. I want to call a remoteFunction in onCheck() method of the checkbox, like the following:
if(checkbox.isChecked)
{
    //do something
}
else
{
    //do some other thing
}

The fact is that I don't know how to get the state of the checkbox in controller, after its check / uncheck. Is it needed to use some javascript code?
Any suggestion?
EDIT:
this is the checkbox
<g:checkBox name="hasStampDuty" value="${receiptInstance?.hasStampDuty}"
            onclick="${remoteFunction(
                    controller: 'Receipt',
                    action: 'addStampDuty',
                    params: '\'id=\' + this.id+\'ischecked=\'+this.checked',
                    onSuccess: 'updateTotalAmount(\'totalAmount\', data, \'00000\')')}"
/>

where addStampDuty is as follows:
def addStampDuty(Long id, boolean ischecked)
{
    //add stamp duty value
    def receiptInstance = Receipt.get(id)
    if(ischecked != null)
    {
        if(ischecked) {
                  //do something
        }
        else {
              //do some other
        }

    }

}

But id is always null...
Comment: Then you may want to rephrase your question since you said "get the current state of the checkbox in controller".
Comment: The state of a checkbox in a controller is if the element exits with a value or not in the params. For example, if you have an element called 'something' and it's checked when the form is sent to your controller params.something will have a value. If it's not checked then params.something won't have a value.
Comment: the fact is that I need to check the checkbox before the sumbit, so the params has not the params.something
Answer: Under normal circumstances, the state of the checkbox is passed to the action in parameters. As noted in the comments above, the presence or not of a parameter with the form "${fieldName}.selected" indicates whether the checkbox is selected (checked) or not. I agree that it is a little awkward. However if you muck with the parameters directly, then you may have messed up that contract.
You can put the following code at the start of your action to see exactly what it is passed in params:
   log.info("Executing \"blah\" action.")
   params.each { log.info("Param ${it.key} = {$it.value}") }

As a side note, if you want to do this on all actions, then create a filter (see Grails filters) and cross cut as you see fit.
Finally, I believe that the Grails AJAX wrapper tags have been deprecated and you should probably avoid their use. Just post the form using the jquery (or whatever you fancy) AJAX client support and let the form fields populate the params in the normal Grails conventions. You should read the

get checkbox state from controller


How to add input field in views fields?

Question: I have to store some hidden values in each views rows (To store Latitude and Longitude of Gmap Locations). How to add a input hidden field in Views Field. I tried bartik_preprocess_views_view_fields(&$variables) but it is not invoked.
Comment: Do you want to hide the values from the screen but want to keep it in browser?
Comment: @SumitMadan yes!
Answer: I added the latitude and longitude in views fields and overwritten the global: Custom Text field with the replacement tokens and added "element-hidden" class so that value will be there in views in hidden. Any other Solutions?
Comment: Thats it. You need the same. Or you can add these classes to the lat long fields so no need to add custom text field. :)
Comment: Yeah that would be more simple.

How to add input field in views fields?


Como atualizar um TreeView de diretórios em C#

Question: Tenho um componente TreeViewMS (aquele com Seleção Multipla) listando os diretórios do sistema em um Form.
criei um evento no Form que quando for apertado F5, esse TreeView se atualize(caso tenha
algum novo diretório no sistema ou não).
Ele até chega a atualizar normalmente, por em seguida é arremessado um NullReferenceException na TreeView MS.dll na classe inicial do programa (Program.cs)
segue código para carregar a TreeView.
private void LoadTreeView() {
   tvDirectories.Nodes.Clear();
   exArq.CreateDirectoryTree(tvDirectories);
}

eis a Excessão:
An unhandled exception of type 'System.NullReferenceException' occurred in TreeViewMS.dll
Additional information: Referência de objeto não definida para uma instância de um objeto.
Método CreateDirectoryTree faz a busca dos diretórios do sistema e monta a arvore, acredito que ele não seja o problema mas segue o método:
public TreeViewMS.TreeViewMS CreateDirectoryTree(TreeViewMS.TreeViewMS treeView) {

    foreach (DriveInfo drv in DriveInfo.GetDrives()) {
        TreeNode rootDirectoryNode = new TreeNode();
        rootDirectoryNode.ImageIndex = ImageIndexs.SystemDiskIcon;
        rootDirectoryNode.SelectedImageIndex = ImageIndexs.SystemDiskIcon;
        rootDirectoryNode.Text = drv.Name;

        switch (drv.DriveType) {

            case DriveType.Network:
                rootDirectoryNode.ImageIndex = ImageIndexs.NetworkDiskIcon;
                rootDirectoryNode.SelectedImageIndex = ImageIndexs.NetworkDiskIcon;
                break;

            case DriveType.CDRom:
                rootDirectoryNode.ImageIndex = ImageIndexs.CDDiskIcon;
                rootDirectoryNode.SelectedImageIndex = ImageIndexs.CDDiskIcon;
                break;

            case DriveType.Fixed:
                rootDirectoryNode.ImageIndex = ImageIndexs.LocalDiskIcon;
                rootDirectoryNode.SelectedImageIndex = ImageIndexs.LocalDiskIcon;
                break;

            case DriveType.Removable:
                rootDirectoryNode.ImageIndex = ImageIndexs.RemovalDiskIcon;
                rootDirectoryNode.SelectedImageIndex = ImageIndexs.RemovalDiskIcon;
                break;

        }

        bool isSystemDirectory = drv.Name.ToString() == Path.GetPathRoot(Environment.SystemDirectory);

        if (isSystemDirectory) {
            rootDirectoryNode.ImageIndex = ImageIndexs.SystemDiskIcon;
            rootDirectoryNode.SelectedImageIndex = ImageIndexs.SystemDiskIcon;
        }

        rootDirectoryNode.Nodes.Add(String.Empty);

        treeView.Nodes.Add(rootDirectoryNode);
    }
    return treeView;

}

Eu suspeito que seja a maneira de limpar a TreeView que deva estar causando o erro.
Eu imagino que não deva ser, mas vou incluir também onde é expandido o nó:
private void tvDiretorios2_BeforeExpand(object sender, TreeViewCancelEventArgs e) {
     TreeNode newNode = exArq.GetDirectoriesAndFilesNodes(e.Node);
}

e a função que busca esses diretorios
public TreeNode GetDirectoriesAndFilesNodes(TreeNode parentNode) {

    string nodePath = parentNode.FullPath + Constants.DIRECTORY_SEPARATOR;

    DirectoryInfo rootDirectory = new DirectoryInfo(nodePath);
    parentNode.Nodes[0].Remove();
    try {

        foreach (DirectoryInfo dir in rootDirectory.GetDirectories()) {

            TreeNode directoryNode = new TreeNode();
            directoryNode.Text = dir.Name;
            directoryNode.Nodes.Add(String.Empty);
            directoryNode.ImageIndex = ImageIndexs.DirectoryIcon;
            directoryNode.SelectedImageIndex = ImageIndexs.DirectoryIcon;
            parentNode.Nodes.Add(directoryNode);

        }

        foreach (FileInfo file in rootDirectory.GetFiles()) {

            bool isExcel = Path.GetExtension(file.Name).ToLower().Equals(Constants.EXTENSION_EXCEL_X) || Path.GetExtension(file.Name).ToLower().Equals(Constants.EXTENSION_EXCEL);

            bool isZipedFile = Path.GetExtension(file.Name).ToLower().Equals(Constants.EXTENSION_RAR) || Path.GetExtension(file.Name).ToLower().Equals(Constants.EXTENSION_ZIP);

            bool isTextFile = Path.GetExtension(file.Name).ToLower().Equals(Constants.EXTENSION_TXT);

            TreeNode fileNode = new TreeNode();
            fileNode.Text = file.Name;

            if (isExcel) {
                fileNode.ImageIndex = ImageIndexs.ExcelFileIcon;
                fileNode.SelectedImageIndex = ImageIndexs.ExcelFileIcon;
            } else if (isZipedFile) {
                fileNode.ImageIndex = ImageIndexs.ZipedFileIcon;
                fileNode.SelectedImageIndex = ImageIndexs.ZipedFileIcon;
            } else if (isTextFile) {
                fileNode.ImageIndex = ImageIndexs.TextFileIcon;
                fileNode.SelectedImageIndex = ImageIndexs.TextFileIcon;
            } else {
                fileNode.ImageIndex = ImageIndexs.GenericFileIcon;
                fileNode.SelectedImageIndex = ImageIndexs.GenericFileIcon;
            }

            parentNode.Nodes.Add(fileNode);
        }

    } catch (UnauthorizedAccessException) {
        TreeNode errorNode = new TreeNode();
        errorNode.Text = "Acesso Negado";
        errorNode.ImageIndex = ImageIndexs.NoPermissionIcon;
        errorNode.SelectedImageIndex = ImageIndexs.NoPermissionIcon;
        parentNode.Nodes.Add(errorNode);
    } catch (IOException) {
        TreeNode errorNode = new TreeNode();
        errorNode.Text = "O Dispositivo não está pronto";
        errorNode.ImageIndex = ImageIndexs.DriverNotReady;
        errorNode.SelectedImageIndex = ImageIndexs.DriverNotReady;
        parentNode.Nodes.Add(errorNode);
    }

    return parentNode;
}

Obrigado a quem puder ajudar.
Comment: Seria interessante você postar o código do método `BuscarDiretorios`.
Comment: Notei que você faz o Cast da classe derivada **TreeViewMS** de volta para **TreeView**. Suponho que você esteja trabalhando com [esta classe](http://www.codeproject.com/Articles/2756/C-TreeView-with-multiple-selection) mas, de qualquer forma, não seria melhor adaptar seus métodos, como **CreateDirectoryTree()** e outros, para trabalharem com o tipo da classe derivada TreeViewMS? Acho arriscado usar a interface da classe mãe, porque podemos acabar usando métodos de **TreeView** que foram sobrepostos (_overrides_) ou sombreados (_shadows_) por implementações específicas em **TreeViewMS**.
Comment: A exception vem na hora em que você cria a pasta via sistema operacional? Você tem no seu projeto algum objeto que monitora alterações nos diretórios, por exemplo um [FileSystemWatcher](https://msdn.microsoft.com/pt-br/library/system.io.filesystemwatcher%28v=vs.110%29.aspx)?
Comment: Prezado, não trabalho com .NET, mas no construtor da classe LoadTreeView, você tem certeza que os objetos tvDirectories e exArq estão instanciados? Ao depurar o código, o que acontece? Parece ser alguma coisa de ciclo de vida do controle (objeto visual). Aliás, vc devolve um objeto TreeView? Meio esquisito isso, pois você está sobrescrevendo a instancia e as referências podem ficar totalmente fora de contexto. Por que simplesmente não devolve somente a hierarquia dos nós e recebe como entrada a referência da TreeView? Entende?
Comment: Afinal, me parece que está faltando isto  tvDirectories = exArq.CreateDirectoryTree(tvDirectories); no construtor. Você está devolvendo uma instância de TreeView...
Comment: inserido amigo @jbueno
Comment: @VbobCat fiz as alterações correspondentes aqui e atualizei na pergunta também, obrigado por notar esses erros, porém continua sem funcionar, em meus testes, eu acesso um diretório pelo programa, crio uma pasta nova fora dele, atualizo o TreeView e volto a esse diretório, porém, assim que eu crio a nova pasta, a exception já é arremessada, antes mesmo de eu atualizar.
Comment: Sim! depois de criar via sistema operacional. não uso o FileSystemWatcher (não conhecia inclusive), mas não consigo imaginar onde adicionar ele nessa situação. a Arvore é criada pelo DirectoryInfo.
Comment: Creio que sem usar um FileSystemWatcher, não se está consumindo eventos gerados diretamente pelo sistema operacional. Em que instante exatamente você tem a exceção? Logo que cria a pasta nova no Windows Explorer, ou quando retorna ao seu programa e tenta usar o TreeView? Se for esse segundo caso, o que me parece é que a execução começa no manipulador do evento BeforeExpand, e encontra algum objeto (talvez interno) que se tornou "null". Qual o escopo da variavel **newnode** em `private void tvDiretorios2_BeforeExpand(object sender, TreeViewCancelEventArgs e)`? Por que ela é definida duas vezes?
Comment: então, assim que eu volto para o programa e o TreeView é exibido é arremessada a exceção. a Variavel newNode tem escopo de classe (o form que usa o evento BeforeExpand), vou verificar se ele é usado em outro método, se não for, deixarei ele dentro do BeforeExpand, quanto a ser definido duas vezes, vou verificar também e posto uma atualização.
Comment: atualizado @VBobCat contudo o erro persiste, mas agradeço sua ajuda.
Answer: Guilherme, para te ajudar a identificar onde está o erro, voce pode incluir nos seus códigos um try...catch, assim você consegue identificar onde está o erro. voce pode colocar um breakpoint no throw.
Usando o breakpoint você pode avaliar toda a cadeia da exceção e ver onde está o erro.
private void LoadTreeView()
{
    try
    {
        tvDirectories.Nodes.Clear();
        exArq.CreateDirectoryTree(tvDirectories);
    }
    catch (Exception ex)
    {
        throw;
    }
}

Comment: obrigado pela ajuda Alexandre, essa função foi desnecessária para meu sistema e entreguei sem ela. obrigado mesmo assim.


Finite summation over reciprocal of binomial coefficient

Question: Problem: Simplify
$$ \sum_{m=0}^k a^m m! (n-m)!$$
where $a$ is real and positive, $k \in \mathbb N$ and $n \in \mathbb N$ with $k \leq n$.
Upper bounds and lower bounds may also be useful. One example I have found  is, assuming $a \neq 1$ and using $m! (n-m)! \leq n!$,
$$ \sum_{m=0}^k a^m m!(n-m)! \leq n! \sum_{m=0}^k a^m = \frac{n! \left(1 - a^{k+1} \right)}{1-a},$$
but I am not satisfied with the accuracy of this bound.
I am aware of the somewhat related math.stackexchange.com question:  Calculate $\sum\limits_{k=0}^{\infty}\frac{1}{{2k \choose k}}$
Comment: Using Euler Beta function one gets $\displaystyle (n+1)!\int\limits_0^1 (1-x)^{n-k}\frac{(ax)^{k+1}-(1-x)^{k+1}}{(a+1)x-1}dx$ for the sum. Maybe you can use this for a better approximation.
Comment: That particular estimate is also valid if $a > 1$, just multiply both numerator and denominator by $-1$.
Answer: One Idea is to estimate entropy function based on the value of $k$ (if you know the range of it)
$n \choose m $ $\approx 2^{nH(\frac{m}{n})}$
Now, if you know $k$ you can find a linear approximation to $H(x)$ in $[0,\frac{k}{n}]$ and use it to simply calculate the summation


Norms on continuous function

Question: Let $f(x)=x^2-x$, $x\in[-1,1]$. Find $\lVert f\rVert_2$.
Some other norms on $C[a,b]$:
$\lVert f\rVert_1=\int_a^b \lvert f(x)\rvert~\mathrm{d}x$.
$\lVert f\rVert_2=\left(\int_a^b \lvert f(x)\rvert^2~\mathrm{d}x\right)^{1/2}$.
I know the answer to this problem is $\sqrt{\frac{2}{3}}$, but am unable to solve it; the only way I get the answer is if I ignore the square. Can I get some help please?
Comment: Since you are only interested in $\|f\|_2$, what's the point of defining $\|f\|_1$?
Comment: Hint: $(x^2-x)^2=x^4-2x^3+x^2$.
Comment: How positive are you that the correct solution is $\sqrt{\frac{2}{3}}$?
Comment: 100% correct, that's the answer given.
Comment: @Lorago already done this, it was first method does not provide the answer
Answer: Following your definition of $\left\Vert f\right\Vert_2$ one can simply insert $f\left(x\right)=x^2-x$ into the formula and integrate the sum term by term:
$$
\begin{aligned}
\left\Vert f \right\Vert_2 &= \sqrt{\int_{-1}^1\left\vert x^2 - x\right\vert^2 dx}\\
&= \sqrt{\int_{-1}^1x^4-2x^3+x^2dx}\\
&= \sqrt{\left. \frac{1}{5}x^5 - \frac{1}{2}x^4 + \frac{1}{3}x^3 \right\rvert_{-1}^1}\\
&= \sqrt{\frac{1}{5}-\frac{1}{2}+\frac{1}{3}-\left(-\frac{1}{5}-\frac{1}{2}-\frac{1}{3}\right)}\\
&= \sqrt{\frac{2}{5}+\frac{2}{3}} = \sqrt{\frac{16}{15}} = \frac{4}{\sqrt{15}}
\end{aligned}
$$
Comment: answer as per text is sqrt(2/3)
Comment: Maybe you incorrectly transcribed the original definition in your question?
Comment: No, I did not. But I feel the answer provided is incorrect, I have tried various options but by no means it is  sqrt(2/3). for an abs function it is only positive in the region of -1<=x<0 for the function provided. The problem is they did not provide the solution in details.

Norms on continuous function


Lognormal with negative values

Question: I have some logged increments from time series data and wanted to fit a lognormal distribution, but obviously some are negative. How can I do this?
Comment: If you have negative values, your data aren't lognormal. It may be that some modification is feasible (e.g. a mixture of lognormal and something else, or a lognormal location-mixture of, say, normals, or a shifted lognormal, or ...), but the lognormal itself isn't possible. But if the original values are lognormal, logged values would be fitted by a normal, which handles negatives. Can you more explicitly show what you mean by 'logged increments'? I can see two ways to interpret it and only one (the less likely one) makes a lot of sense for this, I think.
Comment: Can you please clarify: Are you trying to take the logarithm of the increments, or are you taking the increments of the logarithm? Taking the logarithm of some increments is almost never going to make sense.
Answer: I think you've confused what the lognormal distribution is. If Y follows a lognormal distribution, then log(Y) follows a normal distribution. You seem to be thinking, incorrectly, that if Z follows a normal distribution, then log(Z) follows a lognormal distribution, which is not the case. It's an easy mistake to make.
In time series analysis, you often assume that the variable you're tracking, call it Y, changes multiplicatively. That is, $Y_{i+1}=Y_i * e ^ \delta$. When taking the log of both sides you'll see that $\log Y_{i+1} = \log Y_i + \delta$. This is why we talk about log increments. Now we assume that $\delta$ is normally distributed, which would make $e^\delta$ follow a lognormal distribution.

Lognormal with negative values


Como evitar chamadas a função

Question: Tenho em meus sistemas uma chamada para uma função de javascript e sempre funcionou. É uma função para exibir/esconder uma imagem de carregando para o usuário. O problema é que as vezes eu tenho que chamar essa função em uma ação do usuário de um campo select, por exemplo, e caso o usuário fique altere 10 vezes seguidas esse campo select irá fazer 10 chamadas, o que não tem problemas, mas é ruim para o usuário ficar aparecendo ainda a imagem pois ele fica carregando e sumindo as 10 vezes.
Segue um exemplo para melhor entendimento do que estou dizendo.
Nesse caso não é nenhuma ação que demore para executar, mas por eu ter muitas chamadas de ajax que podem demorar um pouco mais, daí a necessidade de eu exibir para o usuário que esta carregando.
Meu código:
$(document).ready(function() {
     $("select[name=meuSelect]").change(function(event) {
         event.preventDefault();

         var valor = $(this).val();

         ajaxLoadAni('In');
         $("#valor").text(valor);
         ajaxLoadAni('Out');
     });
});

function ajaxLoadAni(inOut) {
    'use strict';

    if (inOut === 'In') {
      $('#ajaxLoadAni').fadeIn('slow'); //EXIBE A IMAGEM DE CARRREGANDO
    } else {
        $('#ajaxLoadAni').fadeOut('slow'); //ESCONDE A IMAGEM DE CARRREGANDO
    }
}

Exemplo funcionando no JSFiddle
Comment: Um `stop` da animação antes do fadeIn resolveria? http://jsfiddle.net/QZ9q8/2/
Comment: Será que poderia mostrar o código relevante?
Comment: Esta ali o link http://jsfiddle.net/QZ9q8/1/ de todo código @Tivie
Comment: Obrigado, não tinha visto
Comment: Sem crise... caso vá alterando o select com as setas do teclado fica mais fácil de entender.
Comment: @bfavaretto resolve sim, falta um pouco de conhecimento mesmo. Valew. Deixe como resposta para pode ficar melhor sinalizado né.
Comment: @bfavaretto não seria um stop no fadeOut?
Comment: Sei que não é o foco, mas vale lembrar uma melhor forma de usar o `document.ready`, usando [IIFE - Immediately Invoked Function Expression (em inglês)](http://benalman.com/news/2010/11/immediately-invoked-function-expression/). [Exemplo aqui](https://gist.github.com/anonymous/9618702). Abraço.
Answer: Você pode resolver isto facilmente parando a animação utilizando .stop() antes de dar .fadeOut() e pode ficar melhor ainda se você também dar um .stop() no .fadeIn() também pois eu realizei alguns testes e se você trocar muito rapidamente você percebe que a animação se repetiu uma vez, por isso:
Você estava utilizando fadeIn() e fadeOut() sem parada:
$('#ajaxLoadAni').fadeIn('slow'); //EXIBE A IMAGEM DE CARRREGANDO
$('#ajaxLoadAni').fadeOut('slow'); //ESCONDE A IMAGEM DE CARRREGANDO

Adicionando uma parada ficaria assim:
$('#ajaxLoadAni').stop(true,true).fadeIn('slow'); //EXIBE A IMAGEM DE CARRREGANDO
$('#ajaxLoadAni').stop(true,true).fadeOut('slow'); //ESCONDE A IMAGEM DE CARRREGANDO

Desta forma você irá parar a animação anterior antes de sair, assim não tendo que mostrar/esconder várias vezes para o usuário.
Detalhe importante sobre a função stop():
Os parâmetros da função .stop() servem para limpar a fila de animações e também finaliza-las, que seriam:

stop([clearQueue],[jumpToEnd])
[clearQueue] - Caso true, indica que a animação deve ser removida da fila.(default false).
  [jumpToEnd] - Caso true, indica que a animação deve ser completada imediatamente.(default false).

Exemplo funcionando no JSFiddle
Referência
Comment: Valeu, agora entendi.
Comment: O que faz o `false, true` que você passou como parâmetro? Eu havia pensado em um stop no fadeIn pois ele só teria efeito caso já houvesse um fadeOut em andamento.
Comment: @Paulo, me diga uma coisa, nesse caso qual a diferença em si. E pelo que pude perceber no fadeOut não funcionou
Comment: E o que melhor funcionou  foi $('#ajaxLoadAni').stop( true, true ).fadeIn('slow');
Comment: editei a resposta te explicando @bfavaretto
Comment: beleza @MarceloDiniz valeu pela dica, notei isso também, mudei ali a resposta ;)
Comment: Outra coisa @MarceloDiniz percebi que utilizando os dois no fadeIn e no fadeOut também fica melhor.
Answer: Questão do OP:
Pelo que percebi, os passos da sua aplicação (num contexto real) são os seguintes:

Utilizador selecciona uma opção no menu
A imagem de loading é activada
É feito um pedido de AJAX
No success callback do AJAX a imagem de loading é desactivada

O seu problema é que, por vezes, o utilizador muda a selecção mais rápidamente do que a animação.
Em termos de experiência do utilizador, tem algumas soluções relativamente simples...

Accelerar a animação. Em vez de "slow" usar "fast" ou especificar os milisegundos directamente (slow é 600ms, fast é 200ms)
Usar show() e hide() em vez de fadeIn e fadeOut. Deixa de ter animação e passa a ser instantâneo.

Outra maneira, um pouco mais complexa seria escutar o evento ajaxStop.
Este evento é disparado quando não existem mais pedidos de AJAX na pilha.
$( document ).ajaxStop(function() {
    ajaxLoadAni('Out');
});

Assim, só quando todos os pedidos de ajax terminarem é que a animação é escondida. Se aliar isto a uma das soluções que apresentei ou à sugestão sugerida pelo Paulo Roberto, a experiência do utilizador melhora.

Problema dos multiplos pedidos:
No entanto, assumindo que a esquematização que fiz dos passos da sua aplicação está correcta, existe um problema maior, que é o número de chamadas AJAX que podem ser disparadas quase em simultâneo.
Por exemplo, se o utilizador utilizar as setas para mudar o select e carregar alternadamente na tecla de cima e na tecla de baixo 25 vezes, terá 25 pedidos de AJAX quase simultâneos, num curtíssimo espaço de tempo. Se o fizer 2500 vezes... imagine.

Solução para o problema dos multiplos pedidos:
A solução mais simples (e mais limpa) seria adicionar um botão que chamasse a função que faz o pedido AJAX, em vez de escutar o "change" event do "select"
$('.ajaxBtn').click(function () {
    //Chamar ajax aqui
});

Também pode desactivar o select enquanto o pedido de ajax não terminou, mas isso pode piorar a experiência do utilizador.
Outra forma, para manter a interface como está, seria colocar uma "flag" que impedisse multiplos AJAX requests de dispararem ao mesmo tempo e só quando o anterior estivesse resolvido é que aceitaria um novo.
 var ajaxFlag = false;
 $("select[name=meuSelect]").change(function(event) {
     event.preventDefault();

     var valor = $(this).val();
     if (ajaxFlag === false) {
         ajaxLoadAni('In');
         ajaxFlag = true;
         //Funcao AJAX
         $.ajax()
            .success(function() //Quando é bem sucessida
            {
                $("#valor").text(valor);
            })
            //.error() //QUando dá erro
            .complete(function() //é sempre chamada
            {
                ajaxLoadAni('Out');
                ajaxFlag = false;
            })
        }
 });

O problema desta solução é que desincroniza o menu select, isto é, se eu mudar rapidamente de opção, ele vai ignorar a segunda opção e mostrar só a primeira, ainda que no menu select esteja selecciona a segunda.
Tem também a opção de dar um delay entre a selecção e o pedido de ajax.
Comment: é quase que isso mesmo que você descreveu. Agora vamos lá: Eu até poderia sim ter colocado "fast" (tanto que na função real minha isso esta como parametro, só deixei o mais limpo possível) mas não deixei pois o interessante já que é uma chamada ajax foi preferível deixar no slow mesmo, e também poderia usar o show e hide, mas da mesma forma foi escolhido ter a animação. E sim, isso pode acontecer de ter as 2500 chamadas, infelizmente, se tiver algo para isso tbm ajuda. E valew mesmo pelos comentários

Como evitar chamadas a função


fnPageChange is not a function

Question: I am getting the subject error when using the following:
 $("#example1").DataTable().fnPageChange(localStorage.getItem('page'),true);

From what I understand, it saves the last page of the datatable that the user clicked on.  If the user has clicked on the 3rd page of the datatable, navigates to another page and then goes back to the datatable, it will still be on the 3rd page of the datatable.
And it works.  The last page of the datatable is saved.
The only problem is, even though the above works, I am getting the following error in the console:
Uncaught TypeError: $(...).DataTable(...).fnPageChange is not a function

I am not sure why.
Here are some other datatable setting I have:
"iDisplayLength": 50,
"order": [[ 1, "desc" ]],
"paging": true,
"scrollY": 300,
"scrollX": true,
"bDestroy": true,
"stateSave": true,
"sPaginationType":"full_numbers",
"autoWidth": false,
"deferRender": true,
"dom": 'Bfrtip',

Why am I getting the above console error and how can I fix it?
Answer: Your use of the "stateSave": true option is what is allowing a user to return to page 3 of the DataTable, after leaving the web page entirely, and then returning.
It also saves filters and sorting selections.
If you want to do something manually, which is not handled for you by "stateSave": true, then you can use the DataTables page change event. The documentation gives an example:
$('#example').on( 'page.dt', function () {
    var info = table.page.info();
    $('#pageInfo').html( 'Showing page: '+info.page+' of '+info.pages );
} );

Otherwise, you can delete that line which is throwing the error - and state saving should not be affected.

Regarding fnPageChange - this is an old plug-in which has been removed from DataTables - you can see a note about this here.
Comment: That's great to know that fnPageChange is no longer being used.  Wish I would've known that earlier.  In regards to the code you suggested, I was unsuccessful getting it to work.  I placed both within the datatable scope as well as outside of the scope.
Comment: Not sure what you mean by the code I suggested. You are already using ` "stateSave": true` - and that is all you should need. Did I misunderstand your comment?
Comment: I was referring to the sample code you provided from https://datatables.net/reference/event/page - side note: the "stateSave" feature does not save the last page for me.
Comment: OK, understood.  You would have to show us exactly how you used that code, and what the specific error message was. For example, the code from the web site assumes your table variable is `example` - whereas in your question, it looks like you are using `example1` instead. That may be why your usage failed - or it may be for some other reason.
Comment: Regarding your note about state saving not working - I cannot explain that! Can you provide a [mre] - maybe in a Fiddle, or similar? That is curious.
Comment: Before I try to create a fiddle, is stateSave supposed to save the most recent page of the datatable?  If so, then maybe something I am doing is preventing stateSave from working.
Comment: Yes - [it is](https://datatables.net/reference/option/stateSave) (it stores the pagination position). You can see saved state in your browser dev tools. For FireFox, hit F12, then go to Storage > Local Storage. It's probably similar for other browsers. Doing this is a good way to identify the auto-generated names DataTables uses for storing its state. The key will be something like `DataTables_data_table_blah...` and the value will be a JSON object containing all the table's saved state. There is no value called `page`, by the way.
Answer:
DataTable começa com minúsculo é um  camel case.
 $("#example1").DataTable().fnPageChange(localStorage.getItem('page'),true);

change to
$("#example1").dataTable().fnPageChange(localStorage.getItem('page'),true);

fnPageChange is not a function


Persistent iptables with Docker: rules get restored multiple times when using if-pre-up.d

Question: Additional Context (may be skipped)
I'm trying to set up psad on my system, which requires to add a rule to the iptables iptables -A INPUT -j LOG. Of course, this rule will get flushed upon reboot, so i looked into ways of making it persistent (of which there are many).
While the iptables-persistent package seems to be the most convenient solution, I cannot use it, as it clashes with the docker daemon running on the system, as iptables-persistent just runs iptables-restore < /etc/iptables/rules.v4 without the -n flag, which may destroy any changes to iptables from the docker-daemon.
Actual Question
So I didn't want to disable the automatic iptable rules from the docker daemon entirely, as it just creates a huge maintenance hassle, so I just added a script
#!/bin/bash
iptables-restore -n < /etc/network/iptables.rules

to /etc/network/if-pre-up.d with chmod +x and saved the configuration without the docker rules with iptables-save > /etc/network/iptables.rules.
The file iptables.rules then just says
-P INPUT ACCEPT
-P FORWARD DROP
-P OUTPUT ACCEPT
-A INPUT -j LOG

But when I reboot the system, i see the rule -A INPUT -j LOG three times. My current guess is that this may be because /etc/network/firewall gets executed multiple times (because there are multiple interfaces??).
How do I resolve this issue? Note that rc.local is deprecated and not meant for this purpose as it is not run when the iptables service is restarted.
Answer: In the end I just created a systemd service that runs the script once and removed it from if-pre-up.d


Confidence interval for a folded normal distribution

Question: (My background: physicist rusty on statistics, evaluating an experimental dataset).
I'm studying a dataset with a random variable $X$, which is approximately normally distributed with standard deviation $\sigma$. I compute the sample average $Y =\sum \frac{X_i}{N}$ and standard error in the mean $\sigma_Y = \frac{\sigma}{\sqrt{N}}$, where $N$ is the number of experiments.
The final step I need to do is to calculate the absolute value $Z = |Y|$ and evaluate the expectation value of $Z$, as well as confidence intervals. I need to consider a general case, since some error bars will be asymmetric ($Y \approx 0$), while others will be symmetric ($Y \gg 0$).
Ideally, I'd like to understand what the confidence intervals should look like, so I don't need to keep sorting the dataset for every data point. Could someone give me some pointers? Thanks a lot!
Comment: What is the mean of $X$? Is it a general unknown $\mu$? Also $Y = X/N$ being a sample average makes no sense. Do you mean $Y = \sum X_i /N$?
Answer: The following method will only work if the mean of $X$ is not 0.
You have have $X \approx N(\mu, \sigma^2)$. Then by the central limit theorem, for the sample average $Y = \sum_{i=1}^{N} X_i/N$,
$$ \sqrt{N} (Y - \mu) \overset{d}{\to} N(0, \sigma^2)\,.$$
However, you are interested in $Z = |Y|$. Define a function $g(x) = |x|$. Then $g$ is continuous everywhere  and differentiable everywhere except 0. If $\mu \ne 0$, then the Delta Method applies. That is
$$\sqrt{N} (g(Y) - g(\mu)) \overset{d}{\to} N(0, \sigma^2 g'(\mu)^2)\, $$
where
$$g'(\mu)^2  = \left(\dfrac{dg(x)}{dx} \Big|_{x = \mu} \right)^2 =  \left(\dfrac{\mu}{|\mu|} \right)^2 = 1\,.$$
So we have,
$$\sqrt{N} (Z - |\mu|)  \overset{d}{\to} N\left(0, \sigma^2 \right)\,.$$
So if $\mu \ne 0$, confidence interval for $|\mu|$ can be created using the above distribution.
Comment: @malina Yes it would. It is not ideal, and this is a drawback of large sample confidence intervals for parameters on a restricted space.
Comment: Thanks for the answer, but I'm a bit confused about one aspect. If $\sigma$ is sufficiently large, and $\mu$ sufficiently small, then it seems the confidence interval for $Z$ would include negative numbers, which it shouldn't?
Comment: Do you know if there are other well-defined ways for constructing confidence intervals which ensure the answer is always within the restricted space?
Comment: @malina Bootstrap confidence intervals most likely. But more than that, I am not so sure.


Cannot run drush rsync - PHP Fatal error in sitealias.inc

Question: drush rsync @ dev @stage

PHP Fatal error:  Unsupported operand types in
  /usr/local/share/drush/includes/sitealias.inc on line 1468

Drush command terminated abnormally due to an unrecoverable
Error:

Unsupported operand types in
  /usr/local/share/drush/includes/sitealias.inc, line 1468
Comment: Where have you defined your site aliases? In sitealias.inc? Do the basic `drush status` and `drush rq` commands work?
Comment: I assume the space between @ dev is a typo here only?
Comment: Trying to use 'rsync' to sync file system of dev site to stage site. Getting PHP fatal error. sitealias.inc. When installed on Rackspace server attempting 'drush rsnc' or 'drush sql-sync' breaks drush. Tried installing with pear, composer and just uploading a drush.zip file from github.None seem to work. Drush 188.8.131.52 acts all wonky and spazzes out. Even initialized a CLEAN Apache/Linux server...nothing works, including "How to make drush work on ANY server: https://www.drupal.org/node/2132447
Comment: Thanks Ryan, yes, just a typo. Been beating this one up for a week...
Comment: Sorry, Patrick. ;)
Comment: Run again with --debug and show output.  Show output of `drush sa @dev`, `drush sa @stage`, `drush @dev status`, and `drush @stage status`.
Comment: I defined three aliases and put them in etc/drush:
Comment: devyau.alias.drushrc.php, stageyau.alias.drushrc.php, and prodyau.alias.drushrc.php
Comment: drush status and drush rq both work - now that I corrected some errors in my alias files. Now drush DOESN'T break, and drush rsync (at)devyau (at)stageyau works.
Comment: However drush sql-sync (at)devyau (at)stageyau fails with this message: Starting to dump database on Source. Unable to load class Drupal\Driver\Database\\Drush [error]PHP Fatal error:  Call to a member function dump() on a non-object in root/.composer/vendor/drush/drush/commands/sql/sql.drush.inc on line 275Drush command terminated abnormally due to an unrecoverable error.Error: Call to a member function dump() on a non-object in /root/.composer/vendor/drush/drush/commands/sql/sql.drush.inc, line 275
Comment: drush sa @devayu gives: $aliases["devyau"] = array (
  'uri' => 'dev.youngamericansunited.org',
  'root' => '/var/www/vhosts/dev.youngamericansunited.org/',
);
Comment: drush sa @stageyau gives: $aliases["stageyau"] = array (
  'uri' => 'stage.youngamericansunited.org',
  'root' => '/var/www/vhosts/stage.youngamericansunited.org',
);
Comment: OH: drush @devyau status gives: Unable to load class Drupal\Driver\Database\\Drush
PHP Fatal error:  Call to a member function db_spec() on a non-object in /root/.composer/vendor/drush/drush/includes/environment.inc on line 370
Drush command terminated abnormally due to an unrecoverable error.
Error: Call to a member function db_spec() on a non-object in /root/.composer/vendor/drush/drush/includes/environment.inc, line 370
[root@web01-new dev.youngamericansunited.org]#
Comment: and drush @stageyau status does the same: [root@web01-new dev.youngamericansunited.org]# drush (at)stageyau status
Unable to load class Drupal\Driver\Database\\Drush  PHP Fatal error:  Call to a member function db_spec() on a non-object in/root/.composer/vendor/drush/drush/includes/environment.inc on line 370Drush command terminated abnormally due to an unrecoverable error                                      [error] Error: Call to a member function db_spec() on a non-object in /root/.composer/vendor/drush/drush/includes/environment.inc, line 370
[root@web01-new dev.youngamericansunited.org]#
Answer: Found an error in my alias files. I had a space between SQL username and password.
<code>$aliases['devyau'] = array(
  'uri'=> 'dev.[sitename]',
  'root'=> '/var/www/vhosts/dev.[sitename]/',
  'db-url' => 'mysql://[username]: [password]/devDBname',
);
</code>


How to build a method that counts how large a group is in an array?

Question: I'm curious on how to build an array (in Java) that tallies how large a group is (consecutive elements with the same value) and prints it through a seperate runner file. So far, this is my code. I've got everything down except for the getNumGroupsOfSize method, which does the counting:

import static java.lang.System.*;
import java.util.Arrays;
import java.util.Scanner;

public class ArrayStats
{
    int[] numArray;

    public ArrayStats(int[]array)
    {
        setArray(int[]array);
    }

    public void setArray(int[]array)
    {
        numArray=array;
    }

    public int getNumGroupsOfSize(int size)
    {
        int cnt=0;
        for (int x=0; x<=size.length; x++)
        {
            do
            {
                count++;
            }
            while (size[x]=size[x+1]);
      return cnt;
     }
    }

    public String toString()
    {
        return ""+Arrays.toString(array);
    }
}
Comment: int cnt is always 0? Why you return always 0
Answer: You could use the build in functionality for counting groups.
Example from another question here.
https://stackoverflow.com/a/25441208/2710666


355/113 and small odd cubes

Question: An important approximation to $\pi$ is given by the convergent $\frac{355}{113}$.
The numerator and the denominator of this fraction are at the same distance of small consecutive odd cubes.
$$\frac{355}{113} = \frac{7^3+12}{5^3-12}$$

Is this a consequence of some general formula, such as a series or continued
fraction?

Attempts, drafts
$$\frac{113}{355} = \frac{1}{10}\left(2+\frac{5^3}{3+\frac{7^3}{4}}\right)-\frac{8}{355} = \frac{1}{5}\left(3-\frac{5^3}{3+\frac{7^3}{4}}\right)$$
Similarly, for $\frac{22}{7}$
$$\frac{7}{22} =\frac{1}{2}\left(\frac{3^3}{1+\frac{4^3}{2}}\right) -\frac{1}{11}$$
For the first convergent $3$,
$$\frac{3^3-6}{1^3+6}=\frac{21}{7}=3$$
The tentative expression
$$a(n)=\frac{(4n+3)^3+6(3n-1)}{(4n+1)^3-6(3n-1)}$$
has $a(0)=3$ and $a(1)=\frac{355}{113}$ but $\lim_{n \to \infty} a(n) = 1 \neq \pi$
A similar fraction for the approximation $\frac{223}{71}$ (Archimedes' lower bound) is
$$\frac{98+5^3}{98-3^3}=\frac{2·7^2+5^3}{2·7^2-3^3}=\frac{223}{71}=3+\frac{1}{7+\frac{1}{10}}$$
Comment: Not sure how to reach $\frac{22}{7}$, but $\frac{25-3}{4+3}$ would suggest squares instead of cubes. From cubes, $\frac{22}{7}=\frac{3^3-5}{2^3-1}$, not that nice.
Comment: I've found a couple via the convergents of $\sqrt[3]\pi$: $$\frac{517^3+13607}{353^3-13607} = \frac{22}{7}$$ and $$\frac{41^3+10}{28^3-10} = \frac{333}{106}$$
Comment: If so would $22/7$ be expressible that way also, being an earlier convergent to the (simple) continued fraction for $\pi$ ?
Comment: When a partial quotient is 1, we get convergents that are neighbours in a [Farey sequence](https://en.wikipedia.org/wiki/Farey_sequence#Farey_neighbours_and_continued_fractions) eg, $22/7, 355/113, 333/106$, with $355 = 22 + 333$ and $113 = 7 + 106$. That can give us linear patterns, but of course it doesn't explain squares & cubes.
Comment: I solved for $x$ in $(u^3+x)/(v^3-x) = p/q$, where $p/q$ is a $\pi$ convergent & $u/v$ is a $\sqrt[3]\pi$ convergent. I just did a brute-force search, looking for combinations that result in an integer value for $x$.
Comment: Jaume-- Good one using squares! [I was trying that but fouled it up.]
Comment: We have $\frac{4^3 + 2}{3^3 - 6}$, still different.
Comment: FWIW, here's a little live Sage / [Python script](https://sagecell.sagemath.org/?z=eJwli0EKAjEMAO99RdhTAyKy3gr6FVlrIkFM15h6Kf271Z3rzGSGE-SiLlrpdmFbskvRuAqG1UQ9ZsbAxUB24CAKpPVJtjgNsx_nh-xO6u-ImAIMto2nJmnuCdrIXrW4jCgKpmOH5n3CfysMAmeYD9v642q0PL4RFi83⟨=sage) to show partial quotients & convergents of $\pi$.
Comment: Maybe, @Crostul. However, this one is quite simple, $\frac{(n+1)^3+2n}{(n-1)^3-2n}$ for $n=6$. The other examples above are more complex.
Comment: $$3=\frac{2^3+4}{2^3-4}$$
Comment: Did you try diff/sum as well?
Comment: @coffeemath If it comes from a continued fraction, I think that fraction may also truncate to $\frac{22}{7}$, but not necessarily.
Comment: Maybe this has nothing to deal with $\pi$? Maybe such a representation exists for any rational number, independently on convergent and other stuff?
Answer: For a coprime pair of integers $1 \le p,q$, consider the following diophantine equation:
$$\frac{x^3+z}{y^3-z}= \frac{p}{q}$$
with $x,y,z$ integer unknowns. This is equivalent to
$$z= \frac{y^3p-x^3q}{p+q}$$
Thus a solution exists if and only if there exist $x,y$ such that
$$y^3p-x^3q \equiv 0 \pmod{(p+q)}$$
Now, note that $-q \equiv p$, and that it has an inverse $\mod (p+q)$. This means that we need
$$x^3+y^3 \equiv 0 \pmod{(p+q)}$$
Now, if we pick $p=355$ and $q=113$, we get
$$p+q=468 = 7^3+5^3$$
In other words, the fraction $355/113$ has such a special property not because it is a convergent of $\pi$, but simply because the sum of numerator and denominator is a sum of two small cubes. We can do the same job with the fraction
$$\frac{203}{265} = \frac{5^3+78}{7^3-78}$$
nothing special with $\pi$.
As for $22/7$ we can find $$\frac{22}{7} = \frac{17^3+5^3}{12^3-5^3}$$
which is even more surprising. In my opinion, having three variables gives you a lot of freedom, so that yo can find such nice forms for any rational number.
EDIT: Just for fun, I looked up convergents of a completely different constant, namely $\gamma$: Euler-Mascheroni constant. One of its convergents is
$$\frac{71}{123}= \frac{3^3+470}{11^3-470}$$ Again, there is nothing special about this rational, simply you can find such a form for any number.
Comment: Here's a [script](https://sagecell.sagemath.org/?z=eJyFUslOwzAQvfcrBilRbOK2qD0gVRhxQuLEB5SmcolDo2Zr7JgmiH9n7C4JCKm-eDzLmzfPc2DQAgcjahIcWBvQ0VNaaFmLdz2KZQJrUvHZjMGe3zMQjS7XTRULLfmzyJSkixHgyRGhghD27qW25SfZ6jwjgWcjfuwF4ENOqQsLdKkyM3KdlzE5RPOwjeYMwy5aNhrjy5V7JGUNDQMDaQHi2Moe5-Lwgjw_ZE0ayi62oZesNIEGOIe7vtAVQ8ghH2aZf7LMMevi67AfMdH8toIxNHjvKUynAxyhlKw1YArccOiG-GKjSEfhAfK0IJY7jWa_u-HQE1FVsogJ6ZibD8U66zFRZa3JTrY8E_kmFqAXDlMv71YnTa1Qp0KrFRb1DRJLHSnj_yCLqRsDh-h6pYSd7shyyLuDx7-yKEysA897S3BBvvzYofrx99EcW9Nzn23nFMjI2KtHlbgzVxHHPWJ4FbFfNnWWrKpxg0nwugvoDyypsQw=⟨=sage) using your method.
Comment: Some p, q combinations generate a lot of solutions, so my script only prints solutions with $|z|<\min(x, y)^2$, sorted (ascending) on $|z|$.
Comment: Great. A graphic for that beautiful $\frac{22}{7}$ would have the same symmetry as the one in the question if  $12$ was odd, or the four cubes even. Maybe your answer generalizes the question to how to build a continued fraction for a constant, that includes a particular approximation.
Comment: For $\gamma$, $3$ and $11$ would allow for two matching near-cubes, but $470=2·5·47$ has a factor too big for $3$ and $11$. The symmetry of the $\frac{355}{113}$ picture is due to the small factors in $12=2·2·3$.
Comment: Very interesting, thank you! I got no solution for $\frac{25}{8}$ (a semiconvergent for $\pi$). Are there rationals that do not accept such a form or some issue in the implementation?

355/113 and small odd cubes


Prove $\tanh x=\frac{\sinh(2x)}{1+\cosh(2x)}$

Question: Question

Prove $\tanh x=\frac{\sinh(2x)}{1+\cosh(2x)}$

My work:
$$\frac{\frac{e^{2x}-e^{-2x}}{2}}{1+\frac{e^{2x}+e^{-2x}}{2}}$$
Simplifies down to $$\frac{e^{2x}-1}{e^{2x}+1}$$
But then I do not know what to do from there
Comment: Are you aware of the identity $\tan\frac{t}{2}=\frac{\sin t}{1+\cos t}$? If so, just replace $t$ with $2ix$ and profit :D
Comment: It is not sin/cos/tan, but sinh/cosh/tanh @JackD'Aurizio
Comment: @YujieZha: they are called hyperbolic trigonometric functions also because $\cos(ix)=\cosh(x)$ and $\sin(ix)=i\sinh(x)$.
Comment: It is one of the classical forms for $\tanh x$!
Comment: @JackD'Aurizio Ah, thanks. Yea, I know they are hyperbolic, but I did not see you later part of the comment (the 2ix part, was reading from a phone) nice comment!
Answer: Dividing numerator and denominator by $e^x$ gives
$$ \frac{e^{2x}-1}{e^{2x}+1} \frac{e^{-x}}{e^{-x}} = \frac{e^x-e^{-x}}{e^{x}+e^{-x}} = \frac{e^x-e^{-x}}{2}\frac{2}{e^{x}+e^{-x}} = \frac{\sinh{x}}{\cosh{x}}=\tanh{x}. $$


Johansen test for cointegration - how to find model given test output?

Question: Suppose we are working with three I(1) variables and that the result below is the Johansen cointegration test:
Unrestricted Cointegration Rank Test (Trace)

Hypothesized No. of CE(s)
Eigenvalue
Trace statistic
0.05 critical value
Prob.**

None*
0.394297
59.23088
42.91525
0.0006

At most 1*
0.203773
20.12442
25.87211
0.2197

At most 2*
0.029684
2.350447
12.51798
0.9432
Answer:
a) According to this test, how many cointegration vectors are significant? Which model should we use? Explain your answer.
According to the test results, we reject the null of no cointegration vectors in favor of the alternative of at least one vector.  However, we do not reject either At most 1* or At most 2*, implying that the correct number of cointegration vectors to use is 1.
How can I decide which model using only this information? Does "model" mean using a trend, trend+constant, etc ?
b) What would the equations of this model be?
I have the same doubt; how would I model the equations based only on the test results?
Thanks a lot!
Answer: a) According to this test, how many cointegration vectors are significant? Which model should we use? Explain your answer.
The Johansen rank test can be read as follows:
First line with NONE means, we are testing, if there are NONE or 0 cointegration relationships in the tested Vector Error Correction Model, known as VECM or sometimes only VEC. As you can see the first line is significant 0.0006 thus, we are rejecting H0, or in other words we are rejecting the hypothesis that there exists a conintegration relationship.
If we can reject the H0, you have to go to the next line with At most 1*. Then you do the test again, can we reject the H0? Now you have the hope that we have at least one relationship. If we unfortunately have to reject H0, you would go to the next line with  At most 2*, to check if we have then 2 cointegration relationships and so on. You read the Johansen-test line by line,

until you hit a higher 0.05 critical value (25.87211) than Trace statistic (20.12442) that means you know the rank of your cointegration relationships in your VECM / Model, in your terms at least a rank of 1 although you are also able to use 2, but normally you would stop at the first H0 which is accepted (I use higher ranks only for genetic algorithm parameters if possible), because you already know everything a rank below is already true.

OR you don't hit a higher critical value than the trace statistic, which would mean you would never cross the critical value, so you never accept H0 or in other terms that there is a cointegration relationship. In line 1 you can not reject H0 thus, you are accepting H0 which means, there is a cointegration relationship.

How can I decide which model using only this information? Does "model" mean using a trend, trend+constant, etc ?
To choose your model, you do something like a competition. You would calculate a VECM with trend, both or only constant and choose the one with a better AIC. This here is a source from the Vilnius University (Lithuania) (slide 61) http://web.vu.lt/mif/a.buteikis/wp-content/uploads/2020/05/Lecture_06.pdf that shows 5 competing cases of VECM with a certain amount of cointegration relationships.
b) What would the equations of this model be?
The model equation itself, is not so problematic. It is just a VAR with an error correction term that show us, when the time series gets back to its original state.
I'm not sure if you understand the fundamental part here, so let me help you, why a time series with cointegration relationships is not problematic. If a time series is stationary we measure a VAR in levels (no transformation just Vector Autoregressive Model).
If variables are not stationary, we check for cointegration relationships, that means variables have a unit root root (time series is not predictable) but if we increase lag and look more into the future they get back to their original state, in other terms, a shock to a time series does not harm its pathway in the long run, or in other words, it tends back to its level and is predictable (VECM your case)
If we have also no cointegration relationships, then we would transform the variables (log, differencing) to measure a VAR in differences.
THUS a VECM is nothing else than a simple VAR with just a factor that "corrects" the VAR/feature to show when the variable/s get back to its original state: YOu can also see that in the slides i linked for you on slide: 66.
Excerpt:
> ---------------------ECT---- Intercept-------Y1-1-------Y2-1---
>
> Equation Y1 -0.6509582 1.767273 -0.06022577 0.1081974
>
> Equation Y2 0.6502533 -1.276647 -0.05833625 0.1501910
>
> ∆Y1,t = 1.767 − 0.65 · (Y1,t−1 − 1.88Y2,t−1 + 0.0371 · (t − 1))
>
> ∆Y2,t = −1.277 + 0.65 · (Y2,t−1 − 1.88Y2,t−1 + 0.0371 · (t − 1))
>
> Coefficient (α =) ECT = 0.65 is called an adjustment coefficient. It
> indicates that Y2 will return to equilibrium in 1/0.65 ∼ 2 steps,
> ceteris paribus

Thus all you have to do is take your lag, you have it already for the johansen test, write your formula of several equations from the VAR (just like in the sample) but instead of writing the ECT (which you dont know) set it to a variable/parameter. which has yet to be determined by the VECM. In this way you can show, that you know a VECM is nothing else than a VAR but it will be corrected THROUGH an ERROR CORRECTION TERM. And you have your final model/equation.
How does the ECT relates to the rank of the cointegration relationship matrix?
Amount of ranks r = amount of ECTs in the model. 1 Rank = 1 ECT.
If you have any further questions do not hesitate to ask me.
Further resource for VECM and Johansen in R:
https://www.r-econometrics.com/timeseries/vecintro/


Android sqlite:could not execute method onclick

Question: I'm trying to login using the database by using the id of the specific members.
But the app crashes with log error.
Following various other similar errors, I included "c1.movetoFirst();" and "c2.movetoFirst();". But still its not working.
The logcat error is:
FATAL EXCEPTION: main
Process: no.nordicsemi.android.nrftoolbox, PID: 13196
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
 at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19888)
 at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5276)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:911)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
 Caused by: java.lang.reflect.InvocationTargetException
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:432)
at android.database.AbstractWindowedCursor.checkPosition
at android.database.AbstractWindowedCursor.getInt
at no.nordicsemi.android.nrftoolbox.LoginActivity.login

The LoginActivity is :
public class LoginActivity extends AppCompatActivity {

    TextView email;
    TextView pass;

    private no.nordicsemi.android.nrftoolbox.myDbAdapter mydb;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        email = (TextView) findViewById(R.id.editText_mail);
        pass = (TextView) findViewById(R.id.editText_pass);
        mydb = new no.nordicsemi.android.nrftoolbox.myDbAdapter(this);

    }

    public void register(View v) {
        Intent goToSecond = new Intent();
        goToSecond.setClass(this, Register_Page.class);
        startActivity(goToSecond);
    }

    public void login(View v) {

        Cursor c1 = mydb.getEmail(email);
        c1.moveToFirst();
        Cursor c2 = mydb.getpass(pass);
        c2.moveToFirst();
        int id1=c1.getInt(0);
        int id2=c2.getInt(0);

        if (id1>0 & id2>0) {
            Intent goToSecond = new Intent();
            goToSecond.setClass(this, Profile.class);
            startActivity(goToSecond);
        } else
            message(getApplicationContext(), "not valid user");
    }
}

The myDbHelper is:
public class myDbAdapter extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 4;
    public static final String DATABASE_NAME = "MyDBName.db";
    public static final String CONTACTS_TABLE_NAME = "contacts";
    public static final String CONTACTS_COLUMN_ID = "id";
    public static final String CONTACTS_COLUMN_NAME = "name";
    public static final String CONTACTS_COLUMN_EMAIL = "email";
    public static final String CONTACTS_COLUMN_PASS = "password";
    public static final String CONTACTS_COLUMN_DOB = "dateofbirth";
    public static final String CONTACTS_COLUMN_GENDER = "gender";
    public static final String CONTACTS_COLUMN_PHONE="phone";
    public static final String CONTACTS_COLUMN_CITY="city";
    public static final String CONTACTS_COLUMN_WALLET="wallet";
    private HashMap hp;

    public myDbAdapter(Context context) {
        super(context, DATABASE_NAME , null, 4);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(
                "CREATE TABLE " + CONTACTS_TABLE_NAME + "(" + CONTACTS_COLUMN_ID + " INTEGER PRIMARY KEY," + CONTACTS_COLUMN_NAME + " TEXT," + CONTACTS_COLUMN_EMAIL + " TEXT," + CONTACTS_COLUMN_PASS +" TEXT," + CONTACTS_COLUMN_DOB + " TEXT," + CONTACTS_COLUMN_GENDER + " TEXT," + CONTACTS_COLUMN_PHONE + " INTEGER," + CONTACTS_COLUMN_CITY + " TEXT,"+CONTACTS_COLUMN_WALLET + " INTEGER DEFAULT 0);"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    }

    public boolean insertContact (String name, String email, String pass, String dob, String gender, String phone, String city) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);
        contentValues.put("email", email);
        contentValues.put("password", pass);
        contentValues.put("dateofbirth", dob);
        contentValues.put("gender", gender);
        contentValues.put("phone", phone);
        contentValues.put("city", city);
        db.insert("contacts", null, contentValues);
        return true;
    }
    //Cursor csr = no.nordicsemi.android.nrftoolbox.CommonSQLiteUtilities.getAllRowsFromTable(db,"contacts",true,null)
    //no.nordicsemi.android.nrftoolbox.CommonSQLiteUtilities.LogCursorData(csr);
        public int updateWallet(String amount,Integer id)
    {
        SQLiteDatabase db=this.getWritableDatabase();

        ContentValues contentValues=new ContentValues();
        contentValues.put("wallet",amount);
        return(db.update("contacts",contentValues,"id = ? ",new String[] { Integer.toString(id)}));

    }

    public Cursor getData(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from contacts where id="+id+"", null );

        return res;
    }

    public Cursor getEmail(TextView email)
    {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor= db.rawQuery( "select id from contacts where email='"+email.getText().toString()+"'",null);
        return cursor;
    }
    public Cursor getpass(TextView pass)
    {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor= db.rawQuery( "select id from contacts where password='"+pass.getText().toString()+"'",null);
        return cursor;
    }
}

Where is the error? And how can it be recitified?
Comment: where are you setting the `click` method ?
Comment: your cursor is empty that's why you're getting indexoutofboundsexpception. check your rawQuery
Comment: I have set "login" method as the onClick of Login button. @Panther
Comment: share your dbhelper class fully in order we could help you
Comment: Shared it !@Bek
Comment: check your database whether something was inserted. You could check it with "db browser for sqlite" program
Answer: You better check whether cursor has next before invoking movetoFirst as in
 Cursor c1 = mydb.getEmail(email);
  if(c1.getcount() > 0)
        c1.moveToFirst();

and make sure, email id is already in database and check for case sensitive.
Comment: It worked. There was problem with the case sensitivity.Thanks a lot.@rajan ks


Error message with Pearson's chi-squared test

Question: <code> > dput(t)
 structure(c(125L, 25L, 28L, 8L, 0L, 68L, 13L, 9L, 10L, 0L), .Dim = c(5L,
 2L), .Dimnames = list(c("Married", "Widowed", "Divorced", "Never married",
 "Other"), c("control", "case")))
 > t
               control case
 Married           125   68
 Widowed            25   13
 Divorced           28    9
 Never married       8   10
 Other               0    0
 > chisq.test(t)
    Pearson's Chi-squared test

 data:  t
 X-squared = NaN, df = 4, p-value = NA

 Warning messages:
 1: In chisq.test(t, simulate.p.value = TRUE) :
   cannot compute simulated p-value with zero marginals
 2: In chisq.test(t, simulate.p.value = TRUE) :
   Chi-squared approximation may be incorrect
</code>
I am trying to see whether marital status affects a person's disease status. However, when I run the Pearson test, I get the above errors. Is this happening because I only have 2 categories for the disease status (i.e: control or case)? What is another appropriate test that I can use instead?
Comment: This is a statistical question masquerading as an r question.
Comment: Pearson (here Karl Pearson) deserves upper case P.
Answer: This is not specific to R and in fact you are being told what is wrong. To spell it out, two of the terms in the chi-square statistic,
$\Sigma (\text{observed} - \text{expected})^2 / \text{expected}$
reduce to $(0 - 0)^2/0$, as the total of a row or column (depending on how the frequencies are displayed) is $0$. That is what is meant by "zero marginal". You could see this for yourself by doing the chi-square test by hand, but regardless of that the R function won't sum (or ignore) indeterminate terms with zero divisor.
Having two categories for disease status is irrelevant to that outcome, except that you need at least two categories to apply the test at all.
The easiest solution is to omit the corresponding category. I'd counsel flagging that you did so in any formal report. There are various obvious consequences: if other researchers had a populated "other" category, then what you are doing is necessarily not quite the same as what they did. Presumably "other"s are possible in principle, just not present in your sample. (In this case, I can't readily imagine what that other would be, but perhaps it is there for people writing in something else or declining to give an answer.)
Comment: One crude method would shrink the frequencies inwards and so replace sampling zeros with positive frequencies. A kind of sensitivity analysis might replace either zero with 1 to see what difference it makes.
Comment: I've recently had similar problems with all-zero variables that in principle could have taken non-zero values. Is there a more general sense of how to proceed? Is there a Bayesian approach?
Comment: @ssdecontrol There is always a Bayesian approach. In fact, there are always lots of Bayesian approaches. Aren't you taking courses with Andrew Gelman?
Comment: it's more a matter of "is there a principled Bayesian approach that someone smarter than me has already put time and effort into developing." Yes, I took a course with him last semester but it was a "soft" one. And I had him in mind when I wrote that comment; I was thinking maybe there was some kind of smooth "partial variable omission" that could be achieved in some kind of multilevel model. The only thing I can think of doing is an imputation, but that would only make sense if I have a very strong theoretical sense of the distribution of the rare-but-not-always-zero variable.


How to take automatic backup of latest code or latest version of Project from TFS to local machine

Question: I am suffering with difficult problem in my project. My question is that, Is it possible to take automatic backup of latest code or latest version of entire project solution from TFS in visual studio 2012.
my need is first take automatic backup of latest version of code & after that mapped it in to another directory/folder. i want to do that with batch process but i  didn't know how to make  batch file for take automatic backup/copy of one folder and mapped it into another folder
Comment: Why would you want to do that? Can you describe what kind of problems you're trying to prevent?
Comment: I just want to get latest version of my project/ solution  or code on my local machine without Regular action like right click on solution-->get latest etc
Answer: I don't really understand the reasoning behind your request, but it's quite simple to create a Batch script that will create a temporary mapping and then downloads all the files from TFS. You could also look into git tf, if having local undo is the feature that you're after.
See: https://stackoverflow.com/a/10524175/736079


How do I implement email dispatch with Drupal Symfony Mailer from scratch?

Question: I'm implementing a cron job that should send a notification email to all users that meet a certain criterion.
I created a Service implementing the CronInterface and hook_cron calls this service's run() method.
This queries for the users that need notification.
I want to loop over these user and send emails to them.
These emails should contain a default message and they should be greeted with their name.
The system already uses the "Drupal Symfony Mailer".
Everything in the documentation seems to migrate configurations from other implmentations.
I tried implementing a  Plugin extending EmailBuilderBase with:
@EmailBuilder(
  id = "notification",
  sub_types = { "update" = @Translation("Update") },
  common_adjusters = {"email_subject", "email_body"},
)

My expectation was that I will be able to

add a new policy on the configuration page that belongs to this class
provide my notification text, using a token for the user name
send the email via Drupal::service('email_factory')->sendTypedEmail('notification', 'update', $user);

This doesn't work.
I can't create a policy matching my Builder.
The dropdown menus on policy creation don't offer options for "notification" and "update" for the type and sub-type selection.
How do I create the policy that allows me to send my email via the method call above without writing a deprecated version that gets migrated?
Comment: What does "doesn't work" mean, technically?
Comment: I expected the magic comment to create additional options in the dropdown menus for policy creation. I thought, there might appear an option "notification" for the type and an option "update" for the sub-type, at least after (re-)activating the module and rebuilding the cache. This didn't happen and now I'm stuck. Either something is broken or I got the concept wrong. I updated the discription.
Answer: I created a specific type and subtype for a custom module, like this:
In src/Plugin/Emailbuilder create a class MyModuleEmailBuilder extends EmailBuilderBase. Make an annotation there:
/**
 * Email Builder plug-in for the custom_email_example module.
 *
 * @EmailBuilder(
 *   id = "my_module",
 *   sub_types = {
 *     "update" = @Translation("Update"),
 *   },
 *   common_adjusters = {"email_subject", "email_body"},
 * )
 */

Then (re-)install the module.
Hopes this helps!


merging two tables but some rows are missing

Question: I am trying to join two tables in R but I don't get the expected result.
Here are two example data.tables
dt1 <- data.table(s = c(1,1,1,1,1),
                  d = c(1,2,3,1,2),
                  c = c(8,8,8,9,9),
                  v = c(6,6,6,6,6))

dt2 <- data.table(s = c(1,1,1),
                  d = c(1,2,3))

I am trying to get this result
dt3 <- data.table(s = c(1,1,1,1,1,1),
                  d = c(1,2,3,1,2,3),
                  c = c(8,8,8,9,9,9),
                  v = c(6,6,6,6,6,NA))

but using
dt4 <- data.table::merge.data.table(dt2, dt1, by = c("s", "d"), all = TRUE)

but dt4 is missing the last entry 6: 1 3 9 NA
any suggstion?
Comment: `all` values are represented. 1/1, 1/2 and 1/3 of the keys in `dt2`. The 1/3 in `dt2` joined to row 3 of `dt1`. You can see what-joins-to-what if you add row numbers beforehand `dt1[, rn1 := .I]; dt2[, rn2 := .I]; merge(dt2, dt1, by=c("s","d"), all=TRUE)`
Comment: I'm not sure how to get your desired result without substantially changing `dt2` - it seems you need to also join on the `c` column, e.g.: `merge(dt1, data.table(s = c(1,1,1,1,1,1), d=c(1,2,3,1,2,3), c=c(8,8,8,9,9,9)), by=c("s","d","c"), all=TRUE)`
Comment: What is the logic behind your desired result?
Comment: @s_baldur You could think of the following example. "s" subjects in a trial, "d" are the days of the trials subject "s" has attended, "c" is the treatment given to subject "s" on day "d" , and "v" is the outcome of the treatment. For further processing I need "v" to have v = 0 when "s" on "day "d" has not received the treatment "c"
Answer: Here is a two-step solution---which can, of course, be combined into one step.
Step #1:
dt4 <- unique(dt1[,.(s, c)])[dt2, on = .(s), all = TRUE]

and Step #2:
dt5 <- dt1[dt4, on = .(s, d, c)][order(s,c,d)]

resulting in
> dt5
   s d c  v
1: 1 1 8  6
2: 1 2 8  6
3: 1 3 8  6
4: 1 1 9  6
5: 1 2 9  6
6: 1 3 9 NA


Out of memory kill on Centos 6

Question: For the last few days I am having regular out of memory problems on my Centos 6 server.
Aug  1 03:40:42 myserver xinetd[2304]: START: smtp pid=11222 from=22.214.171.124
Aug  1 03:40:46 myserver xinetd[2304]: EXIT: smtp status=1 pid=11222 duration=4(sec)
Aug  1 03:41:08 myserver xinetd[2304]: START: smtp pid=11224 from=184.108.40.206
Aug  1 03:41:19 myserver xinetd[2304]: EXIT: smtp status=0 pid=11224 duration=11(sec)
Aug  1 03:44:40 myserver xinetd[2304]: START: smtp pid=11240 from=126.96.36.199
Aug  1 03:44:40 myserver xinetd[2304]: EXIT: smtp status=0 pid=11240 duration=0(sec)
Aug  1 03:44:41 myserver xinetd[2304]: START: smtp pid=11241 from=126.96.36.199
Aug  1 03:44:41 myserver xinetd[2304]: EXIT: smtp status=0 pid=11241 duration=0(sec)
Aug  1 03:44:41 myserver xinetd[2304]: START: smtp pid=11242 from=22.214.171.124
Aug  1 03:44:41 myserver xinetd[2304]: EXIT: smtp status=0 pid=11242 duration=0(sec)
Aug  1 03:44:51 myserver xinetd[2304]: START: smtp pid=11243 from=184.108.40.206
Aug  1 03:44:56 myserver xinetd[2304]: EXIT: smtp status=1 pid=11243 duration=5(sec)
Aug  1 03:51:36 myserver kernel: postmaster invoked oom-killer: gfp_mask=0x201d2, order=0, oomkilladj=0
Aug  1 03:51:36 myserver kernel:
Aug  1 03:51:36 myserver kernel: Call Trace:
Aug  1 03:51:36 myserver kernel:  [<ffffffff800c10bb>] out_of_memory+0x8e/0x2f5
Aug  1 03:51:36 myserver kernel:  [<ffffffff8000f275>] __alloc_pages+0x245/0x2ce
Aug  1 03:51:36 myserver kernel:  [<ffffffff80012970>] __do_page_cache_readahead+0x95/0x1d9
Aug  1 03:51:36 myserver kernel:  [<ffffffff800638fb>] __wait_on_bit_lock+0x5b/0x66
Aug  1 03:51:36 myserver kernel:  [<ffffffff8003f7d9>] __lock_page+0x5e/0x64
Aug  1 03:51:36 myserver kernel:  [<ffffffff8001330f>] filemap_nopage+0x148/0x322
Aug  1 03:51:36 myserver kernel:  [<ffffffff80008848>] __handle_mm_fault+0x1f8/0xe23
Aug  1 03:51:36 myserver kernel:  [<ffffffff8006686f>] do_page_fault+0x4cb/0x830
Aug  1 03:51:36 myserver kernel:  [<ffffffff8000e123>] free_pages_and_swap_cache+0x73/0x8f
Aug  1 03:51:36 myserver kernel:  [<ffffffff8005dde9>] error_exit+0x0/0x84
Aug  1 03:51:36 myserver kernel:
Aug  1 03:51:36 myserver kernel: Mem-info:
Aug  1 03:51:36 myserver kernel: Node 0 DMA per-cpu:
Aug  1 03:51:36 myserver kernel: cpu 0 hot: high 0, batch 1 used:0
Aug  1 03:51:36 myserver kernel: cpu 0 cold: high 0, batch 1 used:0
Aug  1 03:51:36 myserver kernel: cpu 1 hot: high 0, batch 1 used:0

Another example:
Aug  1 03:55:17 myserver xinetd[2304]: EXIT: smtp status=0 pid=11289 duration=36(sec)
Aug  1 03:55:21 myserver xinetd[2304]: START: smtp pid=11293 from=188.8.131.52
Aug  1 03:59:28 myserver kernel: qmail-remote invoked oom-killer: gfp_mask=0x201d2, order=0, oomkilladj=0
Aug  1 03:59:28 myserver kernel:
Aug  1 03:59:28 myserver kernel: Call Trace:
Aug  1 03:59:28 myserver kernel:  [<ffffffff800c10bb>] out_of_memory+0x8e/0x2f5
Aug  1 03:59:28 myserver kernel:  [<ffffffff8000f275>] __alloc_pages+0x245/0x2ce

The regular server memory use is about 30-40%. The server has been very stable and "trouble-free" for years...What could cause that memory spike? Does it have something to do with xinetd?
Over the last few days I updated clamav, installed Comodo mod_security riules and maldet. I also installed clamd as a new application.
Any suggestions? How can I narrow the problem?
Thanks
Comment: Obviously the problems are due to some of the updates you made, have a look at your clamav settings, you may want to reduce the number of child processes..
Answer: As mentioned in above reply..checking updated package is the first debugging step as based on the log trace we can see kernel is doing it job i.e out of memory function is called when all the system memory is occupied including(RAM+Swap) and system will not resume normal operation till memory is freed.
Other option you have is to configure kdump along with vm.panic_on_oom = 1(/etc/sysctl.conf),this will generate vmcore.You can find more info about it here http://people.redhat.com/anderson/crash_whitepaper/
Comment: Thanks. I have a question: how can updated package affect memory usage if it was not running just before crash? I would understand if the process was added to daily or hourly crontab jobs. I will play with kdump and, probably, disable new packages one-by-one to narrow the problem.

Out of memory kill on Centos 6


Laurent Series Expansion Solution Verification

Question: Write the Laurent Series of
$$ \frac{1}{z(1-z)^2}$$
Now the singularities are $z=0$ and $z=1$.
My attempt:
For $z=0$ case
$$= \frac{1}{z}.(1-z)^{-2}$$
$$=\frac{1}{z}.[1+2z+3z^2+...]$$
For $z=1$ case
$$=\frac{1}{(1-z)^2}.\frac{1}{(1+z-1)}$$
$$=\frac{1}{(1-z)^2}.(1+(z-1))^{-1}$$
$$=\frac{1}{(1-z)^2}.[1+(z-1)+(z-1)^2+(z-1)^3+...]$$
I used the $(1+x)^{-n}$ expansion in the last line.
Am I doing it right? Is there a better approach?
Comment: That's how I would have done it.
Comment: You are assuming that $|z|<1$ in the first case and that $|z-1|<1$ in the second case, which makes your solution incomplete. You need to consider also the domains defined by $|z|>1$ in the first case and that $|z-1|>1$.
Comment: The expansion of $(1+u)^{-1}$ has alternating signs.
Answer: Here's an approach that uses partial fraction decomposition:
\begin{align}
\frac{1}{z(1-z)^2}
&= \frac{1}{z} + \frac{1}{1-z} + \frac{1}{(1-z)^2} \\
&= \frac{1}{z} + \sum_{n \ge 0} z^n + \sum_{n \ge 0} \binom{n+1}{1} z^n \\
&= \frac{1}{z} + \sum_{n \ge 0} (n+2) z^n
\end{align}


Can KL-Divergence ever be greater than 1?

Question: I've been working on building some test statistics based on the KL-Divergence,
\begin{equation}
D_{KL}(p \| q) = \sum_i p(i) \log\left(\frac{p(i)}{q(i)}\right),
\end{equation}
And I ended up with a value of $1.9$ for my distributions. Note that the distributions have support of $140$K levels, so I don't think plotting out the whole distributions would be reasonable here.
What I'm wondering is, is it possible to have a KL-Divergence of greater than 1? A lot of the interpretations I've seen of KL-Divergence are based on an upper bound of 1. If it can go greater than 1, what is the interpretation of KL-Divergence beyond 1?
Edit: I know it's a bad choice of reference, but the Wikipedia article on KL Divergence suggests that "a Kullback–Leibler divergence of 1 indicates that the two distributions behave in such a different manner that the expectation given the first distribution approaches zero." I had thought it was implied that this meant the KL-Divergence was bounded above by 1, but it's apparent that this is a mistake in the article.
Comment: Can you please state, and provide references/links as available, for the interpretations you've seen of KL-Divergence which are based on an upper bound of 1?
Comment: edited to indicate my (poor) reference.
Answer: The Kullback-Leibler divergence is unbounded. Indeed, since there is no lower bound on the $q(i)$'s, there is no upper bound on  the $p(i)/q(i)$'s. For instance, the Kullback-Leibler divergence between a Normal $N(\mu_1,\sigma^2)$ and a Normal $N(\mu_2,\sigma^2)$ with equal variance is
$$\frac{1}{2\sigma^{2}}(\mu_1-\mu_2)^2$$which is clearly unbounded.
Wikipedia [which has been known to be wrong!] indeed states

"...a Kullback–Leibler divergence of 1 indicates that the two
distributions behave in such a different manner that the expectation
given the first distribution approaches zero."

which makes no sense (expectation of which function? why 1 and not 2?)
A more satisfactory explanation from the same
Wikipedia page is that the Kullback–Leibler divergence

"...can be construed as measuring the expected number of extra bits
required to code samples from P using a code optimized for Q rather
than the code optimized for P."
Comment: The KL divergence between two normal distributions does not depend on one of the variances?
Comment: just to add to this - the eqn Xi'an gives is when the second Gaussian a standard normal distribution (variance of 1). Wiki has both forms https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence#Multivariate_normal_distributions
Comment: What exactly do you mean with unbounded? The KL-Divergence bounded from below because it cannot become negative?
Comment: Unbounded: having no upper bound (since the lower bound is zero).


Duplicate changelogs in jenkins pipeline script

Question: I am working on how to use the new Jenkins Pipeline Plugin with the Jenkinsfile in the scm of the project (we use GIT).
The job script is loaded from the SCM ('Pipeline script from SCM' option)
and in the Jenkinsfile script I do a checkout scm.
The problem is that the commits are duplicated. In the build directory, there is 2 changelog.xml with the same commits and so the changes view can be very messy :
Summary

1. FNC71010 - Ajout des traductions au launcher (details)
Commit 5a676ee1448b72f1b99227e8832b01081aa1bc6d by thierry
The file was modified   Deploy_serveur/resources/config/trad.properties

Summary

1.FNC71010 - Ajout des traductions au launcher (details)
Commit 5a676ee1448b72f1b99227e8832b01081aa1bc6d by thierry
The file was modified   Deploy_serveur/resources/config/trad.properties

The problem occurs also with in the multibranch pipeline.
Here is the Jenkinsfile content :

#!groovy

node {
    stage 'initialisation'
    def repertoire = "directory"

    def pipeline
    dir(repertoire) {
        checkout scm
        pipeline = load 'pipeline.groovy'
    }
    pipeline.initialisation(repertoire)
    pipeline.build()
    pipeline.runTestsRapides()
    pipeline.copieResultats()
}

Am I doing something wrong ?
Jenkins version : 1.642.2 (docker)
Pipeline version : 1.15
Git plugin : 2.4.3
Comment: If you look in the console, do you see a git checkout twice?
Comment: Yes, one from the Jenkins job, one from the pipeline script. But it looks like the [method recommended by Jenkins](https://github.com/jenkinsci/workflow-plugin/blob/master/TUTORIAL.md#creating-multibranch-projects)
Answer: Did you try upgrading the Git plugin to 2.4.4?
Comment: (back from a long week-end). I upgraded the Git plugin to 2.4.4 and on the command `checkout scm` does not duplicate the commit anymore.
Comment: Great, then the refix of JENKINS-29326 worked. [changelog](https://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin)


finite dimensional simple algebras are semisimple

Question: Finite dimensional simple algebras are semisimple.
I've found two different answers and got a bit confused. Any clarification would be of great help!
A simple algebra that is not semisimple
https://en.wikipedia.org/wiki/Semisimple_algebra#:~:text=A%20finite%2Ddimensional%20algebra%20is,are%20A%20and%20%7B0%7D.
Thank you
Comment: What's the question? A simple finite dimensional unital algebra over a field is semisimple (indeed a simple Artinian ring is semisimple). An infinite-dimensional simple algebra need not be semisimple.
Comment: Yes! Is it because of the Wedderburn's theorem? $A$ is simple artinian iff $A \cong M_n(D)$ for some division ring. And this means $A$ is semisimple by Wedderburn's theorem?
Comment: What is causing confusion? Finite dimensional simple -> Artinian simple -> semisimple.    Qiaochu's example is an infinite dimensional simple ring.
Answer: It's an unfortunate fact about the terminology that for rings (unlike for, say, modules or Lie algebras) "simple" doesn't imply "semisimple," so let's be clear:

A semisimple ring is a ring which is semisimple as a left module over itself. Other definitions are possible, for example "Artinian and trivial Jacobson radical," or "every short exact sequence of left modules splits," and then one has to do some work to show that they're equivalent.
A simple ring is a ring with no nontrivial two-sided ideal.
Every division ring is simple (exercise). If $R$ is a simple ring, then so is $M_n(R)$ (exercise). So any matrix algebra over a division ring is simple.
Every division ring is semisimple (exercise). If $R$ is a semisimple ring, then so is $M_n(R)$ (exercise). If $R$ and $S$ are semisimple, then so is $R \times S$ (exercise). So any finite product of matrix algebras over division rings is semisimple.
The Artin-Wedderburn theorem asserts the converse: every semisimple ring has the above form.
Every finite-dimensional algebra over a field $k$ is Artinian, hence is semisimple iff it has trivial Jacobson radical. The Jacobson radical is a two-sided ideal, so any simple ring has trivial Jacobson radical, and so any finite-dimensional simple $k$-algebra is semisimple, and more generally a simple ring is semisimple iff it's Artinian iff (by Artin-Wedderburn) it's a matrix algebra over a division ring.
The Weyl algebra, as stated in the first answer you linked to, is a simple ring which is not Artinian, so it's not semisimple.

For a proof that "semisimple" as defined above is equivalent to "Artinian and has trivial Jacobson radical" see this blog post.
Comment: Here's an old math.SE answer where I show that if $R$ is simple then so is $M_n(R)$ and also show that the Weyl algebra is simple: https://math.stackexchange.com/questions/2540758/an-example-of-a-non-commutative-ring-with-multiplicative-identity-1-in-which-the/2540826#2540826


web.config redirect non-www OR non-https to https://www using rules

Question: I need to redirect all non-www or non-https traffic to https://www using rule in web.config
http://domain.com --> https://www.domain.com
http://www.domain.com --> https://www.domain.com
https://domain.com --> https://www.domain.com

I modified rules from Web.config. Redirect all traffic to www.my... Using rules element. but it fails to redirect http://www.domain.com to https://www.domain.com.
    <rewrite>
        <rules>
            <clear />
            <rule name="Redirect to www subdomain">
                <match url=".*" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" negate="true" />
                    <add input="{SERVER_PROTOCOL}" pattern="^(.*)(/.*)?$"/>
                </conditions>
                <action type="Redirect" url="https://www.{HTTP_HOST}/{R:0}" redirectType="Permanent"/>
            </rule>
        </rules>
    </rewrite>

Answer: I found the answer, i think it would help others if i post it here.
    <rewrite>
        <rules>
            <clear />
            <rule name="Redirect non-www OR non-https to https://www">
                <match url=".*" />
                <conditions logicalGrouping="MatchAny">
                    <add input="{HTTP_HOST}" pattern="^domain.com$" />
                    <add input="{HTTPS}" pattern="off" />
                </conditions>
                <action type="Redirect" url="https://www.domain.com/{R:0}" redirectType="Permanent"/>
            </rule>
        </rules>
    </rewrite>

Answer: This will redirect all non www or non https to https://www
<rewrite>
  <rules>
    <rule name="non-www-https to www https" enabled="true" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^[^\.]+\.[^\.]+$" />
        <add input="{HTTPS}" pattern="on" />
        <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
      </conditions>
      <action type="Redirect" url="https://www.{HTTP_HOST}/{R:0}" />
    </rule>

  </rules>

</rewrite>

I added this line to ignore it on IIS express (local host):
<add input="{HTTP_HOST}" pattern="localhost" negate="true" />

The other advantage of this is that you do not need to enter your domain in this rule.
You can read more here:
http://weblogs.asp.net/owscott/redirecting-non-www-to-domain-equivalent


Trying to add two queries together

Question: I'm trying to add one more column that is a count for the amount of rows left,
 I don't want include rows where my planned quantity matches completed quantity
(plan_qty != cmp_qty)
SELECT   od_f.ob_oid Order,
         Sum(plan_qty) Plan_Units,
         sum(cmp_qty) Completed_Units,
         Round(((Sum(cmp_qty)/sum(plan_qty)) * 100.00),2)Percent_Cmp,
         total_value Value,
         SUM(round(cmp_qty * unit_price,2)) cmp_value
FROM     od_f,
         om_f
WHERE    od_f.ob_oid = om_f.ob_oid
GROUP BY od_f.ob_oid, total_value
ORDER BY Percent_Cmp desc

Heres a query that returns the new column I want
 SELECT   count(od_rid)
 FROM     od_f
 WHERE    od_f.plan_qty != od_f.cmp_qty
 GROUP BY od_f.ob_oid

I can't add the above where statement because it effects my results.
I'm really not sure what to do, to combined these queries a subquery? some sorta union?  I'm lost on how to do this.
 Thank you for any help
Comment: Can't you join your first query with your second query? I.e. SELECT * FROM (Select1 body) a JOIN (Select2 body) b ON a.something = b.something?
Answer: You can use conditional aggregation for what you want. Although COUNT() with CASE might be sufficient, my best guess is COUNT(DISTINCT):
SELECT   od_f.ob_oid Order,
         Sum(plan_qty) Plan_Units,
         sum(cmp_qty) Completed_Units,
         Round(((Sum(cmp_qty)/sum(plan_qty)) * 100.00),2)Percent_Cmp,
         total_value Value,
         SUM(round(cmp_qty * unit_price,2)) cmp_value,
         COUNT(DISTINCT CASE WHEN od_f.plan_qty <> od_f.cmp_qty THEN od_f. od_rid END) as newcol
FROM od_f JOIN
     om_f
     ON od_f.ob_oid = om_f.ob_oid
GROUP BY od_f.ob_oid, total_value
ORDER BY Percent_Cmp desc;

You should also learn to use proper, explicit JOIN syntax.  Simple rule:  Never use commas in the FROM clause.
Comment: This should work, just drop the extra `)` and in your case the `DISTINCT`.
Comment: I'm getting a syntax error with the line,  COUNT(DISTINCT CASE WHEN od_f.plan_qty <> od_f.cmp_qty THEN od_f. od_rid END)) as newcol. I'm using informix thats probably the issue.
Answer: @GordonLinoff solution is good for you, but only if you want to count uniques od_rid , this solution works for both cases, use a correlated query:
SELECT   t.ob_oid Order,
         Sum(plan_qty) Plan_Units,
         sum(cmp_qty) Completed_Units,
         Round(((Sum(cmp_qty)/sum(plan_qty)) * 100.00),2)Percent_Cmp,
         total_value Value,
         SUM(round(cmp_qty * unit_price,2)) cmp_value,
         (SELECT  count(f2.od_rid) FROM od_f f2
          WHERE f2.plan_qty != f2.cmp_qty and f2.ob_oid = f.ob_oid) as newcolumn
FROM     od_f t
         INNER JOIN om_f
ON       t.ob_oid = om_f.ob_oid
GROUP BY t.ob_oid, total_value
ORDER BY Percent_Cmp desc

Comment: This works but it returns a total in the column, is there a way to add a group by on the inner query? I tried but got a error 'subquery has returned not exactly one row'
Comment: Its not a total, its a count for each ob_oid .. exactly the same as your query @CharlesCooper
Comment: Here's a picture of what it looks like on my side, the first one is your query and the 2nd one is mine. http://imgur.com/a/gaDHd
Comment: Can't go inside this site
Comment: Weird, this should work also. Did you removed the `and f2.ob_oid = f.ob_oid` on the subquery?
Answer: For what I understand you only want a count of rows where plan_qty is not equal to cmp_qty, try this:
SELECT   t.ob_oid                                       AS order,
         SUM(plan_qty)                                  AS plan_units,
         SUM(cmp_qty)                                   AS completed_units,
         ROUND(((SUM(cmp_qty)/SUM(plan_qty)) * 100),2)  AS percent_cmp,
         total_value                                    AS value,
         SUM(ROUND(cmp_qty * unit_price,2))             AS cmp_value,
         SUM(DECODE(plan_qty, cmp_qty, 0, 1))           AS rows_left
FROM     od_f t
         INNER JOIN om_f
            ON t.ob_oid = om_f.ob_oid
GROUP BY t.ob_oid, total_value
ORDER BY percent_cmp DESC;

Comment: Thank you it worked perfectly. I did have to remove the "rows_left" in groupby due to syntax

Trying to add two queries together


what's the php way of setting the lang of a document?

Question: Recently I've learned that setting the charset using the meta tag is a pretty sub-standard way of doing things since we should instead set the charset in the server side like this:
header( 'Content-type: text/html; charset=utf-8' );

Does this concept also applies to the lang attribute of the html tag?
If so, what's the php way of setting the lang attribute of a document?
Answer: Try the Content-Language header.
Comment: @Richet: read [this document](http://www.w3.org/International/questions/qa-http-and-lang).
Comment: Also stick with the proper language codes per http://www.w3.org/TR/html4/struct/dirlang.html#h-8.1.1
Comment: so basically just like the meta charset, if i set the content-language header i can safely omit setting it within the html itself right?
Answer: Same as the regular HTML way: no difference for php.  remains the way forward.
Comment: what do you mean remains the way forward?
Comment: Sorry: I meant **continue to use the standard `lang` attribute**


deep-reverse for scheme

Question: When entering the list of ((1 2) (3 4)), I want to reverse it, but not so it's ((3 4) (1 2)), which is what reverse does, so I'm trying to write a deep-reverse procedure:
(define (deep-reverse l)
  (cond ((null? l) nil)
        (not (pair? (car l)) l)
        (else (append (deep-reverse (cdr l)) (list (car l))))))

but it just throws back ((1 2) (3 4)).  What's wrong and how do I get this to work?
Comment: What answer do you want? What is deep-reverse of '(1 (2 3) 4) and '(1 (2 (3 4)))?
Comment: I could see one possibility: reversed lists, within the reversed list `((4 3) (2 1))` in which case you just need to make recursive calls to reverse lists
Answer: Try:
(define (deep-reverse l) (map reverse l))

The above is the simplest possible answer; a real answer depends on exactly what you expect deep-reverse to do.  See my comment to your question.
If you want everything, all the way down:
(define (deep-reverse l)
  (if (list? l)
      (reverse (map deep-reverse l))
      l))

Here is how it works (correctly):
> (deep-reverse '(1 2 ((3.1 3.2) (4) "abc")))
(("abc" (4) (3.2 3.1)) 2 1)

Comment: the homework tag is [deprecated](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated), you shouldn't ask people  to use it anymore
Comment: but this would only work for a single level of lists within the list, right?
Comment: Right.  You want it all the way down?
Answer: A good start is the reverse procedure that works for a list. Then modify it to recursively apply to each car of the list:
(define (reverse x)
  (define (go items tail)
    (if (null? items) tail
        (go (cdr items) (cons (car items) tail))))
  (go x ()))

(define (deep-reverse x)
  (define (go items tail)
    (cond ((null? items) tail)
          ((not (pair? items)) items)
          (else (go (cdr items) (cons (go (car items) ()) tail)))))
  (go x ()))

An application of deep-reverse would be:
    (define x (list (list 1 (list 2 3) 4) 5 6 (list 7 8) 9 10)) (display x) (deep-reverse x)

   ((1 (2 3) 4) 5 6 (7 8) 9 10)
=> (10 9 (8 7) 6 5 (4 (3 2) 1))

Answer: You have to also deep reverse the car in the code. Otherwise you are not deep reversing the front-most part of the list.
(define (deep-reverse l)
  (cond ((null? l) nil)
        (not (pair? (car l)) l)
        (else (append (deep-reverse (cdr l)) (list (deep-reverse (car l)))))))

deep-reverse for scheme


Display only selected term from content type in Views

Question: maybe this is duplicate but I cant find solution and answer for this one, maybe its so basic buy I need little  help about.
I have content type with:
 1. Title
 2. Body
 3. Category
(Category field is Vocabulary check box with two taxonomy terms called
 1. Yes
 2. No
So I have contents some are with selected yes and some one are selected with no, I want to create a view and display only with the selected (Yes) contents. Any idea how should I do it. Thank you for reading this.
Answer: Under your Views,
Add filter criteria > Has taxonomy term > apply
Vocabulary: your vocabulary in question > Apply
Is one of: Yes > Reduce duplicates > Apply
Save your Views.
HTH
Comment: I knew it! I knew I am missing something there and is so basic. Thanks anyway
Answer:
Create a view with show Content of type your content type and continue and edit
Add a filter under Filter criteria select content : field (ie a taxonomy term reference field)
Select terms from vocabulary having yes value with operator Is one of

Result : Content listed with terms tagged with yes