Como implementar journaling em Python?

Question: Preciso fazer uma série de operações envolvendo arquivos binários (não dá pra usar BD), e preciso garantir que elas terminem com sucesso mesmo em caso de falha no meio da operação. Para isso, não vejo saída a não ser implementar um sistema de journaling manualmente. Comecei a escrever um código, mas não estou seguro se está correto (i.e. se não existem casos em que uma falha no meio da tarefa pode colocá-lo em um estado inconsistente - inclusive falha na própria escrita do journal).
Existe algo pronto nesse sentido? E se não existe, há algum problema na minha tentativa de solução abaixo?
def nova_tarefa(args):
    refazer_journal() # Refaz o que ficou inacabado da última vez (se houver)
    with open('args.json', 'w') as f:
        json.dump(args, f) # Prepara as novas tarefas
    with open('journal.txt', 'w') as f:
        f.write('comecar\n') # Coloca as novas tarefas no journal
    refazer_journal() # Faz as novas tarefas

def refazer_journal():
    try:
        with open('journal.txt', 'r') as f:
            passos = [x.strip() for x in f.readlines() if x.strip()]
    except:
        if not os.path.exists('journal.txt'):
            passos = []
        else:
            raise
    if not passos: # Se não há nada inacabado, termina
        return
    with open('args.json', 'r') as f:
        args = json.load(f)

    # Realiza as tarefas que ainda não foram marcadas como concluídas
    for indice,tarefa in enumerate(args['tarefas']):
        if len(passos) <= indice+1:
            realizar_tarefa_indepotente(tarefa)
            with open('journal.txt', 'a') as f:
                f.write('\ntarefa concluida\n')

    with open('journal.txt', 'w') as f:
        pass # Tudo foi feito com sucesso: esvazia o journal

(Nota: o que está escrito no journal - comecar, tarefa concluida - não é importante, se apenas uma letra que seja for escrita na linha já se considera que o passo foi bem-sucedido)
Código para teste (comigo funcionou sempre - inclusive editando o journal.txt para introduzir uma série de erros):
def realizar_tarefa_indepotente(tarefa):
    if 'falhar' in tarefa:
        raise Exception('Tarefa falhou!')
    print 'Realizando tarefa: ' + tarefa['nome']

tarefa_ok = {'tarefas':[{'nome':'foo'}, {'nome':'bar'}, {'nome':'baz'}]}
falha_3 = {'tarefas':[{'nome':'foo'}, {'nome':'bar'}, {'nome':'baz','falhar':True}]}
falha_2 = {'tarefas':[{'nome':'foo'}, {'nome':'bar','falhar':True}, {'nome':'baz'}]}
falha_1 = {'tarefas':[{'nome':'foo','falhar':True}, {'nome':'bar'}, {'nome':'baz'}]}
falha_1_3 = {'tarefas':[{'nome':'foo','falhar':True}, {'nome':'bar'}, {'nome':'baz','falhar':True}]}

Comment: @FelipeAvelar A maioria dos recursos que achei ao buscar por "python journal" se referia não a [*journaling*](http://pt.wikipedia.org/wiki/Journaling) [no contexto de sistema de arquivos] mas à implementação de alguma espécie de "diário"... Creio que esse link também se trata disso - já que é um plugin para o plone (sistema de CMS).
Comment: Nota: é do meu entendimento que revisão de código (*code review*) [faz parte do nosso foco (é *on topic*)](http://meta.pt.stackoverflow.com/q/264/215) atualmente. Se alguém não concorda, favor se manifestar no meta.
Comment: Não quis colocar isso como resposta, já que é só um link, mas acho interessante documentar. [Essa solução](https://github.com/4teamwork/ftw.journal) te satisfaz?
Answer: Escrevi um artigo que descreve como fazer isto: http://epx.com.br/artigos/arqtrans.php e inclusive um cidadão fez uma implementação em Python baseado no artigo: https://pypi.python.org/pypi/acidfile/1.2.0
A técnica básica é escrever dois arquivos no mínimo. Primeiro um, depois o outro em modo síncrono - conforme foi descrito em outras respostas.
O "tempero" do esquema é adicionar timestamp e um somatório (hash) nos dois arquivos. Dessa forma podemos saber qual é o arquivo mais recente - pelo timestamp - podendo verificar se o arquivo está íntegro (pelo hash).
O sistema de arquivos deve implementar journaling pelo menos dos meta-dados  (geralmente é o caso, journaling dos dados custa performance). Isto garante que pelo menos a pasta e o arquivo sejam legíveis. Se os dados estiverem corrompidos você detecta pelo hash.
Comment: Exatamente o que eu estava procurando! Melhor do que reinventar a roda... Vou testar essa implementação que você citou, mas já dei uma olhada nos fontes e me parece que está tudo ok.
Comment: Acabei por utilizar sua solução: agora eu salvo o próprio `args.json` como um `ACIDFile` - assegurando de só atualizá-lo após me certificar que a tarefa anterior completou com sucesso (ver [resposta do @utluiz](http://pt.stackoverflow.com/a/5825/215)). Simplificou bastante o código.
Answer:
Um problema facilmente visível na sua implementação é que a forma que você checa pra ver se o arquivo journal.txt existe após a leitura está sujeita a race conditions, vide Como checar se um arquivo existe usando Python.
Além disso, o ideal é, não capturar exceções "naked", e sim definindo o tipo específico de exceção que você espera, p.ex. IOError, OSError, etc. Da mesma forma, quando for raise uma exceção, é bom utilizar uma com um nome específico relacionado ao tipo de erro.
Para iterar sobre o dicionário, como uma alternativa, ao invés de iterar sobre o resultado do enumerate(), você pode simplesmente iterar sobre a lista:
passos = [{'nome':'foo','falhar':True}, {'nome':'bar'}, {'nome':'baz'}]
for tarefa in passos:
    realizar_tarefa_indepotente(tarefa)

A forma que você checa se o valor 'falhar' funciona, mas não é muito explícita. Recomendaria trocar por if 'falhar' in tarefa.items(), se você estiver simplesmente checando se ela existe, ou if tarefa.get('falhar') se você quiser certificar-se que o valor de tarefa['falhar'] é True.
Comment: Não precisa, você pode simplesmente retirar o bloco `if` já que se ocorrer exceção dentro do `try` o arquivo provavelmente não existe. Seguindo o bullet seguinte, você poderia checar por exceções diferentes e tratar casos diferentes (p.ex. arquivo não existe, acesso negado, etc).
Comment: Sobre o item #3, **acho** que a ideia é não executar os passos que já foram executados. Por exemplo, se há 3 passos gravados no `journal.txt`, as tarefas serão executadas da 4ª em diante. Nesse caso, a não ser que o índice seja usado para alguma outra coisa no código real, talvez pudesse ser feito algo como `for tarefa in args['tarefas'][len(passos):]:`.
Comment: Ou ainda: já que o seu arquivo `journal.txt` só guarda o número de tarefas que foram executadas com sucesso, você poderia gravar simplesmente o número, incrementando-o a cada sucesso e utilizando-o ao invés de `len(passos)` para pular as tarefas que foram executadas com sucesso.
Comment: [sobre o último comentário] isso não é possível, pois há o risco de eu corromper o `journal.txt` se houver falha durante a manipulação do mesmo. No modo que eu fiz, **ou** uma linha nova será adicionada ao arquivo (confirmando a tarefa) **ou** não (exigindo que ela seja refeita depois). [sobre #1 e #2] Boa sugestão, vou fazer! [sobre #3] A sugestão do @utluiz é boa. Eu preciso ignorar tarefas já feitas pois, embora cada tarefa individual seja indepotente **no estado correto do sistema**, ela não o é se o sistema já mudou de estado (i.e. se a tarefa seguinte já começou).
Comment: Uma dúvida sobre o item #1: o `try` já não faz exatamente isso, solicitando a leitura do arquivo? Deveria então haver um outro bloco try aninhado?
Comment: Certo, entendi. Obrigado!
Comment: Entendi. Minha preferência pessoal seria por iterar sobre esses itens de qualquer forma e ignorá-los em seguida. Outra alternativa é filtrar a lista (p.ex.: `args['tarefas'] = [x for x in args['tarefas'] if x.get('falhar') is False]`), mas com isso você perde a informação sobre índices e a quantidade de itens que já foram feitos e pode demorar um pouco caso o número de itens seja grande.
Answer: Garantia da gravação dos arquivos
Meu primeiro pensamento quando se trata de garantir o processamento de arquivos foi o buffer de dados.
Veja o que diz a documentação do file.flush():

Nota: o flush() não necessariamente escreve os dados do arquivo para o disco. Use flush() seguido por os.fsync() para garantir o comportamento. (tradução livre)

Suponho que as tarefas podem ter um volume bem maior de dados do que o journal.txt. Se ocorrer uma queda de energia no final do método refazer_journal(), o journal pode ter sido gravado no disco enquanto os dados das tarefas ainda estão em buffer.
Eu entendo que os dados do journal são enviados depois, mas não creio existir uma garantia de que o buffer será enfileirado sequencialmente pelo sistema operacional e pelo hardware.
Comment: Boa observação! Vou fazer isso e, pra garantir, também uma verificação dos arquivos recém-escritos para confirmar que está tudo ok **antes** de confirmar a tarefa. (e se entendi bem, é importante que o `os.fsync` seja usado também depois de se escrever o journal - para evitar que a tarefa seguinte comece sem que a registro de conclusão da tarefa anterior esteja pronto, certo?)
Comment: @mgibsonbr Sim, acredito que a sincronização deva ser feita após todas as gravações.
Comment: Li ainda algum lugar (acho que foi no Linux System Programming) que o sync deveria ser feito 2 ou 3 vezes, como é o costume dos admins UNIX na linha de comando. Não lembro a razão exata, é algo como: o primeiro sync só inicia a gravação física, mas o segundo sync efetivamente bloqueia antes do primeiro terminar (se ainda não terminou).
Comment: @epx Wow! Aí o nível baixou muito pra mim... rsrs
Answer: Crie um journaling baseado em arquivos no filesystem. Sugiro usar uma nomenclatura baseada em epoch... Escrever e apagar itens de uma única vez é sempre mais seguro que manipula-lo milhares de vezes. O próprio journaling pode ser corrompido, já que atomicidade em python é dificil de garantir pra processos longos.

Como implementar journaling em Python?


Device IP address returned from Android app different from the phone

Question: The mobile IP address returned from the Android app is different from that shown in the settings of the phone.
I tried to use the following sample code to read the IP assigned from the mobile network to an Android phone (running Android 7) connected to mobile network only. The Android app returns 10.130.151.51 but the IP address found from the phone menu is 220.127.116.11.
Anybody knows why and how can I get the correct one ?
<code>public String Get_Mobile_IP(){
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkinterfaces();
             en.hasMoreElements();) {
            NetworkInterface networkinterface = en.nextElement();
            for (Enumeration<InetAddress> en_IP = networkinterface.getInetAddresses(); en__IP.hasMoreElements();) {
                InetAddress mobile_IPaddr = en_IP.nextElement();
                if (!mobile_IPaddr.isLoopbackAddress() && mobile_IPaddr instanceof Inet4Address) {
                    return mobileIPAddr.getHostAddress();
                }

            }
        }
    } catch (Exception ex) {

    }
    return null;
}
</code>
Comment: I can read the IP address using both Android coding. The problem I have is that the value returned from the application is not the same as that shown in the handset menu of the phone.
Comment: I found that I have to switch off the "VoLTE" in the Android phone to get the correct result
Answer: You may try this code :-
You can use this method to get IP address of the device pass true for IPv4 and false for IPv6
<code> public static String getIPAddress(boolean useIPv4) {
try {
    List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    for (NetworkInterface intf : interfaces) {
        List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
        for (InetAddress addr : addrs) {
            if (!addr.isLoopbackAddress()) {
                String sAddr = addr.getHostAddress();
                //boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                boolean isIPv4 = sAddr.indexOf(':')<0;

                if (useIPv4) {
                    if (isIPv4)
                        return sAddr;
                } else {
                    if (!isIPv4) {
                        int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
                        return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
                    }
                }
            }
        }
    }
} catch (Exception ex) { } // for now eat exceptions
return "";
</code>
}


Como funciona o processo de renderização das página web pelo browser?

Question: Sei que existe a arvore DOM, mas desconheço como funciona a renderização. Sei que aprender isso é importante.
Answer: Não existe algo especifico, isso não ocorre no front-end de fato, ou é dependente de javascript ou algo assim, a questão é que internamente um navegador tem um "motor" (mais de um) baseado em "interfaces" que renderizam seguindo a resposta do seus HTML e CSS.
Então é como se o HTML e CSS fossem instruções para que este motor criasse a composição da página, alterando conforme você manipula o DOM via javascript.
Por exemplo você requisita uma página, o navegador baixa o conteúdo dela podendo ser parcial ou não e começa a processa-la enviando o que já foi baixado para o motor começar a desenhar conforme as instruções e gerar itens como botões e outras coisas.
Na verdade quando você manipula usando JavaScript ou injeta um CSS as instruções e o motor detecta estas "atualizações" e modifica conforme essas novas instruções renderizando novamente.
Não há uma necessidade em aprender a criar algo assim, isto eu digo se você pretende desenvolver páginas web apenas.
Existe algumas respostas minhas que pode lhe interessar sobre o assunto:

Existe um modo de ver o código nativo de funções do JavaScript?
É correto omitir a start tag html no HTML5?
Qual o código e linguagem fazem a tag input fazer o que faz?

Os motores mais populares:

Blink
O Blink é o motor usado pelos navegadores Chrome, Opera e Vivaldi (existem mais), ele é uma fork do motor Webkit. O Blink veem em conjunto com o Chromium que é projeto open-source da Google usada no Chrome e que você pode usar para criar o seu próprio navegador, o Chromium vai bem além do motor de renderização, ele traz consigo varias funcionalidades.
Ele é escrito em C++
Webkit
Motor usado por muitos navegadores, até mesmo nas primeiras versões do Google Chrome, é usado principalmente no Safari para Mac e iOS e em muitos navegadores mobile como o navegador padrão do Android e até mesmo em BlackBerrys, este motor foi baseado em um motor chamado KHTML, irei falar dele posteriormente.
Ele é escrito em C++
Gecko
Motor do navegador Firefox que também é usado em outros produtos da mesma empresa, como o Thunderbird (cliente de email), ele também é open-source.
Ele é escrito em C++
EdgeHTML
É o motor usado no navegador Microsoft Edge, sucessor do Internet Explorer, ele não é open-source (ou seja é proprietário).
Provavelmente escrito em C++
Trident
Motor usado no Internet Explorer, também é proprietário, provavelmente também escrito em C++
KHTML
Este é o motor que deu origem ao Webkit, a Apple anos atrás não possuía navegador próprio, tanto que até a Microsoft desenvolveu uma versão do do Internet Explorer para Mac (não usava o Trident e sim um motor chamado Tasman),  a Apple fez uma fork para criar a primeira e a segunda versão do Safari e tornando esta fork no conhecido Webkit.
Este motor é usado pelo KDE no seu navegador chamado Konqueror e talvez para outras funcionalidades.
Ele é escrito em C++

Ainda existem muitos motores de renderização, mas não tão populares ou que estão simplesmente em desuso.
Cada motor tem o seu próprio "sistema", ou seja cada uma funciona a sua maneira e internamente provavelmente todos são diferentes, o que eles devem seguir são os padrões web para definir como tal instrução deve ser "entregue", não quer dizer que ele teve que seguir o mesmo caminho que outro motor, mas o resultado final precisa ser igual.
Motores de renderização geralmente suportam:

HTML
CSS
SVG

Muitos elementos na página podem usar recursos do sistema operacional como botões e scrollbars e codecs de áudio e vídeo, claro que isso é bem relativo, antes os navegadores usavam plugins ou activex para processar audio e video, hoje os navegadores tem players próprios, alguns ainda sim usam os codecs do sistema operacional (isso devido as LICENÇAS que cada codec tem, o que poderia implicar em muitos problemas legais), outros tem suporte a alguns codecs nativamente.
Comment: @gato total, eles recebem as instruções e geram os elementos visuais, podendo usar ou não componentes do sistema operacional, o DOM seria uma interface que serve como instrução para o MOTOR para ele saber aonde vão as coisas. Amanhã prometo dar uma detalhada melhor, não tem muito como definir porque cada motor faz a sua maneira as coisas.
Comment: Os motores citados tem alguma relação com o DOM?
Comment: Onde exatamente fica o DOM?


validar todos os campos do formulário com JavaScript

Question: Bom dia, tudo bem?
Estou iniciando em JavaScript e preciso validar todos os campos no formulário do código abaixo por meio deste. Consegui validar os 6 primeiros campos, faltam radio e checkbox.
Algum auxílio?
Segue código abaixo:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Freedom/C></title>
    <link rel="stylesheet" type="text/css" href="Freedom.css"/>

Controle de Qualidade

Cadastro de Ocorrências

<form method="post" id="fOcorrencia" name="fOcorrencia" action="mailto:email@example.com">
    <fieldset>
        <legend>Descreva</legend>

Setor:<input type="text" size="70" maxlength="70" name="Setor" id="cSetor"/>

Responsável:<input type="text" size="70" maxlength="70" name="Resp" id="cResp"/>

Tipo de ocorrência:<input type="text" size="70" maxlength="70" name="TipoO" id="cTipoO"/>

Responsável pela aprovação da ocorrência:<input type="text" name="RespApOc" size="70" maxlength="70" id="cRespApOc"/>

Descrição da ocorrência:<textarea name="Descricao" id="cDescricao" cols="70" rows="5"></textarea>

Plano de ação:<textarea name="Plano" id="cPlano" cols="70" rows="5"></textarea>

    </fieldset>
    <fieldset>
        <legend>Tipo</legend>
        <input type="radio" name="Tipo" id="cDisp"/>Disposição
        <input type="radio" name="Tipo" id="cCorr"/>Correção
    </fieldset>
    <fieldset>
        <legend>Natureza</legend>
        <input type="checkbox" value="Prod"/>Produção
        <input type="checkbox" value="Admin"/>Admnistrativo
        <input type="checkbox" value="Amb"/>Ambiental
    </fieldset>
    <input type="submit" onclick="return validar()" value="Enviar Ocorrência"/>
</form>

Answer: Você pode pegar os elementos do tipo radio e checkbox da seguinte maneira:
1 - Todos os elementos devem possuir o atributo name (nesse exemplo capturei os mesmo por esse atributo)
2 - Na captura, precisamos verificar a quantidade de itens que foram selecionados (checados), por isso que na seleção utilizei:  ('input[name="checkNatureza"]:checked').length; pois ele irá retornar a quantidade de elementos checados.
Para realizar a verificação, bastar conferir se o valor capturado nas variáveis é igual a zero, se for, ele entrará no if e não deixará o formulário ser enviado.
Abaixo o exemplo completo:

function validar() {
            var Setor = fOcorrencia.Setor.value;
            var Resp = fOcorrencia.Resp.value;
            var TipoO = fOcorrencia.TipoO.value;
            var RespApOc = fOcorrencia.TipoO.value;
            var Descricao = fOcorrencia.Descricao.value;
            var Plano = fOcorrencia.Plano.value;

            //captura o número de itens "selecionados"
            var Tipo = document.querySelectorAll('input[name="Tipo"]:checked').length;

            //captura o número de itens "checados"
            var Natureza = document.querySelectorAll('input[name="checkNatureza"]:checked').length;

            if (Setor == "") {
                alert("Preencha todos os campos");
                return false;
            }
            if (Resp == "") {
                alert("Preencha todos os campos");
                return false;
            }
            if (TipoO == "") {
                alert("Preencha todos os campos");
                return false;
            }
            if (RespApOc == "") {
                alert("Preencha todos os campos");
                return false;
            }
            if (Descricao == "") {
                alert("Preencha todos os campos");
                return false;
            }
            if (Plano == "") {
                alert("Preencha todos os campos");
                return false;
            }

             if (Tipo == 0) {
                alert("Preencha todos os campos");
                return false;
            }

             if (Natureza == 0) {
                alert("Preencha todos os campos");
                return false;
            }
            return true;
        }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Freedom/C></title>
    <link rel="stylesheet" type="text/css" href="Freedom.css"/>

Controle de Qualidade

Cadastro de Ocorrências

<form method="post" id="fOcorrencia" name="fOcorrencia" action="mailto:firstname.lastname@example.com">
    <fieldset>
        <legend>Descreva</legend>

Setor:<input type="text" size="70" maxlength="70" name="Setor" id="cSetor"/>

Responsável:<input type="text" size="70" maxlength="70" name="Resp" id="cResp"/>

Tipo de ocorrência:<input type="text" size="70" maxlength="70" name="TipoO" id="cTipoO"/>

Responsável pela aprovação da ocorrência:<input type="text" name="RespApOc" size="70" maxlength="70" id="cRespApOc"/>

Descrição da ocorrência:<textarea name="Descricao" id="cDescricao" cols="70" rows="5"></textarea>

Plano de ação:<textarea name="Plano" id="cPlano" cols="70" rows="5"></textarea>

    </fieldset>
    <fieldset>
        <legend>Tipo</legend>
        <input type="radio" name="Tipo" id="cDisp"/>Disposição
        <input type="radio" name="Tipo" id="cCorr"/>Correção
    </fieldset>
    <fieldset>
        <legend>Natureza</legend>
        <input type="checkbox" value="Prod" name="checkNatureza"/>Produção
        <input type="checkbox" value="Admin"name="checkNatureza" />Admnistrativo
        <input type="checkbox" value="Amb" name="checkNatureza"/>Ambiental
    </fieldset>
    <input type="submit" onclick="return validar()" value="Enviar Ocorrência"/>
</form>

Exemplo isolado (apenas os inputs radios e checkboxs):

function validar() {

            //captura o número de itens "selecionados"
            var Tipo = document.querySelectorAll('input[name="Tipo"]:checked').length;

            //captura o número de itens "checados"
            var Natureza = document.querySelectorAll('input[name="checkNatureza"]:checked').length;

             if (Tipo == 0) {
                alert("Preencha todos os campos");
                return false;
            }

             if (Natureza == 0) {
                alert("Preencha todos os campos");
                return false;
            }
            return true;
        }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Freedom/C></title>
    <link rel="stylesheet" type="text/css" href="Freedom.css"/>

Controle de Qualidade

Cadastro de Ocorrências

<form method="post" id="fOcorrencia" name="fOcorrencia" action="mailto:email@example.com">

    <fieldset>
        <legend>Tipo</legend>
        <input type="radio" name="Tipo" id="cDisp"/>Disposição
        <input type="radio" name="Tipo" id="cCorr"/>Correção
    </fieldset>
    <fieldset>
        <legend>Natureza</legend>
        <input type="checkbox" value="Prod" name="checkNatureza"/>Produção
        <input type="checkbox" value="Admin"name="checkNatureza" />Admnistrativo
        <input type="checkbox" value="Amb" name="checkNatureza"/>Ambiental
    </fieldset>
    <input type="submit" onclick="return validar()" value="Enviar Ocorrência"/>
</form>

Dica: Não forneça seu e-mail verdadeiro, pois você pode acabar sendo vítima de mensagens spam, use sempre dados ilustrativos para demonstração de exemplos.


Find number of real roots using Sturm's method.

Question: Sturm's method for finding number of real roots is very good . But it is time consuming to find reminder in division of polynomials specially for high degrees.
I want to know , Is there any way to find first term of reminder? (Because in Sturm's method we need to determine sign of reminder)
For example : $f(x) = 3x^3 + 5x^2 - 6x- 2$
By Sturm's method : $$ p_0(x) = 3x^3 + 5x^2 - 6x- 2$$
  $$p_1(x) = 9x^2 + 10x - 6 $$ $$p_2(x) = \frac{158x}{27 } + \frac{8}{9}$$ $$p_3(x) = +\frac{45630}{6241} $$ and now we must determine signs of $p_i(-\infty)$ and $p_i(+\infty)$ Which first gives us $-$ , $+$ , $-$  , $+$ for three changes  and the second $+$ , $+$ , $+$ , $+$ for zero sign changes . Therefore ,we have $3-0 = 3$ real roots . It is obvious that calculation for solving this problem is very hard and we don't use coefficients like $\frac{158}{27 }$ for determining sign of $p_i(x)$
Comment: Do you know any faster way to find number of real roots ?
Comment: IIRC, none of the coefficients are superfluous; you need to know their values to compute the later polynomials in the sequence. That said, you can do other things, e.g. multiplying $p_2$ through by $27$ to clear denominators. (or, actually, tweak how you do the calculation of $p_2$ to avoid fractions entirely)
Comment: @Hurkyl Can you help ?
Answer: All errors in prior versions were fixed. Note that this is a long post, and was a nightmare to encode in MathJax
I think that Synthetic Division would really help you. It basically simplifies the process of Polynomial Long Division.  I will use your example from above.
$$\frac{3x^3 + 5x^2 - 6x- 2}{9x^2 + 10x - 6}=\frac{p(x)}{q(x)}$$
Let $p(x)$ be the polynomial in your numerator and $q(x)$ be a monic polynomial in the denominator. To make the denominator monic we must divide by the leading coefficient, to get a new $q^*(x) = x^2+\frac{10}{9}x-\frac{2}{3}$
We start by drawing this table
$$\begin{array}{c|rrrr}&x^3 & x^2 & x^1 & x^0\\ \hline&  &  &  &\\ {} &  &  &  & \\ &  &  &  &\\\hline &  &  &   &  {} \end{array}$$
Now let's fill in the coefficients of $p(x)$ in the first line.
$$\begin{array}{c|rrrr}& x^3 & x^2 & x^1 & x^0\\ \hline& 3 & 5 & -6 & -2\\ {} &  &  &  & \\ &  &  &  &\\\hline &  &  &   &  {} \end{array}$$
We now negate all the coefficients of $q^*(x)$ and include all of them except the first going diagonally up; for example, since $q^*(x) = x^2+\frac{10}{9}x-\frac{2}{3}$ our negated coefficients will be $\{-1,-\frac{10}{9},\frac{2}{3}\}$ and we will only use $\{-\frac{10}{9},\frac{2}{3}\}$
$$\begin{array}{cc|rrrr}& & x^3 & x^2 & x^1 & x^0\\ \hline& & 3 & 5 & -6 & -2\\  & \frac{2}{3} &  &  & \\ {-\frac{10}{9}}&  &  &  &\\\hline &  &  &   &   \end{array}$$
We now "drop" the first coefficient
$$\begin{array}{cc|rrrr}& & x^3 & x^2 & x^1 & x^0\\ \hline& & 3 & 5 & -6 & -2\\  & \frac{2}{3} &  &  & \\ {-\frac{10}{9}}&  &  &  &\\\hline &  & 3 &   &   \end{array}$$
We now multiply this "dropped" number by our coefficients of $q(x)$
$$\begin{array}{cc|rrrr}& & x^3 & x^2 & x^1 & x^0\\ \hline& & 3 & 5 & -6 & -2\\  & \frac{2}{3} &  &  & 2\\ {-\frac{10}{9}}&  &  & -\frac{10}{3} &\\\hline &  & 3 &   &   \end{array}$$
We now perform add vertically in the second column
$$\begin{array}{cc|rrrr}& & x^3 & x^2 & x^1 & x^0\\ \hline& & 3 & 5 & -6 & -2\\ & \frac{2}{3} &  &  & 2\\ {-\frac{10}{9}}&  &  & -\frac{10}{3} &\\\hline &  & 3 & \frac{5}{3}  &   \end{array}$$
Repeating the last couple steps until the middle row is filled
$$\begin{array}{cc|rrrr}& & x^3 & x^2 & x^1 & x^0\\ \hline& & 3 & 5 & -6 & -2\\ & \frac{2}{3} &  &  & 2&\frac{10}{9}\\ {-\frac{10}{9}}&  &  & -\frac{10}{3} &-\frac{50}{27}\\\hline &  & 3 & \frac{5}{3}  &   \end{array}$$
$$\begin{array}{cc|rrrr}& & x^3 & x^2 & x^1 & x^0\\ \hline& & 3 & 5 & -6 & -2\\ & \frac{2}{3} &  &  & 2&\frac{10}{9}\\ {-\frac{10}{9}}&  &  & -\frac{10}{3} &-\frac{50}{27}\\\hline &  & 3 & \frac{5}{3}  & \frac{158}{27}   \end{array}$$
Now we just add the last column vertically
$$\begin{array}{cc|rrrr}& & x^3 & x^2 & x^1 & x^0\\ \hline& & 3 & 5 & -6 & -2\\ & \frac{2}{3} &  &  & 2&\frac{10}{9}\\ {-\frac{10}{9}}&  &  & -\frac{10}{3} &-\frac{50}{27}\\\hline &  & 3 & \frac{5}{3}  & \frac{158}{27} &-\frac{8}{9}  \end{array}$$
Now, the we look at the degree of $q(x)$ and draw a dividing line that far from the right; here $q(x)$ is of degree $2$, so we put a dividing line $2$ from the right
$$\begin{array}{cc|rrrr}& & x^3 & x^2 & x^1 & x^0\\ \hline& & 3 & 5 & -6 & -2\\ & \frac{2}{3} &  &  & 2&\frac{10}{9}\\ {-\frac{10}{9}}&  &  & -\frac{10}{3} &-\frac{50}{27}\\\hline &  & 3 & \frac{5}{3}  &|\phantom{-} \frac{158}{27} &-\frac{8}{9}  \end{array}$$
The left side of the dividing line has the coefficients of the result of our division, and the right side has the coefficients of the remainder. Both are written from largest power to smallest power. Since both sides have $2$ coefficients, both the result and remainder are of degree $1$. To get our answer we must write the result and remainder in standard form and remember that we divided by $9$ in the denominator
$$\frac{3x^3 + 5x^2 - 6x- 2}{9x^2 + 10x - 6} = \frac{1}{9}\left(3x+\frac{5}{3}+\frac{\color{red}{\frac{158}{27}x-\frac{8}{9}}}{9x^2 + 10x - 6}\right)$$
Now, since all you need for Sturm's Method is the remainder, you can just stop after drawing the dividing line, which saves time.
Comment: Thank you , Your answer is very good but I'm looking for a way that we don't perform division . Because we only need to determine the sign of polynomial and for doing it , we only need to first term of reminder with its degree and other terms are useless .
Comment: @S.H.W I'm fairly certain that this is the fastest way in general (this is really just shorthand long division of course). All you have to do is carry it out to the term you want — this took me 20 seconds to do by hand with a calculator (MathJax is a different story). You could of course replace the coefficients with variables and get a formula involving only addition and multiplication for the first term by doing synthetic division, but remembering the formula wouldn't be easy and it's really not any faster than just doing plain old synthetic division
Comment: @S.H.W the easiest way in general is still to start with Descartes rule of signs and do some analysis, if you ask me...but perhaps not the fastest
Comment: The Descartes rule of signs gives us only upper bound for roots and also doesn't determine that roots are real or complex.
Comment: @S.H.W sure, hence the "with analysis" part of my comment above
Comment: Okay , but I want a general method . If you know any method using derivation or anything that helps , Please provide.
Comment: @S.H.W there are other ways to do this, but none of them are faster than synthetic division. What are your goals here? No magic formula is going to appear... You can't expect all problems to have simple solutions. As I said before, I could represent the answer in series notation if you would like, but this would really just be a formula derived FROM synthetic division which comes FROM long division. They are all really the same, I just know from experience that synthetic Division balances memorization and time efficiency.
Comment: @S.H.W another way is by taking the discriminant, but good luck calculating that for any polynomial greater than degree $2$ or $3$. There's a reason Sturm came up with his method
Comment: Okay , Thank you a lot.
Answer: Sturm polynomials are very powerful but I am afraid the time consuming part is inevitable. Are you trying to do this on a computer? For example Mathematica can do this very fast. Below is an example. Hope it helps. (I've added couple of related commands.)
Comment: No , I know that sturm's method using computer is very good. But I want to use it with hand
Comment: In other words , I'm looking for method that helps me to find number of real roots for polynomials in general. (Without using computer)
Comment: Then I would probably not start with Sturm since it is very powerful but very tedious instrument. Starting with Descarte's rule of signs? Checking which infinity the polynomial diverges to? Investigating its shape? I am afraid when it comes to simplicity, there is very little that would be general.
Comment: The Descarte's rule of signs only gives us a upper bound and also doesn't care about real or complex roots
Comment: Well, the last thing I can offer, since I do not know more, is this book on polynomials (especially 1.4 helped me in the past): http://www.springer.com/gb/book/9783540407140
Comment: Okay , Thank you a lot for your help.


How to do test the significant difference of CD4 count less than 350 in relation to different races using SPSS

Question: I have a pool of CD4 count from 0 to more than 1000, and all the CD4 counts are respect to different races. So how to only test the CD4 count less than 350 to different races? To see whether there is significant difference CD4 counts for different races for CD4 count <350?
Answer: This is an inappropriate question to ask.  CD4 count does not work biologically such that something magic happens at 350.  And your power is greatly diminished when you toss information away.  Frame this as a general question, e.g., do CD4 counts tend to be larger for some races than for others?  That would be answered robustly and powerfully using the Kruskal-Wallis test.
Comment: CD4 count less than 350 is a WHO criteria for HIV treatment.  That might be the magic number came from.
Comment: That cutoff has not been validated.  Even if it had, it should not dictate that you do low-power analysis.  Statistical inference should use all the information in the data.  Once you are finished you can convert the result to get a maximum likelihood estimate for the probability of falling below 350.  For parametric models this is a function of the predicted mean and SD.  For ordinal models (e.g., proportional odds model - the generalization of the Kruskal-Wallis and Wilcoxon tests) probabilities of inequalities come directly out of the model.
Answer: You could simply create in indicator variable that is coded 1 in instances where the CD4 count is less than 350; zero otherwise.  Call that variable CD4ind.  Then you could include an interaction term with your race variable and CD4ind in your model (e.g. $y=CD4ind + race +CD4ind*race$).  If the coefficient associated with the interaction term turns out to be significant, they you have some evidence that CD4 is associated with changes in y differently for different races.
That being said, Frank offers some valuable advice here.


How to know that $(z-z_0^3)(z-z_0^5)(z-z_0^7) = \sum_{k=0}^3 z^k z^{3-k}_0$

Question: How to know that $$(z-z_0^3)(z-z_0^5)(z-z_0^7) = \sum_{k=0}^3 z^k z^{3-k}_0$$
with $z_0$ a root of $z^4+1$.
I can check that it is true, but is there a way to tell, by seeing the LHS expression, that it can be in the RHS form ?
Comment: From $z_0^4=-1$, you have $z_0^5=z_0$, $z_0^7=z_0^3$ etc.
Answer: I'm not sure if that is what you are after, but:
If $\omega$ is a primitive $2k$-th root of unity, then the solutions of $z^k+1 = 0$ are $\omega^{2n+1},\, 0 \leqslant n < k$, so
$$z^k + 1 = \prod_{n=0}^{k-1} (z-\omega^{2n+1}),$$
and hence
$$\begin{align}
\prod_{n=1}^{k-1} (z-\omega^{2n+1}) &= \frac{z^k+1}{z-\omega}\\
&= \frac{z^k - \omega^k}{z-\omega}\\
&= \sum_{m=0}^{k-1} z^{k-1-m}\omega^{m}\\
&= \sum_{m=0}^{k-1} z^m\omega^{k-1-m}.
\end{align}$$
So the "trick" is to recognise that $z_0^3,z_0^5,z_0^7$ are just the fourth roots of $-1$ that are different from $z_0$.


Saving an array of new entities via breeze context "saveChanges"

Question: If I have an entity that contains a 1:n collection of another entity then what is the correct way to save the collection?
I've got to this (code not finalised/checked yet):
return datacontext.savechanges([parentEntity]).then(function() {
    for (var i=0;i < childArray.length;i++) {

        var newChildEntity;
        return datacontext.makeNewChildEntity(newChildEntity).then(function() {
            newChildEntity.parentID(parentEntity().id());
            ...
            //set other newChildEntity properties
            ...
            return datacontext.savechanges([newChildEntity]).then(function() {
                 //set finished flag and exit function...
            }

        }
    }
}

"datacontext" is an async module with various exposed methods including creating a new childEntity.
Whereas I haven't tested this yet, it kind of logically works for me, but am I right to be looping around in the createEntity/modifyEntity/saveEntity loop for each new child object I want to add to the collection of childEntities?  Is this the only way to do it or is there a way of doing all childEntities in one hit?
The "parentID" is an identity field - store generated so I have to wait for the intitial parent save to finish before I can use the returned ID.
Edited to add: I don't think I need to have a "then" on the end of the async newChildEntity save, do I?  I need it to be async still so it can go off and loop through multiple childEntities quickly as the dependent bit is the id from the parent record that's already generated. All the child records share the same parentID so I can set off multiple saves without waiting for the saveChanges method to respond, right?
Answer: Breeze's EntityManager.saveChanges can save any number of entities in a single call, which is substantially more performant than trying to call saveChanges once per entity.
Also, I'm not sure why your makeNewChildEntity needs to be asynchronous, Breeze's EntityManager.createEntity itself is synchronous, so I think that all you need to do is something like this.
return datacontext.savechanges([parentEntity]).then(function() {
    var listOfEntities = [parentEntity];
    for (var i=0;i < childArray.length;i++) {
        // synchronous makeNewChildEntity
        var newChildEntity = datacontext.makeNewChildEntity();
        newChildEntity.parentID(parentEntity().id());
        ...
        //set other newChildEntity properties
        ...
        listOfEntities.push(newChildEntity);
     }
     // alternatively use datacontext.savechanges(listOfEntities).then(...)
     return datacontext.savechanges().then(function() {
             //set finished flag and exit function...
     }
}

}
Comment: Ah yes. Good point on the synchronous nature of "createEntity", I'd forgotten that.  I'll have a quick go at implementing this, but it looks good at a glance, thanks for the guidance Jay.
Comment: Just one thing Jay - what does this line do please? `var listOfEntities = [parentEntity];`? Is this a breeze related function I'm unaware of?
Comment: In case you wanted to create an array containing the parentEntity and its list of children.  This just starts the array containing the parentEntity. (See the alternate call).


Symbol(s) not found for architecture i386 zbar

Question:
I can't run my application cause of this crazy error. Everything ran great before I updated from Xcode 6 to 7.
Comment: Hi Berk, Welcome to stackoverflow, Please post the segment of the code where you get the error.
Answer: You have to import AVFoundation and AudioToolbox frameworks and also set i386 armv6 armv7 armv7s architectures needed for running the libraries.
OR
The 7 frameworks need to be in the following order:
<code>Foundation.framework
CoreGraphics.framework
UIKit.framework
AVFoundation.framework
CoreMedia.framework
CoreVideo.framework
QuartzCore.framework
libiconv.dylib
libzbar.a
</code>
I wasn't aware the order the frameworks are declared in the Build Phases mattered. Anyways, hopefully for anybody trying to integrate a barcode scanner into their app, this answer will be useful.
Comment: I already add all of them also architecture is correct.But still not running.I gues it is because of mac os version or xcode version.I have another mac which is not updated yet.On there i can run the project.Bu in os 10 or hihger with xcode it doesnt run.What should i do ? I am glad you to answer..
Comment: If you are using Xcode 7 then sometimes its gives error on build so just try to reinstall Xcode 7 again on your system.


Windows XP laptop doesn't appear in WSUS All computers list

Question: I have this one laptop that doesn't appear in WSUS all computers list.  We have about 23-25 PCs/laptops/servers in the network, all, but one are listed in WSUS.
This is what I have done so far:
1) Changing Updates on local PC:

Go to your Windows XP client and start a new Microsoft Management
Console (MMC). At Start, Run, type MMC.
Use Ctrl+M to add a new snap-in.
Click Add, and then add the Group Policy Object Editor for the Local
Computer.
Click Close, and then click OK.
Expand the Local Computer Policy.
Under Computer Configuration, go to Administrative Templates, Windows
Components, Windows Update.
In the right-hand pane, double-click Specify intranet Microsoft
update service location.
Configure the settings to reflect my WSUS server.
Click OK and then close the MMC without saving it.

executed wuauclt.exe /detectnow
2) Edited registry key to be pushed to the PCs using GPO
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate]
"WUServer"=http://wsusserver
"TargetGroupEnabled"=dword:00000001
"TargetGroup"="WINXP"
"WUStatusServer"=http://wsuswerver

3) executed wuauclt /resetauthorization /detectnow
4)Synchronised and refreshed the group
I am running out of ideas here.  The client is running Windows XP pro, WSUS version is 3.0 and is running on Windows 2008 R2 64-bit.
Please, help!
Thanks!
EDIT 13.IX.2012 @ 15.40 CT
I should have also mentioned that we do have a Windows Update GPO for workstations group and that laptop is a part of that group.
EDIT 13.IX.2012 @ 18.03 CT
Here are the .  Now, after googling the error that's the solution I came across and it didn't help:
-> Stop the Automatic Updates service and BITS service.
net stop wuauserv

net stop bits

-> Delete "%windir%\softwaredistribution" directory.
-> Start the Automatic Updates service and BITS service. When these two services have been started, they will auto-create "softwaredistribution" and its subfolder at system directory.
net start wuauserv

net start bits

-> After the "%windir%\softwaredistribution" directory has been generated, please let the client contact the WSUS server immediately.
wuauclt.exe /resetauthorization /detectnow

-> After 15 minutes, please check the client to confirm whether it detects needed updates.
Edit 14.IX.2012 @ 9.59 CT
1) Okay, I ran nslookup on the WSUS server:
Server:  xxxx.xxxxxxx.local
Address:  x.x.x.2

Name:    xxx-xxx.xxxxxxx.local
Address:  x.x.x.36

2) I pinged the WSUS server (name):
Pinging xxx-xxx.xxxxxx.local [x.x.x.36] with 32 bytes of data:

Reply from x.x.x.36: bytes=32 time=1ms TTL=128
Reply from x.x.x.36: bytes=32 time<1ms TTL=128
Reply from x.x.x.36: bytes=32 time<1ms TTL=128
Reply from x.x.x.36: bytes=32 time<1ms TTL=128

Ping statistics for x.x.x.36:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 1ms, Average = 0ms

3) I pinged the WSUS server (IP):
Pinging x.x.x.36 with 32 bytes of data:

Reply from x.x.x.36: bytes=32 time<1ms TTL=128
Reply from x.x.x.36: bytes=32 time<1ms TTL=128
Reply from x.x.x.36: bytes=32 time<1ms TTL=128
Reply from x.x.x.36: bytes=32 time<1ms TTL=128

Ping statistics for 10.3.1.36:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms

I don't believe it's a DNS issue, but I might be mistaken.  Anything you need to run to check DNS issue?
Comment: 1. Why would you be manually configuring Windows Update on a computer joined to the domain when you should be using GPO to configure Windows Update? 2. Have you confirmed that your Windows Update GPO is being applied to the computer in question?
Comment: OK, the computer should show up in the All Computers group as well as the target group. If it's not showing up in the All Computers group, then I would suspect that the GPO isn't being applied. Have you run gpresults or RSOP for the computer in question to verify that the GPO is being applied? Also, you know that that is a WSUS group not an AD group, right?
Comment: Can the XP client resolve the WSUS server name as configured in your GPO?
Comment: @joeqwerty Yes, I am sorry, I should have mentioned it in my post.  GPO is applied to workstation and that laptop is a part of that group.
Comment: George, joeqwerty meant to ask: do you assign the update server and group within the GPO?  Regardless, post results of [the diag tool](http://download.microsoft.com/download/9/7/6/976d1084-d2fd-45a1-8c27-a467c768d8ef/WSUS%20Client%20Diagnostic%20Tool.EXE) (refer to [the readme](http://download.microsoft.com/download/e/4/b/e4bc4153-be1f-460f-800e-69c6a1857d68/readme.htm) ).
Comment: @joeqwerty I know the difference.  & that's the issue, it should... but it does...
Comment: @mbrownnyc I posted the results.  I googled that error & followed the instructions I listed to no luck...
Comment: joeqwerty points out, looks like you've got a DNS problem.
Comment: @joeqwerty Just added an edit.  I don't think it's a DNS issue.
Comment: @mbrownnyc Thanks for your help, but like I said I don't think it's a DNS issue.
Comment: @George, It's not clear to me from your edit where you ran the nslookup and ping test from. Did you run them from the XP computer?
Comment: @joeqwerty Yes, from the XP computer in question.
Comment: OK. Can you open/access the WSUS URL from the XP computer?
Comment: @joeqwerty Yes.
Comment: "The 0x80072EE7 error code may occur if the client computer cannot find the correct IP address when it tries to resolve a URL for the Windows Update Web site or for the Microsoft Update Web site. This error may occur if the Hosts file contains a static IP address." [(source)](http://support.microsoft.com/kb/883821).  Use [the network troubleshooter](http://support.microsoft.com/kb/308007) and post results. Or use netdiag.exe from [this](http://www.microsoft.com/en-us/download/details.aspx?id=18546).  Or just use [this fixit](http://support.microsoft.com/kb/883821#FixItForMeAlways0x80072EE7).
Comment: @mbrownnyc it's a 50 page result report from netdiag.exe, I am not going to post it here, it'll be time consuming for anyone to look through. Anything in particular you want me to post here, out of that report?
Comment: You tell me.  You see the word "error" or "warning" in that report?  Anything interesting to you (as a professional IT person)?  What about a problem with the HOSTS file?
Comment: You seem to be using a proxy. Maybe anything to do with that?
Answer: Clearly you can ping a server, but you can't communicate with WSUS on the WSUS port.
Been a while since I used WSUS 2.0, and I can't remember if I was using port 80 or some other port, but I always specified the port that I was using:
"WUStatusServer"=http://wsusserver:8530

-- and you need to check the spelling of your server name in the GPO: that's an easy mistake to make.
You need to check what port the server is using, and that nothing else has grabbed that port, and that the firewall at both server and client allows connection on that port.


for loop prints out all contents not just the last added into list box... any reason why?

Question: for loop prints out all contents not just the last added into list box... any reason why??
def changeCss():
    readingCss = open(FileName.get()+'.css','r')
    FileContentsCss = readingCss.readlines()
    readingCss.close()
    index = 0
    while index < len(FileContentsCss):
        FileContentsCss[index]= FileContentsCss[index].rstrip('\n')
        index +=1
    while '' in FileContentsCss:
        FileContentsCss.remove('')
    for cont in FileContentsCss:
        Open.insert(END, cont + '\n')

Comment: Note about style: variable names should start with a lowercase letter.
Answer: Explanation: On for loop
The for loop iterates through all the elements in a list
Example:
list1 = ['hello', 'world']
for ele in list1:
    print(ele)

or
Using slicing, we can specify the start index and end index to make for loop iterate through all the elements between those indexes
l1 = ['hello', 'world', 'good']
for a in l1[1:3]:
    print(a)

For the above query if you want to print the last added element in the list:
l1 = ['hello', 'world', 'good']
l1.append('morning')
for a in l1[-1::1]:
    print(a)

Output:
morning


403 error with large media files on django server running nginx

Question: I'm running a Django server hosted on DigitalOcean using Nginx and Gunicorn. I tried adding a 2MB picture via the admin interface when I get hit with a 403 error. Looking into error.log indicated permission was denied, as follows:
2017/06/27 01:03:29 [error] 1643#1643: *30 open() "/home/brian/nydkc11/nydkc11/nydkcd11/media/image_main/dtc1.jpg" failed (13: Permission denied), client: 126.96.36.199, server: nydkc11.org, request: "GET /media/image_main/dtc1.jpg HTTP/1.1", host: "nydkc11.org", referrer: "http://nydkc11.org/admin/blog/image/7/change/"

The weirdest thing, however, is that smaller image files work just fine (around 18 kb or so). Anyone know why larger media files may be triggering the problem, and how I should fix it?
I had to set client_max_body_size to 100M in my nginx.conf, if that's a useful thing to know.
Comment: There is a django default setting which causes files greater than 2.5 Mb to be streamed to a temp folder (in stead of processing them in memory). That might be the cause for your issue. How big exactly is your file, and what happens in your upload files of about 1-2 Mb in size?
Comment: It's 3MB. I haven't uploaded files in the 1 ~ 2MB size, but files in the KB range work just fine. Any way to change that default setting by any chance?
Comment: The setting is DATA_UPLOAD_MAX_MEMORY_SIZE, with a default value of 2621440 (which is 2.5Mb). So if you want to adjust it to 10Mb, just multiply by four. This worked for a project I had deployed to Heroku.
Comment: That wasn't able to fix the problem. But the weirdest thing was that uploading the same file under `runserver` worked just fine.
Answer: I just came across the exact same problem. Thanks for your SO thread, otherwise I'd still be searching in the wrong place.
To fix this, you actually do not need to set DATA_UPLOAD_MAX_MEMORY_SIZE as long as you're only experiencing this error when uploading files. The Django documentation links to the other value, FILE_UPLOAD_MAX_MEMORY_SIZE, here.
Setting FILE_UPLOAD_MAX_MEMORY_SIZE to a higher limit in my settings.py resolves the problem, alongside with the aforementioned client_max_body_size in nginx.conf.
This sets the upload maximum to roughly 200 MB:
FILE_UPLOAD_MAX_MEMORY_SIZE = 200000000
Comment: This seems to be a bug in Django's TemporaryFileUploadHandler
Answer: larger files(>2.5M) are stored using temporary files, which will get 0o600 permissions by default. The problem can easily be fixed by setting a value to FILE_UPLOAD_PERMISSIONS
Set this in settings.py
FILE_UPLOAD_PERMISSIONS = 0o644

Reference
See For Python2
See Documentation


When I install SQL Server 2012 Express I do not see the SQL Server Management Studio

Question: When I install SQL Server 2012 Express I do not see the SQL Server Management Studio when I look for it via Start -> All Programs -> SQL Server 2012 Express.
Answer: Well, which version of SQL Server 2012 Express did you install??

there's the bare-bones engine - just the engine, nothing else
(Express (Containing only the database engine))
there's the SQL Server 2012 Express With Tools version which includes and installs Management Studio
there's the SQL Server 2012 Express Advanced Services version (which I believe doesn't include Management Studio)

So which one did you install? If you got the bare-bones one : yes, that doesn't include Management Studio. Either download the With Tools edition, or install Management Studio separately.


Download spring reference documentation

Question: Since the redesign of springsource.org, I am no long able to find the reference documentation available for download.  Previously, you could download the source archive (which contained all the code) and it would also have the reference docs available for offline use.  This was really helpful.
Is this available somewhere else now?  As a note, I'm looking for the reference documentation (the user guide - i.e. what is found at http://docs.spring.io/spring/docs/3.2.4.RELEASE/spring-framework-reference/html/) - not the API (javadoc) docs...those are available via maven central.
Comment: https://zealdocs.org is a nice tool for downloading a variety of offline documentations, the Spring Framework being among them.
Comment: http://docs.spring.io/spring/docs/3.2.4.RELEASE/spring-framework-reference/pdf/spring-framework-reference.pdf for the PDF version.
Comment: Their servers seems to fall a lot.
Answer: You can get a directory listing when you delete part of the path.
An archived copy of the Spring Framework Reference Documentation (for version 4.1.0) can be found here.
Comment: Yeah - I actually want the individual (separate) html files...not the single html file or the pdf file (either of which are easily downloadable).  Problem is that if you go to http://docs.spring.io/spring/docs/3.2.4.RELEASE/spring-framework-reference/html/, the index page is served - instead of the directory listing.
Comment: Though I may just have to suck it up and use the single HTML file (I don't like to though - because it's so big it gets unwieldy to search through when I'm looking for something)

Download spring reference documentation


Gaspard de la Nuit: Scarbo fingering

Question: Does anyone have any suggestions for fingering and for practicing the scale-run at measure 228 in Scarbo?  I am working on all three movements and have had particular trouble with this quick run.  I cannot seem to get that fast, effortless, continuous stream of notes down.  As it descends the keys, I am fine and can go fairly quickly.  But, the trouble is doing that 5 against 3 arpeggio that ascends to the high keys.  I can't get that wet and intense sound in the bottom notes to contrast with a delicate and dry top notes.  I know one of the answers is practice, but I'm trying to make my practice more efficient.  Same question goes for a similar run in measure 253.
Lastly, does anyone have fingering suggestions for the majors seconds in measure 460?  I have actually been using my thumb to play two white notes and my second and third finger to play the black notes.  Thoughts?
Comment: Yes, using the thumb on two white keys simultaneously is exactly the kind of *cochonnerie* that Ravel would write. In fact, the edition I have is explicitly annotated 11-23-11-23.
Answer: With regards to the runs, the fingering I recommend is as follows:

For the downwards run:

Right Hand: G#: 5, D#: 2, B: 1, F#: 5, C#: 2, A: 1 (repeat each time)
Left Hand: G#: 1, F#: 2, C#: 4, A: 5 (repeat each time)

For the upwards run:

Right Hand: A: 1, C#: 2, F#: 4 (repeat each octave)
Left Hand: Bottom F#: 4, Bottom A: 2, Bottom D: 1, from then on:

F#: 4, G#: 3, A: 2, D: 1 (repeat each octave).

The same fingering works for the next set of runs too.
I think in terms of the fluidity, the most important thing is to lean enough. If you lean to your right at the beginning of the downwards run, and travel to the left as the run descends, you are moving your body to in front of the notes, and so it should be no more difficult than if you are playing these figures around middle C. Leaning up and down the piano to enable your reaching of the notes is essential to achieve the fluidity you are after when playing Ravel. The same goes for leaning and travelling the other way for the upwards runs.
With regards to the sound of the upwards run, from the sound you are describing you want, this sounds like a combination of dexterity practice (I recommend practising the run slowly and staccato to get the touch) and then using a touch of pedal towards the bottom (something around 1/4 depth pedalling just to thicken the sound at the bottom).
As for the major seconds, using the thumb on all the pairs of white notes and 2/3 on the black is the fingering the Durand edition uses, and it works very well for the whole style (provided you still create a sense of line and don't thump the thumbs!).
Hope this helps!

Gaspard de la Nuit: Scarbo fingering


android get path of recorded video/audio

Question: I let the user record a video/audio by doing following:
<code>Intent videoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        startActivityForResult(videoIntent, VIDEO_REQUEST);
         //pretty the same thing for audio
</code>
I'm not sure what to do in the onActivityResult() method to get the Uri of the recorded file and then convert it to an absolute path like /mnt/sdcard/DCIM/Camera/1231.avi
Any help is appreciated.
Answer: Try my program wherein you will get how to get the Path.The Link is as follows:-Imp Link.


Is it possible to call a function inside another function in Python? (Web-Scraping problem)

Question: I'm working on a web-scraping task and I can already collect the data in a very rudimentary way.
Basically, I need a function to collect a list of songs and artists from the Allmusic.com and then add the data in df. In this example, I use this link: https://www.allmusic.com/mood/tender-xa0000001119/songs
So far, I managed to accomplish most of the objective, however, I had to perform two different functions (def get_song() and def get_performer()).
I would like, if possible, an alternative to join these two functions.
The codes used are below:
import requests
from bs4 import BeautifulSoup

headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0'}
link    = "https://www.allmusic.com/mood/tender-xa0000001119/songs"

# Function to collect songs (title)
songs = []

def get_song():
url = link
source_code = requests.get(url, headers=headers)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for td in soup.findAll('td', {'class': 'title'}):
    for a in td.findAll('a')[0]:
        song = a.string
        songs.append(song)

# Function to collect performers
performers = []

def get_performer():
url = link
source_code = requests.get(url, headers=headers)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for td in soup.findAll('td', {'class': 'performer'}):
    for a in td.findAll('a'):
        performer = a.string
        performers.append(performer)

get_song(), get_performer() # Here, I call the two functions, but the goal, if possible, is to use one function.

df = pd.DataFrame(list(zip(songs,performers)), columns=['song', 'performer']) # df creation

Comment: You can wrap your two functions in another function that will call them. E.g., `get_data`. In the particular case, the interest of limited though...
Comment: Does this answer your question? [Call a function with argument list in python](https://stackoverflow.com/questions/817087/call-a-function-with-argument-list-in-python)
Answer: You can just add the soup.findAll code from performer in the first function.
    import requests
    from bs4 import BeautifulSoup
    import pandas as pd

    headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0'}
    link    = "https://www.allmusic.com/mood/tender-xa0000001119/songs"

    # Function to collect songs (title)
    songs = []
    performers = []

    def get_song_and_performer():
        url = link
        source_code = requests.get(url, headers=headers)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)
        for td in soup.findAll('td', {'class': 'title'}):
            for a in td.findAll('a')[0]:
                song = a.string
                songs.append(song)
        for td in soup.findAll('td', {'class': 'performer'}):
            for a in td.findAll('a'):
                performer = a.string
                performers.append(performer)

get_song_and_performer() # Here, I call the two functions, but the goal, if possible, is to use one function.

df = pd.DataFrame(list(zip(songs,performers)), columns=['song', 'performer']) # df creation

Answer: You could create a seperate function for getting song info; this would be the most organized way to do this, if you want to keep the functions seperate.
import requests
from bs4 import BeautifulSoup

headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0'}
link    = "https://www.allmusic.com/mood/tender-xa0000001119/songs"

# Function to collect songs (title)
songs = []

def get_song():
    url = link
    source_code = requests.get(url, headers=headers)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for td in soup.findAll('td', {'class': 'title'}):
        for a in td.findAll('a')[0]:
            song = a.string
            songs.append(song)

# Function to collect performers
performers = []

def get_performer():
    url = link
    source_code = requests.get(url, headers=headers)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for td in soup.findAll('td', {'class': 'performer'}):
        for a in td.findAll('a'):
            performer = a.string
            performers.append(performer)

# Function for getting song and performer
def get_song_info():
    get_song()
    get_performer()

get_song_info() # Call just one function!

df = pd.DataFrame(list(zip(songs,performers)), columns=['song', 'performer']) # df creation

Answer: To get titles/performer you can use next example:
import requests
import pandas as pd
from bs4 import BeautifulSoup

url = "https://www.allmusic.com/mood/tender-xa0000001119/songs"
headers = {
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
}

soup = BeautifulSoup(requests.get(url, headers=headers).content, "html.parser")

all_data = []
for td in soup.select("td.title"):
    title = td.get_text(strip=True)
    performer = td.find_next("td").get_text(strip=True)
    all_data.append((title, performer))

df = pd.DataFrame(all_data, columns=["title", "performer"])
print(df)
df.to_csv("data.csv", index=False)

Prints:
                              title                          performer
0                    Knock You Down                        Keri Hilson
1   Down Among the Wine and Spirits                     Elvis Costello
2                  I Felt The Chill                     Elvis Costello
3            She Handed Me A Mirror                     Elvis Costello
4         I Dreamed Of My Old Lover                     Elvis Costello
5                   She Was No Good                     Elvis Costello
6                  The Crooked Line                     Elvis Costello
7                 Changing Partners                     Elvis Costello
8           Small Town Southern Man                       Alan Jackson
9                    Find Your Love                              Drake
10            Today Was a Fairytale                       Taylor Swift
11                     Need You Now                             Lady A
12                   American Honey                             Lady A
13                      Peace Dream                        Ringo Starr
14                  If I Died Today                         Tim McGraw
15                            Still                         Tim McGraw
16                      I Need Love                             Ledisi
17                          Uhh Ahh                        Boyz II Men
18                  Shattered Heart                             Brandy
19            Right Here (Departed)                             Brandy
20           Warm It Up (With Love)                             Brandy
21                  If I Were a Boy                            Beyoncé
22                Why Does She Stay                              Ne-Yo
23              Daddy Needs a Drink                  Drive-By Truckers
24                  Think About You                        Ringo Starr
25                      Liverpool 8                        Ringo Starr
26                        Nefertiti                     Herbie Hancock
27                            River  Herbie Hancock/Corinne Bailey Rae
28                   Both Sides Now                     Herbie Hancock
29                  Court and Spark         Herbie Hancock/Norah Jones
30  I Taught Myself How to Grow Old                         Ryan Adams
31                           Ghetto           Kelly Rowland/Snoop Dogg
32                      Little Girl                   Enrique Iglesias
33          The Magdalene Laundries                     Emmylou Harris
34                   Because of You                              Ne-Yo
35               We Belong Together                       Mariah Carey
36          Thank You for Loving Me                           Bon Jovi
37        He's Younger Than You Are                      Sonny Rollins

and saves data.csv (screenshot from LibreOffice):
Answer: For your url, you can use pd.read_html:
source_code = requests.get(link, headers=headers)
df = pd.read_html(source_code.text)[0]  # <- Only one table in the page

Output:
>>> df
                     Title/Composer                            Performer   Stream
0                    Knock You Down                          Keri Hilson  Spotify
1   Down Among the Wine and Spirits                       Elvis Costello      NaN
2                  I Felt The Chill                       Elvis Costello      NaN
3            She Handed Me A Mirror                       Elvis Costello      NaN
4         I Dreamed Of My Old Lover                       Elvis Costello      NaN
5                   She Was No Good                       Elvis Costello      NaN
6                  The Crooked Line                       Elvis Costello      NaN
7                 Changing Partners                       Elvis Costello      NaN
8           Small Town Southern Man                         Alan Jackson  Spotify
9                    Find Your Love                                Drake  Spotify
10            Today Was a Fairytale                         Taylor Swift  Spotify
11                     Need You Now                               Lady A  Spotify
12                   American Honey                               Lady A      NaN
13                      Peace Dream                          Ringo Starr  Spotify
14                  If I Died Today                           Tim McGraw  Spotify
15                            Still                           Tim McGraw  Spotify
16                      I Need Love                               Ledisi  Spotify
17                          Uhh Ahh                          Boyz II Men  Spotify
18                  Shattered Heart                               Brandy  Spotify
19            Right Here (Departed)                               Brandy  Spotify
20           Warm It Up (With Love)                               Brandy  Spotify
21                  If I Were a Boy                              Beyoncé      NaN
22                Why Does She Stay                                Ne-Yo  Spotify
23              Daddy Needs a Drink                    Drive-By Truckers  Spotify
24                  Think About You                          Ringo Starr      NaN
25                      Liverpool 8                          Ringo Starr      NaN
26                        Nefertiti                       Herbie Hancock  Spotify
27                            River  Herbie Hancock / Corinne Bailey Rae  Spotify
28                   Both Sides Now                       Herbie Hancock  Spotify
29                  Court and Spark         Herbie Hancock / Norah Jones  Spotify
30  I Taught Myself How to Grow Old                           Ryan Adams  Spotify
31                           Ghetto           Kelly Rowland / Snoop Dogg      NaN
32                      Little Girl                     Enrique Iglesias  Spotify
33          The Magdalene Laundries                       Emmylou Harris  Spotify
34                   Because of You                                Ne-Yo  Spotify
35               We Belong Together                         Mariah Carey  Spotify
36          Thank You for Loving Me                             Bon Jovi  Spotify
37        He's Younger Than You Are                        Sonny Rollins  Spotify


Is there a simple way of getting an xyz array from xarray dataset?

Question: Is there a simple way of getting an array of xyz values  (i.e. an array of 3 cols and nrows = number of pixels) from an xarray dataset? Something like what we get from the rasterToPoints function in R.
I'm opening a netcdf file with values for a certain variable (chl). I'm not able to add images here directly, but here is a screenshot of the output:
Xarray dataset structure
I need to end with an array that have this structure:
[[lon1, lat1, val],
 [lon1, lat2, val]]

And so on, getting the combination of lon/lat for each point. I'm sorry if I'm missing something really obvious, but I'm new to Python.
Answer: I can suggest you a small pseudo-code:
import numpy as np
lons = ds.variables['lon'].load()
lats = ds.variables['lat'].load()
chl = ds.variables['chl'].load()
xm,ym = np.meshgrid(lons,lats)
dataout = np.concatenate((xm.flatten()[np.newaxis,:],ym.flatten()[np.newaxis,:],chla.flatten()[np.newaxis,:]),axis=0)

Might be it does not work out-of-the box, but at least one solution could be similar with this.
Answer: The natural format you are probably looking for here is a pandas dataframe, where lon, lat and chl are columns. This can be easily created using xarray's to_dataframe method, as follows.
import xarray as xr
ds = xr.open_dataset("infile.nc")
df = (
     ds
     .to_dataframe()
     .reset_index()
     )


Proving $\forall x\forall y Fxy ∴ \exists xFxx$

Question:
Construct a proof for the argument:
$$\forall x\forall y Fxy ∴ \exists xFxx$$

I try to start with Fay universal instantiation
But proof-checker keeps telling me im wrong?
I'm not really sure how to start this proof
I have to do the proof on proof-checker.org
These are the rules im allowed to use:

modus ponens  ->E
modus tollens MT
modus tollendo ponens DS
double negation   DNE
addition  vI
adjunction    ^I
simplification    ^E
bicondition   <->I
equivalence   <->E
repeat    Rep
conditional derivation    ->I
reductio ad absurdum  RAA
universal instantiation   AE
universal derivation  AI
existential instantiation EE
existential generalization    EI
Comment: I find your series of logic questions and the proof-checker tool interesting, and I started to look into your questions first on [$P\wedge(Q\vee R)\therefore (P\wedge Q)\vee (P\wedge R)$](https://math.stackexchange.com/q/4499435/89922) and then on [$\neg(R\vee S), P\to R, Q\to S\therefore \neg(P\vee Q)$](https://math.stackexchange.com/q/4499497/89922) before you deleted them. Surely the formatting has room for improvement, but why do you keep deleting fine questions as soon as you solved them?
Comment: Deleting answered questions is generally bad. You should really respond to @peterwhy 's question.
Comment: I was trying with the tool and found proofs for both of the previous questions, but typing and formatting in this site took time. If the questions would disappear randomly, why should I waste time to try and figure future questions out?
Comment: @D.Dmitriy My guess is, the OP is using a system which implicitly assumes the domain of discourse is nonempty.  Indeed, if you allowed for an empty domain of discourse, the sequent would not be valid.
Comment: @WoodsStashGang - If you figure out an answer to your own question, it is 100% permitted to post the answer to your question, and it's actual the politest way to deal with it. Let others enjoy the results of your work too!
Comment: I deleted them because none helped me.
If I figured out my own question, why would I leave up the question and waste time for someone else to try and figure it out?
Comment: Is the statement you're trying to prove written correctly? My formal logic is not strong, but it looks unprovable or false to me.
Comment: Yes it's written correctly
Comment: Thanks @WoodsStashGang, I see that you undeleted one previous question. Maybe you will be able to [accept your answers and resolve these questions](https://math.stackexchange.com/help/self-answer).
Answer: Okay so the problem was trying to start with $Faa$.
Solution:

Premise = $\forall x \forall y Fxy$
$\forall y Fay$ 1 Universal instantiation
$Faa$  2 Universal instantiation
$\exists x Fxx$  3 Existential generalization


Search all pcap files in a folder and sub-folders for a certain condition

Question: I have a folder (containing many sub-folders) full of pcap files and I'd like to get all pcap files containing packets that match a certain condition, for example "have source IP 22.214.171.124". Do you know any tool that does that kind of search?
I need this both for Windows and Ubuntu
Answer: PcapSearch does exactly what you need. It's part of the PcapPlusPlus library and it's cross-platform so it'd work on Windows and Linux
In your case use it as follows (Linux case):
<code>./PcapSearch -d /your/folder/ -s "ip src 126.96.36.199"
</code>
you can also use the -r switch to write results to a file, it'll also print the match packets to that report
EDIT: if you don't want or can't compile this utility, please take a look at PcapPlusPlus recent release, it contains binaries for quite a lot of platforms such as Windows, Ubuntu (12.04/14.04) and Mac OS X (Mavericks/Yosemite/El Capitan)
Comment: Thanks for the quick answer! it's exactly the tool I was looking for


Drawing over desktop in C#

Question: I've seen a few similar questions, but nothing doing exactly what I need.
I'm looking to create something similar to the old Sheep.exe program which had a little sheep on top of all of the windows that could walk around.
I found two possible solutions:
The first is to draw to the desktop's HDC. The problem is that it's not my DC and I can't control when stuff is refreshed.
The other solution would be using transparent windows. I want to have a bunch of independent images (that interact). I'm not sure whether I should use a transparent window that fills the entire screenspace and draw multiple images to that or if I should create a individual window for each image (which gets extremely inefficient when there's a lot of images.
What would be the most optimal way to go about this?
Answer: WPF: Main window of application always on top, always maximized, background transparent, then start overlaying/animating to your hearts content.
Comment: Use of Expression Blend makes the task very easy
Comment: Do not set background to null unless there is a specific reason. In general, set it to Black or White, and set the Alpha channel to 0.
Answer: You can use WPF as a solution. In order to do so, you need to make sure you set the Background to {x:null} along with the AllowsTransparency="True"
Example:
<code><Window x:Class="WPFMe.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="1024" Width="768" AllowsTransparency="True" WindowStyle="None" Background="{x:Null}">
    <Grid>

    </Grid>
</Window>
</code>

Drawing over desktop in C#


Dafny - Loop invariant for nested loops

Question: I am trying to create a Dafny program that returns true if and only if, A contains no duplicates.
This is what I have so far, however the invariant invariant r <==> (forall j :: 0 <= j  A[j] != A[i]); says that it will not hold on entry.
Any advice on what I am doing wrong?
`method CheckArr1(A: array<int>) returns (r: bool)
requires A.Length > 0
ensures r <==> (forall i, j :: 0 <= i < A.Length && 0 <= j  A[i] != A[j]);
{
    var i := 0;
    r := true;
    while i < A.Length
    decreases A.Length - i;
    invariant i <= A.Length;
    invariant r <==> (forall x, y :: 0 <= x < i && 0 <= y  A[x] != A[y]);
    {
        var j := 0;
        while j < i
        decreases i - j;
        invariant j <= i;
        invariant r <==> (forall j :: 0 <= j  A[j] != A[i]);
        {
            r := (r && (A[j] != A[i]));
            j := j + 1;
        }
        i := i + 1;
    }
}`

Answer: The "invariant doesn't hold on entry" error is for the declared invariant
r <==> (forall j :: 0 <= j  A[j] != A[i])

of the inner loop. On entry to the that loop, j is 0, so the condition that needs to hold on entry to the inner loop is
r <==> (0 <= 0  A[0] != A[i])

which we can simplify to
r <==> (0  A[0] != A[i])           // (*)

There is no reason to believe that r will hold this value on entry to the inner loop. All you know inside the body of the outer loop is that
r <==> (forall x, y :: 0 <= x < i && 0 <= y  A[x] != A[y]) // (**)

which says that r tells you whether or not there are any duplicates within the first i elements. Condition (*) says something about a[i], whereas (**) does not say anything about a[i].
From your current program, it would be easier if you changed the inner loop to use a different variable, say s, to achieve the invariant you have given. That is, use the invariant
s <==> (forall j :: 0 <= j  A[j] != A[i])

Then, after the inner loop, update r using the value you computed for s.

Dafny - Loop invariant for nested loops


jQuery Select2 android hide keyboard

Question: We created responsive website where we are using select2. On desktop it is working very good, but on android once keyboard appears we cannot hide it.
How can we do that.
Comment: Want to know why down voted. This is really rude.
Comment: You should post some code with example what you mean exactly.
Answer: Thank you very much for rude replies and down votes.
But I came out with workaround. First I detect device is touch or normal by below code
<code> var isTouchDevice = 'ontouchstart' in document.documentElement;
</code>
Then I declare normal variable and assign it with zero and in next line if the device is touch device than I will assign -1. By this I can hide and unhide search box in select2. which in turn don't show keyboard on touch devices.
<code>var m = 0;
m = isTouchDevice === true ? -1 : 0;
 $("#selacity1").select2({
  minimumResultsForSearch: m,
  width: 210
});
</code>
It will help to somebody.
Once again thank you for down votes.
Comment: i have tried your solution but it's not worked on android browser. this option prevents the filter textbox, but the first tap opened and automatically closed the dropdown, then second tap opens permanently. for your information
Comment: Not working, it just hide the search box in select2 but keyboard does not hide.

jQuery Select2 android hide keyboard


output of for loop as a matrix MATLAB

Question: the following function gives as output a 3x3 matrix
S=myfunction(i,3)

I would like to know please if there is a way to stock the output of the following loop in a way that I can recall the matrix from each step.
 for i=1:8
 S=myfunction(i,3)
 end

This loop at each step gives a different matrix and I would like to give a name to each matrix from each step for exampe S1, S2 , S3 ..
Is this possible? or should I save the result in a 3 x (24) huge matrix?
Thank you
example of output:
 for i=1:8
 S=myinfluence(i,3)
 end

 S =

'HH'    'HH'    'HH'
'HH'    'HH'    'HH'
'HH'    'HH'    'HH'

Comment: there are higer dimensional matrices
Answer: The easy way seems to me is to have a three dimensional matrix, and just index along the third dimension to save the intermediate result.
for i = 1:8
  S(:, :, i) = myinfluence(i,3);
end

then you can access each iteration by calling  S(:, : , 1) or S(:, : , 2) or S(:, : , 3) and so on.
using the : as an index means that all of the entries along the appropriate index of the right hand side of assignment will be  automatically copied to the corresponding index in the left hand side of assignment.

output of for loop as a matrix MATLAB


Correlation of signs of a jointly Gaussian RV

Question: Given $$\left(\begin{array}{c} X_1 \\ X_2 \end{array}\right) \sim \mathcal{N} \left(\left(\begin{array}{c} 0 \\ 0 \end{array}\right), \left(\begin{array}{cc} 1 & \rho \\ \rho & 1 \end{array}\right)\right),$$
I want to show that $$\mathbb{E}\left[ \text{sign}(X_1) \text{sign}(X_2)\right] = \frac{2}{\pi}\sin^{-1}(\rho)$$
This seems to be the essence of the proof of Geomans-Williamson MAX-CUT SDP relaxation. Is there an easy way to see it?
Answer: For convenience let's call $\operatorname{sgn}(X_1),\operatorname{sgn}(X_2)$ as $S_1$ and $S_2$, respectively.
There are only $9$ possible combinations of $(S_1,S_2)$: $(\pm1,\pm1)$, and at least one of the $S$ being $0$. Now, since we are looking for $E[S_1S_2]$, ignoring the states of $S=0$ will not affect the result. Hence, \begin{align*}E[S_1S_2]&=1\times P(S_1=1,S_2=1)+1\times P(S_1=-1,S_2=-1)\\
&\quad+(-1)\times P(S_1=1,S_2=-1)+(-1)\times P(S_1=-1,S_2=1)\\
&=1\times P(X_1>0,X_2>0)+1\times P(X_1<0,X_2<0)\\
&\quad+(-1)\times P(X_1>0,X_2<0)+(-1)\times P(X_1<0,X_2>0).\end{align*}
Further, one can show that $$P(X_1>0,X_2>0)=P(X_1<0,X_2<0)=\frac{1}{4}+\frac{1}{2\pi}\sin^{-1}(\rho),$$ and $$P(X_1>0,X_2<0)=P(X_1<0,X_2>0)=\frac{1}{2\pi}\cos^{-1}(\rho).$$ So \begin{align*}E[S_1S_2]&=\frac{1}{2}+\frac{1}{\pi}\sin^{-1}(\rho)-\frac{1}{\pi}\left(\frac{\pi}{2}-\sin^{-1}(\rho)\right)\\
&=\frac{2}{\pi}\sin^{-1}(\rho).\end{align*}
Comment: @Devil: it's possible to turn integrations into trigonometric inequalities with the help of Box-Muller transformation, [this thread](http://math.stackexchange.com/questions/255368/getting-px0-y0-for-a-bivariate-distribution) may help.
Comment: Is there an easy way to see the integral? That was where I was stuck before as well. All references I see seem to do it the messy way.
Answer: $$\mathbb{E}[ \text{sign}(X_1) \text{sign}(X_2)] = 1 * (P(X_1 \ge 0,X_2 \ge 0) +  P(X_1 \le 0,X_2 \le 0)) - (P(X_1 \ge 0,X_2 \le 0) + P(X_1 \le 0,X_2 \ge 0))$$ which in turn $$= 2P(X_1 \ge 0,X_2 \ge 0) - 2P(X_1 \ge 0,X_2 \le 0)$$ by symmetry.
Plugging in the Bivariate Normal density, this evaluates (integrates) to $\frac{2}{\pi} sin^{-1}(\rho)$. The details of performing the integration are left to you.
Edit: Have changed what was $\sigma^2$ to $\rho$ to match edit of question.
Comment: +1 for that last comment since the implications of writing $\sigma^2$ are that the parameter cannot be negative and that it can exceed $1$.
Comment: Ah. I did not realise that. Have fixed it.


multiple queries in select sql

Question: $result = db_query("SELECT {node}.title, {content_type_answer}.field_question_nid, {content_type_answer}.nid FROM {node}, {content_type_answer} ORDER by nid ASC LIMIT %d, %d", 0, 3);
while($ref = db_fetch_object($otvet)) {
    $otvets[] = array($ref->field_question_nid, $ref->nid, $ref->title);
}

I have 2 content types: 1. question, 2. answer.
In {content_type_answer} i have a nodereference field - field_question_nid that gives me the node id of the referenced question and {content_type_answer}.nid - gives me the answer node id.
But the problem is in title, {content_type_answer} table doesn't has a title row. In a code above i've succesfully selected title row from {node} table :D But how to make condition - i need only {node}.title from nodes which have {content_type_answer}.nid?
Comment: Why are you coding it directly instead of using the Views Module?
Comment: OK, one way to do this is to create a view with a block display.  Have this view return answers based upon a nid by using the nid as an argument.  Since you can't pass an argument to a block, tell it to grab the default argument from the URL. Figure out what fields you want to display, and then set up via the Blocks Admin page to display this block on a page that displays a question.  This will provide Views with the nid you need to display the answer to the question on the same page as the question.  If you want to limit it to four answers, you can do that with views and its paging options.
Comment: you are describing a WHERE or a JOIN.  I'd let Views do it for you as you have a couple other issues in your code that suggest you aren't entirely comfortable with writing db access code.
Comment: Could you help with a piece of code?
Comment: i'm doing that in page.tpl.php. Because with views i cant display question and below answer on that question (node reference to question)
Comment: I am certainly not one to hide behind "best practices" as I've taken a dull ax and hacked at many a core module, but I can't believe putting db_query()s in your page.tpl.php is any way to go, so I really think you need to rethink this whole thing.  And I don't have an answer for you there.
Comment: Thanks, but i won't do that with views.. Can you give me a tip on how to make it with db_query?
Comment: This is surely what you were asking here http://drupal.stackexchange.com/questions/18099/need-sql-assistance.

You might want to think about expanding that question rather than focusing on this one, as you have had most of the work done there.
Answer: This is a job for Views.  To expound upon the comments, this is a screen shot of a quick view that will do this:

I created two quick content types, answer and question.  I used the body field just for expediency in both, and the only other field I added was a node reference called question in the answer type.
In the View, I filted on published nodes of type answer, the argument is that node reference field above, with the default coming from the URL.  I output the Title and Body field.  I set the paging options to 4 so that it would output a maximum of 4 answers to match the LIMIT in your query.  I didn't sort the output but you can do that if you want in Sort Criteria.
I created only one quick question and answer.  On my system, the question is nid 379, so:

putting that in as the argument, the view will output any answers (well, up to 4) with that nid as the node reference in question.  Create a block display for this, and you can have this displayed on your node page with the question.
Now, as you mention in the comments, if you are sure you want to do all of this yourself in your page.tpl.php file with db_query()s, feel free to scrape out the query Views has built for you from the preview.  In this case, that would be:
SELECT node.title AS node_title, node.nid AS nid, node_revisions.body AS node_revisions_body, node_revisions.format AS node_revisions_format FROM node node  LEFT JOIN content_type_answer node_data_field_question ON node.vid = node_data_field_question.vid LEFT JOIN node_revisions node_revisions ON node.vid = node_revisions.vid WHERE (node.status = 1) AND (node.type in ('answer')) AND (node_data_field_question.field_question_nid = 379 )

and modify it to your specific needs.

multiple queries in select sql


OpenStack Keystone | db_sync --check return exit code 1

Question: Hy,
I'm using Ansible OpenStack for deploy OpenStack test environment
On playbook setup-openstack.yml task os_keystone : Check current state of Keystone DB fails because exit code 1 from /openstack/venvs/keystone-20.1.0.dev9/bin/keystone-manage db_sync --check command

TASK [os_keystone : Check current state of Keystone DB]
  ***************************************************************************************** fatal: [infra1_keystone_container-3fe165e4]: FAILED! => {"changed":
  true, "cmd":
  ["/openstack/venvs/keystone-20.1.0.dev9/bin/keystone-manage", "d
  b_sync", "--check"], "delta": "0:01:42.935686", "end": "2019-10-28
  21:25:55.634598", "failed_when_result": true, "msg": "non-zero return
  code", " rc": 1, "start": "2019-10-28 21:24:12.698912", "stderr": "",
  "stderr_lines": [], "stdout": "", "stdout_lines": []}

With debug=True and use_stderr=True in keystone.conf
logs

root@infra1-keystone-container-3fe165e4:/etc/keystone# /openstack/venvs/keystone-20.1.0.dev9/bin/keystone-manage db_sync --check
  2019-10-28 21:41:49.802 7461 WARNING oslo_db.sqlalchemy.engines [-] SQL connection failed. 10 attempts left.: oslo_db.exception.DBConnectionError
  : (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
  2019-10-28 21:41:59.821 7461 WARNING oslo_db.sqlalchemy.engines [-] SQL connection failed. 9 attempts left.: oslo_db.exception.DBConnectionError:
   (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
  2019-10-28 21:42:09.830 7461 WARNING oslo_db.sqlalchemy.engines [-] SQL connection failed. 8 attempts left.: oslo_db.exception.DBConnectionError:
   (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
  2019-10-28 21:42:19.844 7461 WARNING oslo_db.sqlalchemy.engines [-] SQL connection failed. 7 attempts left.: oslo_db.exception.DBConnectionError:
   (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
  2019-10-28 21:42:29.859 7461 WARNING oslo_db.sqlalchemy.engines [-] SQL connection failed. 6 attempts left.: oslo_db.exception.DBConnectionError:
   (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
  2019-10-28 21:42:39.870 7461 WARNING oslo_db.sqlalchemy.engines [-] SQL connection failed. 5 attempts left.: oslo_db.exception.DBConnectionError:
   (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
  2019-10-28 21:42:49.884 7461 WARNING oslo_db.sqlalchemy.engines [-] SQL connection failed. 4 attempts left.: oslo_db.exception.DBConnectionError:
   (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
  2019-10-28 21:42:59.898 7461 WARNING oslo_db.sqlalchemy.engines [-] SQL connection failed. 3 attempts left.: oslo_db.exception.DBConnectionError:
   (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
  2019-10-28 21:43:09.913 7461 WARNING oslo_db.sqlalchemy.engines [-] SQL connection failed. 2 attempts left.: oslo_db.exception.DBConnectionError:
   (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
  2019-10-28 21:43:19.927 7461 WARNING oslo_db.sqlalchemy.engines [-] SQL connection failed. 1 attempts left.: oslo_db.exception.DBConnectionError:
   (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
  2019-10-28 21:43:29.940 7461 CRITICAL keystone [-] Unhandled error: oslo_db.exception.DBConnectionError: (pymysql.err.OperationalError) (2013, 'L
  ost connection to MySQL server during query')

Manually connect to database with credentials in keystone.conf from keystone lxc container works, but no table in keystone database
>
root@infra1-keystone-container-3fe165e4:/etc/keystone# /openstack/venvs/keystone-20.1.0.dev9/bin/keystone-manage --version
16.0.1
Answer: I had the same error during my deployment after having to re-run the setup-openstack playbook twice (because of an unrelated error).
I deployed my setup on baremetal (not containers) with mysqld + haproxy/keepalived. When I ran the playbook the 1st time, it appears keepalived/haproxy was stopped for some reason, meaning keystone couldn't access mysql when running the playbook for a 2nd time, causing the above error.
Try checking if your MySQL server is accessible from keystone's point of view. Hopefully this is helpful!
Answer: For me also same issue happened .I restarted keepalived service and then were able to ping the lb ip and also ran playbook successfuly


javac and java command in terminal

Question: I have a question below. I use JDK 17.
this is my codes.
package myPackage;

  public class myClass {

  public static void main(String[] args){

    System.out.println("test");
 }

}

1.When I write in IntelliJ terminal:
javac MyClass.java
java MyClass

Error:Could not find or load main class MyClass
java.lang.NoClassDefFoundError: myPackage/myClass(wrong name: MyClass)
2.When I write in IntelliJ terminal:
javac MyClass.java
java MyClass.java

Program run succesfully without any error.
May somebody explain me why this happen?
Edit:
This is directory and cmd commands
Comment: You've typed different commands -- `java MyClass`, which as the error message explains doesn't work because you left out the package, and `java MyClass.java` which uses the new ability of `java` to run a single class from the source file, without a compilation step.
Comment: so what is correct syntax without .java?
Comment: What's the first line of the `MyClass.java` file? Please [edit] your question to include the first few lines of the file _as text_ (not as image)
Answer:
java MyClass

This treats the argument as a Fully Qualified Name and looks that type up in the classpath. It does this by translating the FQN to a filename (replace all dots with slashes and stick .class at the end of it), so, /MyClass.class, and then looks for that file by appending that string to all entries on the classpath. This succeeds, in that . (the current directory) is likely on your classpath, and there is indeed ./MyClass.class - that is a real file.
However, this then fails: This class file is opened, read, and java only then notices: Ah, this is a class file describing myPackage.myClass, and I wanted MyClass, so while I found the file, I'm not going to run it.
To make it work, you'd have to run java myPackage.myClass (note the lower case m here), which will look for /myPackage/MyClass.class relative to all classpaths. For it to work it needs to [A] find the file, and [B] that file needs to be the product of compiling a file containing package myPackage; .... class myClass {} in it.

java MyClass.java

This is something completely different; javac treats this is as a special case (new functionality since Java 11), solely intended for very bare bones "I am learning java" / "Making a quick demo project". This bypasses all attempts to build a complete application and shortcuts the process: It opens that file, compiles it, and runs that class that was in it that was public, regardless of its actual name or package.
This 'mode' is triggered because the argument ends in .java and that file exists.
This does work and runs your code fine.
Comment: Thanks, I tried again as you advised.  But it didn't work. (package - myPackage, class in package - myClass)
Comment: "Did not work" isn't going to help. I shall counter with a similarly useless comment: "Well, it works for me". HINT: You need to be in `C:\foo\bar`, and un `java myPackage.myClass` from there, and then you need `C:\foo\bar\myPackage\myClass.class` to exist. Which you made by running `javac myClass.java` on a file with `package myPackage; class myClass {}` inside.
Comment: Thank for help, it couldn't work. I will add file directory and cmd in the post above. note: I removed package and commands work correctly.
Comment: You clearly do not understand the answer then; perhaps reread it? The right commands are, when in the dir that contains `myClass.java`: `javac myClass.java` `cd ..` `java myPackage.myClass`.

javac and java command in terminal


Erro ao criar array de strings

Question: Eu estou tendo problemas ao tentar inicializar um vector de strings o meu codigo se encontra assim:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    char *str[3];
    printf("DIGITE QUALQUER STRING: ");
    scanf("%s", str[0]);
    printf("%s\n", str[0]);
    printf("DIGITE OUTRA STRING: ");
    scanf("%s", str[1]);
    printf("%s\n", str[1]);
    printf("DIGITE MAIS OUTRA: ");
    scanf("%s", str[2]);
    printf("%s\n", str[2]);

    /*
    char *str[2];
    str[0] = "abc";
    str[1] = "cba";
    printf("%s\n", str[0]);
    printf("%s", str[1]);
    */
    return 0;
}

Quando eu compilo esse código o compilador não me retorna nenhum aviso e nenhum erro, quando eu o executo e entro com o primeiro valor ele para e sai do programa dai se eu diminuir o meu vetor para apenas 2 e entrar com o primeiro valor ele me retorna lixo de memoria e no segundo me retorna a string passada.
Se em vez de vetor eu fizer com apenas char *str uma string ele me retorna o valor passado normalmente eu estou tentando pegar o macete de alocação dinâmica tenho quase a certeza que eu estou fazendo alguma coisa de errado.
Comment: Você quer alocar a *string* no *stack* ou no *heap*?
Answer: Dá erro porque não está alocando espaço para as strings, só para seus ponteiros. Então ou muda para array e aloca na stack o que me parece mais conveniente para este caso ou use o malloc() para alocar no heap e retornar um ponteiro.
#include <stdio.h>

int main(){
    char str[3][30];
    printf("DIGITE QUALQUER STRING: ");
    scanf("%s", str[0]);
    printf("%s\n", str[0]);
    printf("DIGITE OUTRA STRING: ");
    scanf("%s", str[1]);
    printf("%s\n", str[1]);
    printf("DIGITE MAIS OUTRA: ");
    scanf("%s", str[2]);
    printf("%s\n", str[2]);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: bom o que eu queria fazer mesmo era criar um array de strings sem tem que usar um limite para o tamanho da string mas eu ja estou vendo que não é uma boa fazer isso. em relação a stack,pilha e alocação eu ainda não eu estou muito familiarizado com isso mas vlw pela ajuda
Answer: O post é velho, e já tem uma resposta correta, porém, acredito que possa ajudar novos usuários.
Não utilize scanf para pegar entrada do teclado. Scanf não tem um limite definido, se a entrada do usuário for maior que o espaço alocado, será possível realizar a técnica de buffer overlow.
Eu sugiro:
#include <stdio.h>

#define BUFFER_TAMANHO_MAXIMO 30

int main(void) {

        char str[3][BUFFER_TAMANHO_MAXIMO];

        // -1 para incluir o NULL_BYTE \0 no final da string.
        fgets(str[0], BUFFER_TAMANHO_MAXIMO - 1, stdin);
        puts(str[0]);
        return 0;
}

Erro ao criar array de strings


Views block template print individual field from content

Question: I created a view of paragraphs and I passed the parent ID as the contextual filter using a relationship to the content that use the field that reference the paragraph.
I can see the data been display and now I want to theme the output that I want to display on a block. I created a custom template file for the view block:

block--views-block--MY-VIEW-NAME-block-1.html.twig

and it is working. I can see the content of the view by adding:
{% block content %}
{{ content }}
{% endblock %}

But I would like to access the fields value individually. I have try the followings without luck:
content.field_name
content.field_name[0]
content.field_name[0].value

What am I missing?
Answer: I finally found the answer to this issue. Here it is in case some one is having the same issue.
The solution is insanely simple use the views fields template.
In my case I created a new template:
views-view-fields--VIEW-NAME.html.twig

And now you can access your fields values like this:
{{ fields.field_NAME.content }}

More details here
Enjoy.