Researcher ignored huge coefficients in research results. Why?

Question: I apologize beforehand. This is a stupid question.
I'm doing article review on one research paper, and I'm bamboozled by its results. The dependent variable in this OLS is the log of ratio with results ranging from -2 to 2. The research is focused on the connection between military effectiveness and economic development analyzing hundreds of battles in the last century. The part that I don't understand is how can researcher ignore the highlighted values and talking only about the effect of variable GDP per capita (and others, but this one is the most important).
My knowledge of statistics is limited. I can understand OLS somehow, but I have never seen this scenario before. I can't understand why the highlighted variables with huge coefficients don't overshadow every other variable to the point where you can't reliably research their influence, because possible error in "Artillery" variable is bigger than Beta of almost any other variables.
In case of more information needed, write a comment or see the article (section Empirical Analysis).
Answer: Even though the number is big compared to other, here, you should also consider the standard error (presumably the number in parentheses), which is also quite big. This measure shows the variability of the estimate : the lower, the better. The ratio of the value, i.e. $10.70/4.72 = 2.42$, which is significant (there is indeed a grand prize star!), is most helpful to envision the magnitude of the effect. Compared to this value, consider also the result : $.78/.21=3.71$ , which is somewhat much better (two stars!).
Not sure why the researcher(s) omitted the result. Maybe it was not of interest. My idea is that, because the effect vanished in model 2, they did not want to point it out. But I might be wrong, I only base my statement on this very table.


Trabalhar com datas vindas do MySQL/PHP

Question: Dentro de um select no banco, busco a data de validade do produto. Preciso que seja calculada mudando um status na resposta tipo 'a vencer', 'critico' e vencido'. Estou tentando fazer desta forma abaixo, mas estou meio enferrujado.
                        <?php
                    if($tabela == 'controle_insumos') {
                        $sql =  mysql_query("SELECT controle_insumos.*, prod01.* FROM controle_insumos INNER JOIN prod01 ON controle_insumos.rwc = prod01.procod LIMIT 200 ");
                    while ($result = mysql_fetch_array($sql) )
                    {
                    echo "
";
                    echo "".$result['rwc']."	";
                    echo "".$result['prodes']."	";
                    echo "".$result['quantidade']."	";
                    echo "".$result['pround']."	";
                    echo "";
                    echo date('d/m/Y', strtotime($result['data_compra']));
                    echo "	";
                    echo "";
                    echo date('d/m/Y', strtotime($result['fabricacao']));
                    echo "	";
                    echo "";
                    echo date('d/m/Y', strtotime($result['validade']));
                    echo "	";
                     $data2 = new DateTime($result['validade']);
                     $data1 = new DateTime();
                     $intervalo = $data1->diff($data2);

                        if ($intervalo<0) {
                            echo "";
                            echo $intervalo->format('%R%');
                            echo "	";
                            }
                        elseif ($intervalo<30)  {
                            echo "";
                            echo $intervalo->format('%R%');
                            echo "	";
                            }
                        elseif ($intervalo>90)  {
                            echo "";
                            echo $intervalo->format('%R%');
                            echo "	";
                        }
                    echo "
";
                        }
                    }
                    else
                    $sql =  mysql_query("SELECT $res_codigo as rwc, $res_nome as descricao, $res_un as unidade FROM $tabela order by RAND() LIMIT 200 ");
                if($sql== 0)
                        $sql =  mysql_query("SELECT $res_codigo as rwc, $res_nome as descricao, $res_un as unidade FROM $tabela order by RAND()");
                    while ($result = mysql_fetch_array($sql) )
                    {
                    echo "
";
                    echo "".$result['rwc']."	";
                    echo "".$result['descricao']."	";
                    echo "".$result['unidade']."	";
                    echo "<button class='btn btn-lg btn-primary btn-block' type='submit'>Comprar</button>	";
                    echo "
";
                    }
            ?>

Answer: Tem uma chave que está sendo fechada a mais, seria esse o problema?
tente isso:
<?php
$data2 = new DateTime($result['validade']);
$data1 = new DateTime();
$intervalo = $data1->diff($data2);
echo "
";
echo "
";
if ($intervalo->days<0) {
    echo "";
    echo $intervalo->format('%R%a dias');
    echo "	";
}
elseif ($intervalo->days<30)  {
    echo "";
    echo $intervalo->format('%R%a dias');
    echo "	";
}
elseif ($intervalo->days>90)  {
    echo "";
    echo $intervalo->format('%R%a dias');
    echo "	";
}
echo "
";
echo "
";

?>
Comment: Na verdade ó código não termina alí.. segue inteiro
Comment: então qual seria sua dúvida? o que não está funcionando?
Comment: Funcionou! Desculpa! obrigado pela ajuda!

Trabalhar com datas vindas do MySQL/PHP


NoClassDefFoundError: com/aventstack/extentreports/reporter/ExtentHtmlReporter

Question: I am trying to obtain a report in my maven project using Cucumber, and ExtentReport. I am using java 8. Here are my dependencies:
<dependencies>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.4.0</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>1.2.5</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>1.2.5</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.vimalselvam</groupId>
        <artifactId>cucumber-extentsreport</artifactId>
        <version>3.1.1</version>
    </dependency>

</dependencies>

and then i used the below runner class, to run all my *.feature files:
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        features            = {"src/test/resources/features" },
        monochrome          = true,
        plugin              = {"com.vimalselvam.cucumber.listener.ExtentCucumberFormatter:output/report.html"},
        glue                = {"stepDefinitions"}
        )
public class TestRunnerJUnit {

}

But when i run the test-Runner, it complains with:
cucumber.runtime.CucumberException: java.lang.NoClassDefFoundError: com/aventstack/extentreports/reporter/ExtentHtmlReporter
    at cucumber.runtime.formatter.PluginFactory.instantiate(PluginFactory.java:114)
    at cucumber.runtime.formatter.PluginFactory.create(PluginFactory.java:87)
    at cucumber.runtime.RuntimeOptions.getPlugins(RuntimeOptions.java:245)
    at cucumber.runtime.RuntimeOptions$1.invoke(RuntimeOptions.java:291)
    at com.sun.proxy.$Proxy11.done(Unknown Source)
    at cucumber.runtime.junit.JUnitReporter.done(JUnitReporter.java:227)
    at cucumber.api.junit.Cucumber.run(Cucumber.java:101)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: java.lang.NoClassDefFoundError: com/aventstack/extentreports/reporter/ExtentHtmlReporter
    at com.vimalselvam.cucumber.listener.ExtentCucumberFormatter.setExtentHtmlReport(ExtentCucumberFormatter.java:55)
    at com.vimalselvam.cucumber.listener.ExtentCucumberFormatter.<init>(ExtentCucumberFormatter.java:38)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at cucumber.runtime.formatter.PluginFactory.instantiate(PluginFactory.java:107)
    ... 12 more

Update:
When i add the below dependency:
<dependency>
    <groupId>com.aventstack</groupId>
    <artifactId>extentreports</artifactId>
    <version>3.1.1</version>
</dependency>

I receive this new error:
java.lang.IllegalArgumentException: testName cannot be null or empty
    at com.aventstack.extentreports.ExtentTest.<init>(ExtentTest.java:80)
    at com.aventstack.extentreports.ExtentReports.createTest(ExtentReports.java:105)
    at com.aventstack.extentreports.ExtentReports.createTest(ExtentReports.java:145)
    at com.vimalselvam.cucumber.listener.ExtentCucumberFormatter.feature(ExtentCucumberFormatter.java:155)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at cucumber.runtime.Utils$1.call(Utils.java:40)
    at cucumber.runtime.Timeout.timeout(Timeout.java:16)
    at cucumber.runtime.Utils.invoke(Utils.java:34)
    at cucumber.runtime.RuntimeOptions$1.invoke(RuntimeOptions.java:294)
    at com.sun.proxy.$Proxy11.feature(Unknown Source)
    at cucumber.runtime.junit.JUnitReporter.feature(JUnitReporter.java:184)
    at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:69)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

Answer: try to replace this
<dependency>
    <groupId>com.aventstack</groupId>
    <artifactId>extentreports</artifactId>
    <version>3.1.1</version>
</dependency>

with this one
<dependency>
    <groupId>com.aventstack</groupId>
    <artifactId>extentreports</artifactId>
    <version>3.0.7</version>
</dependency>

the component "cucumber-extentsreport" and "extentreports" are different things.
I had the same issue and solved by using "extentreports" version 3.0.7 with "cucumber-extentsreport" version 3.1.1
Good luck!
Answer: I got the answer.
Everything was fine, but i needed to added a value to Feature in the  *.feature file.
So, here you can see the Feature key word should exist, and exactly in front of it should be a text. If you write the text in next line, you will face with the error.
Feature: Check Welcome-message
  As a user, I should find a welcome-message in my mailbox, and my age in my profile.

Answer: I got the answer. Everything was fine, but i needed to added a value to Feature in the *.feature file. So, here you can see the Feature key word should exist, and exactly in front of it should be a text. If you write the text in next line, you will face with the error.  :- Yes its work for me too


Detect if running inside PhoneGap/ Cordova

Question: There has been a few questions how to detect an HTML page is running inside a device as a phonegap application.
Most of the solutions (here and here) have been

Detect if browser agent is iPhone/iPad/Android/Blackberry
Use 'deviceready' event to detect if running inside a device.
Use URL to detect whether protocol is HTTP or FILE

Are there any other solutions? All 3 won't work for me since I run the development HTML files locally before compiling the app, as a result it will detect 1). and 2). will fire and 3). is indeed FILE protocol.
Answer: In local file and mobile website deviceready won't fire as it is a PhoneGap specific event. so u can set your IsRunningOnPhoneGap flag in the device ready event.
Comment: DeviceReady fires if the cordova.js file is loaded and the listener is placed. This won't help use the same code for the web and the cordova app.
Answer: This works:
<code>if (window.cordova)
{
    document.addEventListener("deviceready", onReady, false);
}
else
{
    onReady();
}
</code>


O que é uma linguagem de script?

Question: Costuma-se dizer que PHP, Javascript, Ruby, Python, entre outras são "linguagens de script."
Mas o que define se uma linguagem de programação é uma linguagem de script ou não?
Alguns diriam que as linguagens de script são as interpretadas, porém Java é interpretado e não é citado como uma linguagem de script.
O que é uma linguagem de script?
Comment: A pergunta é boa justamente porque muita gente não entende bem o que é. É verdade que não dá para responder 100% porque não há uma conceituação universalmente aceita, mas vimos aqui algumas respostas bem erradas (algumas foram apagadas) mostrando que é necessário uma explicação.
Comment: Java não é interpretada há muitos anos.
Comment: @Filipe nenhum problema em apagar não. Se você não consegue melhorá-la, é o melhor a fazer mesmo. Eu mesmo já apaguei minhas. Nas respostas apagadas eu dei os motivos objetivos de estar errado, nada vago. Eu já aprendi muita coisa errada, na internet tá cheio de informação errada, mas quando você começa juntar as coisas, você lê as definições existentes você vê que uma contrapõe a outra e aí você só pode se valer daquelas que não encontra objeção clara. A forma de execução não define se a linguagem é de *script*, tem tantas casos contrários nisto que não serve de parâmetro.
Comment: Retirei o meu voto de fechar, na esperança de aparecerem respostas interessantes, mas para já, continuo a achar amplo demais, não vejo nenhuma resposta concreta e fundamentada, apenas me parecem opiniões com algum tipo de informação correta.
Comment: @bigown apaguei sim, respondi o conceito que sempre achei ser verdade, mas como você disse ser uma premissa errada (e não quero contribuir com lixo) espero uma resposta concreta de alguém para comparar com a minha resposta, assim fica mais fácil discutir o assunto, só dizer que está errado fica muito vago.
Comment: Linguagens de script são linguagens de programação que não requerem  compilação, ou seja são interpretadas. e a unica diferenca que vejo.
Answer: Linguagem de script é qualquer linguagem que for usada para escrever um script. A grande pergunta é O que é um script?. E essa é bastante subjetiva, uma análise caso a caso.
A distinção toda está no objetivo e no uso. Em um script você descreve uma sequencia de comandos e tarefas que alguém deve executar (o interpretador). O exemplo clássico disso são as linguagens para os prompts de comando, seja o shell/bash ou para o batch do Windows. Outras linguagens sugiram como um intuito de facilitar a escrita de pequenos programas, permitindo maior complexidade no que antes era feito com os .sh ou .bat. Essas linguagens são chamadas de shell languages.
Varias linguagens criadas posteriormente que podem funcionar como script são o perl, python, ruby, etc. Mas note que com o poder e flexibilidade que elas tem, muitas são usadas para escrever grandes aplicações, especialmente do lado do servidor. Nesse caso já deixou de ser apenas de script.
Outra definição comum está em afirmar que linguagens de script são aquelas que podem ser embutidas em outros programas. Na engine de jogos Unity3D, por exemplo, você pode programar o comportamento de cada objeto usando C#. Nesse caso C# é uma linguagem de script, mesmo sendo compilado. Mas se você escrever uma aplicação inteira em C# e executar ela de forma independente, não vai ser um script. Da mesma forma você pode entender que o javascript está estendendo a habilidade do browser dando características adicionais à sua página, portanto é um script. Existe um dialeto de C/C++, o AngelScript, que foi construído com esse objetivo de ser embutível facilmente. É mais um exemplo de linguagem de script.
Dizer que tudo que é compilado não é script e tudo que é interpretado é script é errado. A forma como o código é executado não influencia, ainda mais nesses dias de JIT em que os interpretadores cada vez mais são iguais aos compiladores. A questão toda está no propósito daquele código.
De forma geral, pode-se dizer que as linguagens de script dependem de um certo ambiente para serem executadas corretamente. Seja as utilidades da linha de comando, seja as funcionalidades de uma engine de jogos ou navegador. Enquanto que uma linguagem sem ser de script executa "nua", sendo mais independente. Tem muitos casos em que é difícil distinguir, vira algo quase subjetivo.
Leitura complementar:
Why are scripting languages (e.g. Perl, Python, Ruby) not suitable as shell languages?
Comment: Ainda fiquei com mais dúvidas eu... Parece-me que estamos a focar um ponto bastante subjetivo, o que é um script.
Comment: "closed as not constructive" ;)
Answer: Bem... cheguei um pouco tarde neste post, mas eu sempre compreendi linguagens de script como sendo aquelas usadas em "domínios específicos", ou seja, criadas para auxiliar a resolução de problemas em um determinado segmento da ciência da computação. Geralmente, o "motor" de uma linguagem de script está embutido em uma aplicação, de modo que a mesma possa ser configurada com muita flexibilidade, auxiliando a automatização de determinadas tarefas.
Linguagens de programação por sua vez, permitem a criação de aplicativos (ou programas) para execução em um ou mais sistemas operacionais, estes aplicativos podem ser criados para diversas finalidades e são executados quase sempre independentes de alguma outra aplicação.
Eu participei de um projeto, onde foi desenvolvida uma aplicação em linguagem C, para ler e processar arquivos provenientes de centrais telefônicas. Esta aplicação usa a linguagem de scripts Tcl embutida, de modo que quando é concluído o download de um arquivo, scripts em Tcl são executados para efetuar diversos tipos de processamento no conteúdo do mesmo, os resultados produzidos após este processamento atendem outras áreas da empresa, como por exemplo a de faturamento e a de análise contra fraudes.
Neste exemplo, C seria a linguagem de programação, Tcl a linguagem de scripts.
Atualmente, as linguagens de scripts estão se tornando mais sofisticadas, permitindo por exemplo que o código fonte de um script seja "compilado" para um arquivo em "bytecode", neste caso, o "motor" na aplicação hospedeira executa o arquivo em bytecode, que tende a ter uma melhor performance de execução além de proteger o código fonte do script contra terceiros. O problema começa quando scripts são desenvolvidos para execução fora de uma aplicação, isto é possível, sendo que eu mesmo já criei scripts em Tcl que possuem interface gráfica e são executados diretamente pelo interpretador desta, fora de qualquer aplicação hospedeira, neste caso Tcl também pode ser classificada como uma linguagem de programação? Na minha humilde opinião, não. O próprio autor da linguagem afirma que a mesma foi criada para ser embutida em aplicações, de modo a resolver um conjunto específico de problemas.
Parece não existir uma classificação formal para identificar linguagens de script e de programação. Eu acho que o mais indicado é descobrir quem criou a linguagem e que uso esta pessoa ou empresa pretende para a mesma. Geralmente, se a linguagem permite ser embutida em uma aplicação escrita em uma outra linguagem, então ela é definida como sendo principalmente uma linguagem de script.
Comment: mas um script não seria uma linguagem de programação?
Answer: Linguagens de script são aquelas em que o interpretador lê o código fonte e gera um "bytecode" que é então executado pelo compilador, ou seja o bytecode é um meio termo entre a fonte e linguagem de maquina. Portanto as linguagens de script ou interpretadas precisam do código fonte para executar o programa, ao contrario de linguagens compiladas que após ser executado a compilação, basta o executável binário para executar o programa.
Simplificando
Linguagens interpretadas necessitam do código fonte para executar, enquanto as compiladas precisam apenas do compilado.
Minha conclusão :
Linguagens de programação base (linguagens compiladas) são descompiladas pelo compilador( semelhante ao que o descompactador zip faz ) e executadas pelo executável binário (linguagem primária da máquina , linguagem que o homem não entende ou seja a origem de tudo relativo ao software da máquina ) .
Por outro lado linguangens scripts ou linguagens interpretadas são aquelas que não são executadas diretamente pelo compilador , primeiro elas são interpretadas pelas linguagens de programação base(linguagens compiladas) e essas interpretam esse script e transformam-á em código compilado  para que essas sejam processadas pelo compilador e finalmente serem executadas .
Espero que eu tenha ajudado a galerinha á entender o que são scripts ou linguagens scripts :) ...
Comment: Não não é isto, dê uma lida na resposta bem mais votada que tem informações mais concretas. Tem vários conceitos errados nesta resposta.
Answer: Linguagens de script são aquelas em que o interpretador lê o código fonte e gera um "bytecode" que é então executado pelo compilador, ou seja o bytecode é um meio termo entre a fonte e linguagem de maquina. Portanto as linguagens de script ou interpretadas precisam do código fonte para executar o programa, ao contrario de linguagens compiladas que após ser executado a compilação, basta o executável binário para executar o programa.
Simplificando
Linguagens interpretadas necessitam do código fonte para executar, enquanto as compiladas precisam apenas do compilado.
Comment: Há uma enorme confusão de conceitos aqui. Além de cair no erros de outras respostas, ainda inverteu o erro deixando uma parte da resposta contradizendo a outra parte, tornando-o ainda pior.
Answer: Linguagens de programação que foram desenvolvidas originalmente em ambiente Linux, normalmente são chamadas scripts, devido a uma relação analoga que os profissionais fazem ao se remeterem à outras linguagens de script com o shell script(sh script), bash script, etc. Em algumas traduções de livros diz se que são roteiros de comandos a serem executados, daí também a analogia script.
Comment: A resposta não explica bem, mas pelo menos não cai no erro de outras respostas que confundem conceitos e usam premissas erradas. Essa sua até está razoavelmente boa, mas já vi outras respostas que você deu que são muito vagas e não ajudam muita coisa. Aqui procuramos respostas que realmente ajudem a entender ou resolver problemas. Procure desenvolver suas respostas um pouco melhor e vai se dar bem. Elas nem precisam ser longas, mas precisa dar um resposta real, por isso uso esta como um exemplo de algo que se aproximou bem do objetivo.
Comment: Queria dizer ambiente Unix correcto?

O que é uma linguagem de script?


Factoring $x^{15}−1$ into irreducible polynomials over $\mathrm{GF}(2)$

Question:
Factorize $x^{15}−1$ into irreducible polynomials over $\mathrm{GF}(2)$

The answer is
$$(x+1)(x^2+x+1)(x^4+x+1)(x^4+x^3+1)(x^4+x^3+x^2+x+1)$$
but how would I find this? Please help.
Comment: sorry forgot to mention the degree. it is 4
Comment: [Related](http://math.stackexchange.com/q/50989/11619).
Answer: The polynomial $x^{16}-x\in\mathbb{F}_2[x]$ has roots precisely equal to the elements of $\mathbb{F}_{16}$, and the subfields of $\mathbb{F}_{16}$ are $\mathbb{F}_{16}$, $\mathbb{F}_{4}$, and $\mathbb{F}_{2}$, which have degrees
$$[\mathbb{F}_{16}:\mathbb{F}_2]=4\qquad [\mathbb{F}_{4}:\mathbb{F}_2]=2\qquad [\mathbb{F}_{2}:\mathbb{F}_2]=1$$
Therefore $x^{16}-x$ is the product of the irreducible polynomials in $\mathbb{F}_2[x]$ of degrees $1$, $2$, and $4$.
Therefore $x^{15}-1$ is the product of the irreducible polynomials in $\mathbb{F}_2[x]$ of degrees $1$, $2$, and $4$, other than the irreducible polynomial $x$.
To find these irreducible polynomials, you can use Sieve of Eratosthenes (Wikipedia link), adapted to the ring $\mathbb{F}_2[x]$.
Comment: thanks for the reply, very good explanation about finding the degree of the irreducible polynomials for a specific polynomial over GF(q)
Comment: I didn't understand how to find the irreducible polynomials from Sieve of Eratosthenes. Could you explain how to do this please?


How do I find out if BMP image contains BGR or BGRA pixels from header?

Question: I can't figure out how do I find out if BMP image contains BGR or BGRA colors. I wrote simple BMP reader but there are different values on different images.
There are 2 options I have found out already.

Simple BGR (255, 255, 255)
Fourth value is 0 (255, 255, 255, 0)

Is there any way how do I find out which option is that from bitmap info header?
Comment: It's complicated: https://en.wikipedia.org/wiki/BMP_file_format
Answer: The first 54 bytes in the bitmap file is the header. Read BITMAPINFOHEADER which contains bitmap's width and height, as well as biBitCount
For a 32-bit (4-byte) image biBitCount is 32 (BGRA)
For a 24-bit (3-byte) image biBitCount is 24 (BGR)
biBitCount can also be 16-bit, or 8, 4, 1 for palette based bitmaps.
Comment: I have downloade a sample picture from some Microsoft website which is 8 bit BMP. I tried to read that picture and every fourth color of *each* pixel is 0. How is that possible? It can't be BGR, because first, second and third colors matches.
Comment: 8-bit bitmap (256 colors) has palette. The palette size is 1024 bytes (256 colors * 4-bytes). The pixels start after 54+1024, and these pixels are not BGR values, it is an index to the palette. In this case each pixel is only 1-byte


The prediction at the average of the covariates is different from the average of the predictions

Question: I read in Stata manual : "The prediction at the average of the covariates is different from the average of the predictions" after a logistic regression.
If I compute predictions for a linear regression (with command Predict that uses own values of covariates for each individual) and I find the mean "a" of my predictors. Then I compute predictions in holding values of my covariates at their means and I find the mean "b" of my predictors.
Have "a" and "b" the same value?
Answer: The answer is no for logistic regression, but yes for linear regression. Why? Because the conditional expectation function in linear regression is linear!
Logistic regression case:
The logistic function $f(x) = \frac{1}{1 + e^{-x}}$ is non-linear. You almost certainly do not have $E[f(x)]$ equal to $f(E[x])$ (except in absolutely degenerate cases like $x = 0$ for all data).
The prediction at the average of the covariates would be: $$f\left(E[\boldsymbol{x}]'\boldsymbol{b}\right)$$
The average of the predictions of the covariates would be:
$$E\left[ f(\boldsymbol{x}'\boldsymbol{b})\right]$$
In any realistic setting, the two would not be equal.
Linear regression:
On the other hand, for linear regression, the conditional expectation function $f(\boldsymbol{x}) = E[y \mid \boldsymbol{x}]$ you're estimating is linear! For a linear function $f$, (eg. $f(\boldsymbol{x}) = \boldsymbol{x}'\boldsymbol{b}$), you have $E[f(\boldsymbol{x})] = f(E[\boldsymbol{x}])$. Intuition: $\boldsymbol{x}'\boldsymbol{b}$ is a sum, taking the expectation is a sum, and you can reorder sums any way you want and it doesn't matter.
For linear regression:
$$E[\boldsymbol{x}'\boldsymbol{b}] = E[\boldsymbol{x}]'\boldsymbol{b}$$
$E[\boldsymbol{x}'\boldsymbol{b}]$ is the average of the predicted values while $E[\boldsymbol{x}]'\boldsymbol{b}$ is the prediction of the average.
Note: I use bold symbols to denote vectors. I use $\boldsymbol{b}$ to denote the vector of estimated coefficients (either from linear or logistic regression, depending on the section).


D7 - Ckeditor buttons get messed up when moving a site from one server to other

Question: I just moved a D7 site from one server to another and the Ckeditor buttons get messed up. Look my capture. How can I fix this?
I use the Adminimal Theme but it is not the problem. If I switch to Bartik the problem persist.
I already cleared caches and run Cron several times.
Comment: For good measure clear your browser cache.
Answer: Have you checked Css settings on Ckeditor profile page?
Comment: Yes I have. But I just re-saved this page I the problem is gone. I guess it needed to be refreshed.  Thanks.
Comment: Happy to help, don't hesitate to voteup if it really helped you :)


Finding an orthogonal vector to two vectors in $\mathbb{R}^4$

Question: "Let $u_1$, $u_2$ be to vectors in $\mathbb{R}^4$ $$u_1=(1,0,1,1) \text{ and } u_2=(1,1,0,3)$$
Provide a real vector which is orthogonal to both $u_1$ and $u_2$
So, I kind of guessed a vector $u_3=(1,-1,-1,0)$ which must be orthogonal to both since $$u_1 \cdot u_3 = 0 \text{ and } u_2 \cdot u_3=0$$
My question is, how should it be done if it can't immediately be guessed? In $\mathbb{R}^3$ one could just take the cross product of the two vectors, but that's not defined for any other vector spaces
Comment: Pick a random vector. It almost surely won't be orthogonal, and almost surely will be linearly independent. Find its projection onto the previous vectors, then subtract out these projections to obtain an orthogonal vector. This is the Gram-Schmidt process.
Comment: Nonzero binary cross products exist only in three and seven dimensions. See here: https://en.wikipedia.org/wiki/Seven-dimensional_cross_product#Generalizations
Answer: You can use Gauss-Jordan method to solve the linear system:
$$\langle (x,y,z,t),u_1\rangle=0$$
$$\langle (x,y,z,t),u_2\rangle=0$$
that is:
$$ x+z+t=0 $$
$$ x+y+3t=0$$
so the matrix of your system of linear equations is:
$$
A=\left[
\begin{array}{cccc}
1&0&1&1\\
1&1&0&3
\end{array}
\right]
$$
the rref of $A$ is
$$
\mathrm{rref}(A)
=
\left[
\begin{array}{cccc}
1&0&1&1\\
0&1&-1&2
\end{array}
\right]
$$
so, you have
$$x=-z-t$$
$$y=z-2t$$
with $z,t$ being any real values.
then all vectors $\vec{v}=(x,y,z,t)$ that are ortogonal to both $u_1$ and $u_2$ are of the form
$$\vec{v}=(-z-t,z-2t,z,t).$$

See the link bellow to clarify the general cross product:
Cross product in $\mathbb R^n$
Comment: @Alex5207 More fundamentally, the null space of a matrix is the orthogonal complement of its row space. Row-reduction doesn't change the row space, and once you have the rref, you can read a basis for the null space from it.
Comment: Great - I see this works. I guess on parametric form it's equal to $$\begin{bmatrix} x \\ y \\ z \\ t \end{bmatrix} = s \cdot \begin{bmatrix} -1 \\ 1 \\ 1 \\ 0 \end{bmatrix} + t \cdot \begin{bmatrix} -1 \\ -2 \\ 0 \\1 \end{bmatrix}$$ where $(s,t)=(z,t)$ - Right? However, could you explain exactly why it works to put the vectors in a matrix and rref? I'm not really sure why it provides the answer..
Comment: Yes, it is true because $\vec{v}=(x,y,z,t)$ will be a solution to both conditions $\langle \vec{v},u_1\rangle=0$ and $\langle \vec{v},u_2\rangle=0$. Recall that these two conditions are just two linear equations that you can solve using Linear System techniques as Guass Jordan.
Comment: You are the man! Thanks very much
Comment: Yes, exactly! that's a good explanation.
Answer: Take a non-null vector $u_3$. If it is orthogonal to the other two, you're done. Otherwise, compute the $4$-dimensional cross-product of $u_1$, $u_2$, and $u_3$ described here.
Answer: Since you have only two vectors, you can work in $\mathbb R^3$. Let $u_3 = (a, b, c, 0)$, so that $u_1 \cdot u_3$ and $u_2 \cdot u_3$ only depend on the first three components of $u_1$ and $u_2$. So, call $v_i$ the vector of the first three components of $u_i$, and compute $v_3 = v_1 \times v_2 = (a, b, c)$ (this wouldn't work if either $v_1$ or $v_2$ was zero).
Specifically,
$$u_3 = \begin{pmatrix}
\begin{vmatrix}0 & 1 \\ 1 & 0\end{vmatrix},
-\begin{vmatrix}1 & 1 \\ 1 & 0\end{vmatrix},
\begin{vmatrix}1 & 0 \\ 1 & 1\end{vmatrix},
0
\end{pmatrix} = (-1, 1, 1, 0)$$
Which only differs in sign from your solution.


MPMoviePlayerController on iPhone when enter full screen go in pause

Question: i have add MPMoviePlayerController in my project in this way:
player = [[MPMoviePlayerController alloc] init];
[player setContentURL:videoURL];
[self.view addSubview:player.view];

then when i press a button i play the video:
[player play];

all works perfect, but when i press the button to enter in the fullscreen mode the video go in pause and i have to press the play button to continue the playback, anyone know why?
Comment: Does this answer your question? [iOS 6.0 MPMoviePlayerController full screen mode black color? then App blocked no more actions](https://stackoverflow.com/questions/14437511/ios-6-0-mpmovieplayercontroller-full-screen-mode-black-color-then-app-blocked-n)
Answer: This worked well for me
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    if (!self.moviePlayer.isFullscreen) {
        [self.moviePlayer pause];
    }

}


Permutations of 0...N-1 with given properties

Question: We have the sequence of natural numbers {0.....N-1}
where N=K^L (power), being K,L >1
I am looking for permutations of this sequence, {A(0)....A(N-1)}, such that for any given index m, 0<= m < N :
floor( A(m+1)/K ) = A(m) mod (K^(L-1))
For instance, for K=3, L=2, we have N=9. And 2 possible solutions are
{0,1,4,3,2,8,7,5,6}
{2,7,5,8,6,1,4,3,0}
My questions are

Will there always exist a solution for any given K,L?
If so, can an algorithm or general formula be found for any case?
Answer: In effect, you are asking for a permutation of all L-digit numbers in base K (including those with leading zeros) such that the last $L-1$ digits of any number would be the first $L-1$ digits of the next one.
Well, that calls for de Bruijn sequences.
Comment: Have just taken a look at it and you're right, thanks. In fact the original problem was about a minimum length sequence, but didn't know of the link. So, I guess there is no general formula for the indexes but an algorithm?
Comment: Looks like so. Well, as to me, an algorithm is as good as formula.


How do I query entities to get all fields values - including referenced ones (INNER JOIN)

Question: I have custom content types in my Drupal 8 module and want to query nodes of those content types programmatically.
Querying through entityQuery is easy. However, I have also entity reference fields (so a node of one content type has a relation to a node of another content type).
Is there a way how to make a query that will return 'rows' of field values, exactly as when I use raw SQL INNER JOIN? I want to have an associative array of all field values, not only the specific node, but also the referenced nodes/entities.
Right now I have an own class to handle this, but it's way too much complicated and, I believe, unnecessary, so I guess I'm missing something.
Thank you.
Answer: No, there is not.
Entity query only returns IDs, you need to load those and then from there access the referenced entities.
Comment: Am I doing something wrong in design then (shouldn't use nodes but something else instead)? To me it seems like a lot of unnecessary work (loading nodes, then accessing fields, if reference field - load referenced entity, load field and repeat on every node) comparing to using an own SQL INNER JOIN sentence.
Answer: Views uses joined tables a lot, you can implement this in UI and run it in code.
Or use a db_select.
Example from Drupal\taxonomyTermStorage:
<code>public function getNodeTerms(array $nids, array $vocabs = array(), $langcode = NULL) {
    $query = db_select('taxonomy_term_field_data', 'td');
    $query->innerJoin('taxonomy_index', 'tn', 'td.tid = tn.tid');
    $query->fields('td', array('tid'));
    $query->addField('tn', 'nid', 'node_nid');
    $query->orderby('td.weight');
    $query->orderby('td.name');
    $query->condition('tn.nid', $nids, 'IN');
    $query->addTag('term_access');
    if (!empty($vocabs)) {
      $query->condition('td.vid', $vocabs, 'IN');
    }
    if (!empty($langcode)) {
      $query->condition('td.langcode', $langcode);
    }

    $results = array();
    $all_tids = array();
    foreach ($query->execute() as $term_record) {
      $results[$term_record->node_nid][] = $term_record->tid;
      $all_tids[] = $term_record->tid;
    }

    $all_terms = $this->loadMultiple($all_tids);
    $terms = array();
    foreach ($results as $nid => $tids) {
      foreach ($tids as $tid) {
        $terms[$nid][$tid] = $all_terms[$tid];
      }
    }
    return $terms;
  }
</code>
Comment: Thanks, I didn't know I can use Views created in UI programmatically. This is probably what solves my problem :)


Other ways to compute this integral?

Question: The following (improper) integral comes up in exercise 2.27 in Folland (see this other question): $$I = \int_0^\infty \frac{a}{e^{ax}-1} - \frac{b}{e^{bx}-1}\,dx.$$
I computed it as follows.
An antiderivative for $a(e^{ax}-1)^{-1}$ is $\log(1-e^{-ax})$, found by substituting $u = e^{ax}-1$ and noting that $1/u(u+1) = 1/u - 1/(u+1)$.
Therefore, $$\int_{\varepsilon}^R \frac{a}{e^{ax}-1} - \frac{b}{e^{bx}-1}\,dx = \log\left(\frac{1-e^{-aR}}{1-e^{-bR}}\right) + \log\left(\frac{1-e^{-b\varepsilon}}{1-e^{-a\varepsilon}}\right).$$
The first term goes to $\log(1) = 0$ as $R\to\infty$.
For the second term, we have
$$\lim_{\varepsilon\to 0^+} \log\left(\frac{1-e^{-b\varepsilon}}{1-e^{-a\varepsilon}}\right) = \log \lim_{\varepsilon\to 0^+} \frac{1-e^{-b\varepsilon}}{1-e^{-a\varepsilon}},$$
which looks like $0/0$. Applying l'Hospital's rule,
we get $$\lim_{\varepsilon\to 0^+} \frac{1-e^{-b\varepsilon}}{1-e^{-a\varepsilon}} = \lim_{\varepsilon\to 0^+} \frac{be^{-b\varepsilon}}{ae^{-a\varepsilon}} = \frac{b}{a}$$
so $I = \log(b/a)$.
What are some other ways to compute this integral? Perhaps there is a method incorporating Frullani's theorem?
Comment: Perhaps use residues? This method already seems fairly painless...
Comment: @hermes There is no typo; moreover, your integral is divergent.
Comment: @Potato Perhaps I should ask simply for *other* and not *quicker* ways. My solution feels gritty to me.
Comment: @Unit You did the straightforward thing. I don't see anything wrong with that aesthetically.
Comment: @Potato Perhaps you would be interested in my answer below.
Answer: Well, I guess the Frullani way really just involves expressing the integrand as an integral over its derivative and then switching the order of integration.  So, consider
$$f(u) = \frac{u}{e^{u x}-1}$$
$$f'(u) = -\frac{u \, x \, e^{u x}}{(e^{u x}-1)^2} + \frac1{e^{u x}-1}$$
$$\int_b^a du \, f'(u) = \frac{a}{e^{a x}-1} - \frac{b}{e^{b x}-1} $$
Thus, we assert that
$$\begin{align}\int_0^{\infty} dx \, \left (\frac{a}{e^{a x}-1} - \frac{b}{e^{b x}-1} \right ) &= \int_0^{\infty} dx \, \int_b^a du \, \left [-\frac{u \, x \, e^{u x}}{(e^{u x}-1)^2} + \frac1{e^{u x}-1} \right ] \\ &=  \int_b^a du \, \int_0^{\infty} dx \,\left [-\frac{u \, x \, e^{u x}}{(e^{u x}-1)^2} + \frac1{e^{u x}-1} \right ] \end{align}$$
We assert this because we know (ahem) that each integral is finite by itself.  (I know this reasoning allowing us to switch the order of integration can be improved upon but I want to stress the mechanics of the computation for now.)
Now we must do the inner integral.  The funny thing is that the integrand is completely symmetric in $u$ and $x$ so that we may simply write down the antiderivative as $f$, but now seen as a function of $x$ rather than $u$.  Thus,
$$\int_0^{\infty} dx \,\left [-\frac{u \, x \, e^{u x}}{(e^{u x}-1)^2} + \frac1{e^{u x}-1} \right ] = \left [\frac{x}{e^{u x}-1} \right ]_0^{\infty} = -\frac1{u}$$
Thus, the integral we seek is
$$-\int_b^a \frac{du}{u} = \log{\frac{b}{a}}$$
Comment: This is nice! But it's really just a proof of Frullani's theorem in disguise, as explained by your first sentence! For if we have some $C^1$ function $f$ then $\frac{\partial}{\partial t} f(xt)/x = \frac{\partial}{\partial x} f(xt)/t = f'(xt)$, then $\int_b^a f'(xt) = (f(ax)-f(bx))/x$ and $\int_a^b\int_0^\infty f'(xt)\,dx\,dt = f(xt)|_{x=0}^\infty \int_a^b dt/t$!
Comment: Took too long editing my comment; the last integral should be from $b$ to $a$ and this is what changes $f(\infty)-f(0)$ to $f(0)-f(\infty)$.
Answer: Here's a nice solution.
If we let $$f(x) = \frac{x}{e^x-1} = \frac{1}{1+\frac{x}{2}+\frac{x^2}{6}+\dotsb}$$
then $f(0) = 1$ and $f(\infty) = 0$ and $$\frac{f(ax) - f(bx)}{x} = \frac{a}{e^{ax}-1} - \frac{b}{e^{bx}-1},$$
and now apply Frullani's theorem.

Other ways to compute this integral?


Find minimum number of batteries to last a week with 95% probability given mean and sd of lifetime

Question: A TA needs a very important program on his computer but his power cable is missing. Luckily, he happens to have 100 batteries lying around and a contraption that can store batteries to use one at a time. From his understanding, the average lifetime of a battery will last 2 hours for his computer with a standard deviation of 30 minutes. How many batteries will he need to place in the contraption to keep his computer continuously running for the next 7 days (168 hours) with at least a 95% probability?
I'm trying to approach this question using confidence intervals, but i'm confused what the sample proportion would be, would it be 84 batteries? cause u need 84 to run the computer for 168 hours, assuming each battery lasts exactly 2 hours. Would my standard error just be the standard deviation given?
 Or is there another way to approach this question
Comment: (1) This appears to be a [routine textbook-style](http://stats.stackexchange.com/tags/self-study/info) question. Such questions are treated differently here. Please add the tag at that link, and read the guidelines there. $\,\,$ (2) "84" is not a proportion, which lie between 0 & 1. "84 batteries" is a count. Note that batteries don't last "exactly 2 hours" but *on average two hours*. That means that 84 batteries would only have (about) a 50-50 chance of lasting 168 hours; you'll need more batteries than that.
Comment: You use confidence intervals to find plausible bounds for an _unknown_ mean. Here you know the true mean, so confidence intervals aren't relevant.
Answer: You need to use the properties of the sum of independent distributions and the Central Limit Theorem. It's a probabilistic problem, not a statistical one.
Each battery's time of use follows a distribution  $X$ with $E[X]=2, Var[X]=0.5^2$. As you add batteries, you add variables (two batteries last $Y_2=X+X$ with $E[X]=2+2, Var[X]=0.25+0.25$). So $n$ batteries will last $Y_n=n\cdot X$ with $E[X]=2n, Var[X]=0.25n$. You need to find $n$ so that the probability of the joined time of use of $n$ batteries $Y_n$ is greater than 168 hours ($P(Y_n>168)=0.95$). As n will be quite large, you can use the CLT to aproximate $Y_n$ with a normal distribution.
To do that, you need to typify the distribution. You look for the 95% quantile and do the equation to find $n$. Thanks for the corrections and advices you have given.
Comment: that's the right approach in my opinion. I'm wondering about a few things however: (1) The question doesn't say that lifetimes are normally distributed. Nevertheless you still need a way to say what the distribution is, if not for a battery lifetime then at least for the _sum_ of the lifetimes. (2) Are you sure that adding _standard deviations_ is the correct thing to do? I think you mean variances. (3) What condition needs to hold to add variances? (This condition doesn't always hold. E.g. to find the variance of who wins a tennis match I can't add the variances of each player together.)
Comment: re 1) you want the central limit theorem as it applies to sums (it's more often applied to the mean but applies to sums too as the mean is just the sum/$n$).
Comment: 1) Indeed, the Normal distribution is something I've asumed. I don't know any other way to compute the final probability (the sum of random distributions are not necessarely normal). 2) I ment variances, I'll edit it. 3) The variances can be added whenever you add two independent normal distributions. It's basic proprerties of the Normal distribution, and also from any uncorrelated variables, regardless of their distributions (Bienaymé formula). I guess that it doesn't work for tennis match because the winning of one player is correlated to the (non) winning of the other one.
Comment: cool, re 1) can you think of any way of saying something about the distribution of a sum (or the mean) of a large number of independent identically distributed random variables? re 3) agreed, it's good to state independence explicitly though, in particular as it's required for 1).
Comment: 3) Yes, it's good to say that the time of life of one battery does not affect in the time of life of another one, so you can state that they are independent. 1) The expectation and variance of any independent random variables are the sum of their expectations and variances. Only the joint variance is corrected by the covariance if the variables are dependent. http://www.milefoot.com/math/stat/rv-sums.htm I don't know which other reason do you expect.
Comment: 1) You are right. As n will be quite large, you don't need to assume that X is normal, Y_n will aproximately be.
Comment: I solved the question. Using the formula y(bar) +- z*(S.D/sqrt(n)).
I found that a 95% confidence interval is between (1.902,2.098). Then 168/1.902 = 88 batteries. What I found was the average time for each battery given 100 batteries within a 95% confidence interval. Then I just simply divided the total required hours by the less average battery time within the interval.
Comment: @Andy - well, it looks to me like a somewhat roundabout way to do it, but I think your answer is right.
Comment: Using the way I said you get `-1.645=(168-2n)/0.5sqrt(n)` which gives you `n=87.855`. Your way of thinking works because the confidence interval for the mean of the population (which is a parameter) is equivalent to the centered probability interval for the sample mean (which is a statistic, and in your case, Y_n). The difference is that when isolating from the distribution of the sample mean, you keep in the center of the inequalities the sample mean (X-bar) instead of the population mean (mu).


AUROC: Regression vs Classification results

Question: I'm trying to evaluate the probability of a rare occurrence. My training data is a binary 1/0 for output and a TFIDF Vector of words for input.
Which seems to lend itself to a regression, I've been using xgboost's XGBRegressor with decent results but something is confusing me.
The feature_importances for XGBRegessor seem to pick ngrams which seem to me not that important.
When I ran the exact same test but instead used XGBClassifier the important phrases it chose made more sense to me.
The results of sklearns roc_auc score indicate similarly, it ranks the classifier as better than the regressor. Which I don't understand.
Can I compare the roc_auc score of a classifier and regressor as apples to apples?
Does it make sense that a classifier could perform better at predicting a probability than a regressor?
Answer: This really should be done as a classification problem; xgb naturally produces a probability score (though generally not well-calibrated).
I would suspect that XGBRegressor would actually produce some outputs outside [0,1]; is that the case for you?
Gradient boosting is always a regression under the hood; the only difference is in the loss function. Using mse here will, for example, give the same penalty for predicting 1.2 as for predicting 0.8 for a positive sample. That's likely to mess with the rank-ordering, and hence the ROC curve.
Comment: Ah, I think Harrell's distinction between "classification" and "prediction" there is not quite in line with the sklearn API. Here, most classifiers are probabilistic; since Harrell mostly is arguing against hard classification, I think we're fine.
Comment: Can the results of the `roc_auc` can be taken as apples to apples across regression and calssification? I'm leaning towards making the switch it's just I started out confident it should be taken as a regression task because everyone online talks about rare probability events need to be evaluated as a regression task.

I guess if XGB is all regression under the hood it makes sense.
Comment: I would say yes, because the ROC curve depends only on the rank-ordering. Can you provide reference(s) for rare-event classification being better treated as regression?
Comment: https://stats.stackexchange.com/questions/290886/how-to-improve-rare-event-binary-classification-performance

There was a few other posts also, Thanks though I think I'm going to probably move forward with classification as by all my measurements it's doing better...


Thousand separator use space(" ") instead of "," [BATCH/CMD]

Question: I have this code in my batch/cmd file:
@echo off
setlocal EnableDelayedExpansion

set "var1=9500"

set "var2="
set "sign="
if "%var1:~0,1%" equ "-" set "sign=-" & set "var1=%var1:~1%"
for /L %%i in (1,1,8) do if defined var1 (
   set "var2=,!var1:~-3!!var2!"
   set "var1=!var1:~0,-3!"
)
set "var2=%sign%%var2:~1%

echo %var2%

The output I get:

9,500

The output I want:

9 500
Answer: I found the solution myself.
The one we don't want(line):
set "var2=,!var1:~-3!!var2!"

The one we DO want:
set "var2= !var1:~-3!!var2!"

As you can see, in the second one, I removed a comma.
Now I get this output:

9 500

Hope I helped :).


Running xcode iOS simulator build

Question: I developed an iOS app with Facebook integration. I need to send an iOS simulator build for Facebook to review how the Facebook integration works on my app.
The link provides the instructions on how to create the iOS Simulator build.
https://developers.facebook.com/docs/ios/creating-ios-simulator-build-for-review/
The said link provides code that creates the iOS simulator build
xcodebuild -arch i386 -sdk iphonesimulator{version}

What I wanted to do is to run the app iOS Simulator Build. I want to test if iOS simulator build works.
I searched and found this:
Launch an iOS app in the simulator without XCode
which asked me to use this code to run the iOS simulator build.
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app/Contents/MacOS/iPhone\ Simulator -SimulateApplication ${PROJECT}/build/Debug-iphonesimulator/<yourapp>.app/<yourapp>

Yes, the iOS simulator runs however it does not launch my app.
How should I run the iOS simulator build on the simulator? Need help on this. Thanks!
Addition Note:
I am using Xcode 5.1.1
Comment: its work for me, Check this [answer](http://stackoverflow.com/a/24354660/3257273) and follow the steps.
Answer: I had success using ios-sim.   Then run with ios-sim launch <yourproject>.app
Comment: This should be the right answer. If you're using brew, it's as easy as doing `brew install ios-sim` and then `ios-sim launch .app`.
Answer: Update instructions for Xcode 6.x and later using simctl:
xcrun simctl install booted /path/to/your/built/simulator.app
xcrun simctl launch booted com.your.app.identifier

Running xcode iOS simulator build


Zend Framework 2 Restful web service: common functionality across controllers

Question: Im making a restful web service with Zend FW 2. How can I create a system, that checks ie. API key everytime REST is called? Checking the key in every controller in every function of course is not the way to go, so Im looking for something "global".
Thanks!
Answer: Assuming all your rest methods are in one controller you can listen to that controllers dispatch event, using a high priority so checks are done early...
Register the listener in your modules bootstrap, for example assuming you added an ApiController to the Application module
public function onBootstrap(EventInterface $e)
{
    $app = $e->getApplication();
    // get the shared events manager
    $sem = $app->getEventManager()->getSharedManager();
    // listen to dispatch event when triggered by the ApiController
    $sem->attach('Application\Controller\ApiController', 'dispatch', function($e) {
        // do your api key checks

        // if checks fail get the response from the controller
        $controller = $e->getTarget();
        $response = $controller->getResponse();
        $response->setStatusCode(401);
        // return $response, short circuiting dispatch event
        return $response;
    }, 9000); // 9000 = high priority, do this early
}

Point of note, the event passed to your closure contains as its target an instance of your controller, so if you need to get services from the ServiceManager to do your api checks you can do so just like you would in the controller itself, ie...
 $controller = $e->getTarget();
 $sm = $controller->getServiceLocator();

Comment: My rest methods are in multiple controllers, but they all extend the original RestfulController, so maybe I would be able to listen that? This infact is the thing I tried, mut I didn't know that you can set the priority.
Comment: That should work, yeah. You can hand the shared event manager a list of controllers too, `$sem->attach(array('Application\Controller\ApiController', 'Application\Controller\OtherController'), 'dispatch',  ...`


Definition of a valuation of a rational fraction

Question: Let $F$ be a field. Then the field of rational fractions over $F$ in indeterminates $x_1,...,x_n$, denoted by $F(x_1,...,x_n)$, is the field of fractions of the polynomial ring $F[x_1,...,x_n]$.
P.A.Grillet ("Abstract Algebra") defines a valuation of a rational fraction $f(x_1,...,x_n)/g(x_1,...,x_n)$ at $(a_1,...,a_n) \in F^n$ as $f(a_1,...,a_n)g(a_1,...,a_n)^{-1}$, but he says it is only defined if $g(a_1,...,a_n) \neq 0$ and in this case it invariant under the change of the representative of the equivalence class which is the rational fraction. Concretely, if $f_1(x_1,...,x_n), f_2(x_1,...,x_n), g_1(x_1,...,x_n), g_2(x_1,...,x_n)$ are polynomials over $F$ so that $g_1$ and $g_2$ are nonzero and $f_1(x_1,...,x_n)g_2(x_1,...,x_n) = f_2(x_1,...,x_n)g_1(x_1,...,x_n)$, then $f_1(a_1,...,a_n)g_1(a_1,...,a_n)^{-1} = f_2(a_1,...,a_n)g_2(a_1,...,a_n)^{-1}$.
I understand why $f_1(a_1,...,a_n)g_1(a_1,...,a_n)^{-1} = f_2(a_1,...,a_n)g_2(a_1,...,a_n)^{-1}$ if $g_1(a_1,...,a_n), g_2(a_1,...,a_n) \neq 0$ and $f_1(x_1,...,x_n)g_2(x_1,...,x_n) = f_2(x_1,...,x_n)g_1(x_1,...,x_n)$ (it follows directly from the fact that evaluation $F[x_1,...,x_n]\to F$ at $(r_1,...,r_n)$ is a homomorphism of rings.
What I don't understand if why we necessarily have $g_2(a_1,...,a_n) \neq 0$ if $g_1(a_1,...,a_n) \neq 0$ and $f_1(x_1,...,x_n)g_2(x_1,...,x_n) = f_2(x_1,...,x_n)g_1(x_1,...,x_n)$. Indeed, if $g_1(a_1,...,a_n) \neq 0$ it is possible that $g_2(a_1,...,a_n) = 0$ together with $f_2(a_1,...,a_n) = 0$.
Answer:
What I don't understand if why we necessarily have $g_2(a_1,...,a_n) \neq 0$ if $g_1(a_1,...,a_n) \neq 0$ and $f_1(x_1,...,x_n)g_2(x_1,...,x_n) = f_2(x_1,...,x_n)g_1(x_1,...,x_n)$.

No, that's not true, so there's no way to prove it.  To see this, take a particular example.
Let $g_1(x) = x+8964$, $g_2(x) = (x+8964)(x + 1997)$, $f_1(x) = x+1$, $f_2(x) = (x+1)(x + 1997)$.  It's easy to see that $f_1(x)g_2(x) = f_2(x)g_1(x)$ and $g_1(-1997) \ne 0$, but $g_2(-1997) = 0$.
Comment: Hmm, I suspected this may be a case. Does this mean that the evaluation of rational fractions is not well-defined and useless?
Comment: @Jxt921 No, the definition is good.  You simply need $g_2(a)^{-1} \ne 0$ when you write $f_1(a_1,...,a_n)g_1(a_1,...,a_n)^{-1} = f_2(a_1,...,a_n)g_2(a_1,...,a_n)^{-1}$.
Comment: @Jxt921 I mean you only need to include $g_i(a_1,\dots,a_n) \ne 0$, $i = 1,2$ into the assumptions of the definition.
Answer: Well, consider the general construction of the field of fractions from an integral domain $R$.
For this, one defines an equivalence relation on $R\times (R\setminus\{0\})$:
$(a,b) \equiv (c,d)$ if $ad=bc$.
The equivalence classes are written as fractions: $a/b := \{(c,d)\mid (a,b)\equiv (c,d)\}$. On the quotient set $K =\{a/b\mid a,b\in R,b\ne 0\}$ define addition and multiplication as usual. In this way, $K$ becomes a field and $R\rightarrow K:r\mapsto r/1$ is an embedding (ring monomorphism).
The construction shows that for the fractions $a/b$ one has $b\ne 0$ by definition.
Comment: OP is not sure about the possibility that $b \in R \setminus \{0\}$ is mapped to $0_R$ by an evaluation homomorphism $g_2(a_1,\dots,a_n)$ for some polynomial $g_2$ and $a_1,\dots,a_n \in K$.  How does your answer address that?


using volatile on atomic variables

Question: Using volatile on a variable reduces the risk of memory consistency error (Please correct me if this reveals some holes in my understanding of any relevant concept). So in the following example even though the variable c1 is volatile, still the occurrence of memory constancy error results in c1 becoming  15 or sometimes 14 in the output rather then the correct output 16.
<code>class Lunch implements Runnable {

    private volatile long c1 = 0;
    private Object lock1 = new Object();
    private Object lock2 = new Object();
    public void inc1() {
       // synchronized(lock1) { c1 is volatile
            c1++;
       // }
    }

    public void run() {
        try {
            inc1();
            Thread.sleep(1000);
            inc1();
            Thread.sleep(1000);
            inc1();
            Thread.sleep(1000);
            inc1();
            inc1();
            Thread.sleep(1000);
            inc1();
            Thread.sleep(1000);
            inc1();
            Thread.sleep(1000);
            inc1();
        }
        catch(InterruptedException e) {
            return;
        }
    }
    public long value() {
        return c1;
    }
    public static void main(String args[]) throws InterruptedException {
        Lunch l = new Lunch();
       Thread t1 = new Thread(l);
       Thread t2 = new Thread(l);
       t1.start();
       t2.start();
       t1.join();
       t2.join();
       System.out.println(l.value());
    }
}
</code>
Comment: ( I'm a bit worried about your use of the phrase "reduces the risk". Usually the aim is to ensure no risk at all. )
Comment: The assumption here is that ++ is atomic. Verify your assumptions !
Answer: You are correct.  Because ++ is NOT an atomic operation you can still get inconsistent results where a thread reads/increments/writes a value at the same time as another thread.
Consider using AtomicInteger for cases like this.
Comment: So if I replace multiple invocations of increment() in run() with another function update(long c1) { this.c1 = c1 } which is a part of this class. Then since c1 is volatile and ++ is not involved, the result should be consistently correct?
Comment: Or `AtomicIntegerUpdater` in some circumstances where load-manipulate-store operations are rare.
Comment: @msk it would be "correct" in that at any point in time any thread reading c1 would be guaranteed to see the up to date value of c1.  The usefulness of information that is set without being checked beforehand is often questionable.  The usual use-case is a boolean flag where one thread is signalling another (like a stop flag).  This is pretty much the only case where I use volatile.
Answer: Atomicity is only part of the picture. There is also visibility. If a non-volatile (and non-synchronized) variable value is changed, other threads are not guaranteed to see the change in time, or at all.
Answer: Check http://www.javabeat.net/tips/169-volatile-keyword-in-java.html for understanding what volatile does. It avoids the intermediate thread cache but anyway there can be the lossed update from reading its value and updating in a non atomic operation.

using volatile on atomic variables


Call to a member function getFileUri() on null in ImageItem::presave()

Question: I have a node migration as part of a D6->D8 migration, and for the image field in the node, I've done a separate files migration, and then in my node migration, I just refer to the files migration to get the destination fid and write that to the image field.
field_image:
  plugin: iterator
  source: field_thumbnail
  process:
    target_id:
      plugin: migration
      migration: file
      source: fid

The problem I'm running into is the error listed in the title. This is the presave() function:
public function preSave() {
  parent::preSave();

  $width = $this->width;
  $height = $this->height;

  // Determine the dimensions if necessary.
  if (empty($width) || empty($height)) {
    $image = \Drupal::service('image.factory')->get($this->entity->getFileUri());
    if ($image->isValid()) {
      $this->width = $image->getWidth();
      $this->height = $image->getHeight();
    }
  }
}

It seems like it's dying because there is no image for that node, because it's dying at this line:
$image = \Drupal::service('image.factory')->get($this->entity->getFileUri());

It works just fine when there is an image for the node. Shouldn't this be skipped if there is no image found in the files migration? Is there a config option in the .yml file I can use to avoid this error?
Thanks.
UPDATE: I found this docs page on the skip_on_empty process plugin, and implemented as suggested on that page:
field_image:
  plugin: iterator
  source: field_thumbnail
    process:
    target_id:
    -
      plugin: migration
      migration: file
      source: fid
    -
      plugin: skip_on_empty
      method: row

but I still get the same error, more than likely because in the pipeline, it's already errored out before it gets to the skip_on_empty plugin. However, if I switch things around:
field_image:
  plugin: iterator
  source: field_thumbnail
    process:
    target_id:
    -
      plugin: skip_on_empty
      method: row
    -
      plugin: migration
      migration: file
      source: fid

Then the entire blog node is skipped if there is no image. How can I just skip trying to migrate the image if there is none?
Answer: I a similar issue on a previous migration, I found that a core issue sometimes causes that error.
The patch submitted fixed the problem on my case.


Find the range of $y$ in a DE

Question:
Consider the equation $$y' = y^2 - y - 2 = (y+1)(y-2).$$ If $y(10) = 0$, find the range of $y(t)$ for $t>10$. That is, find the best $A$ and $B$ such that $A<y(t)<B$ for $t>10$.

From integration by parts, and using $y(10) = 0$, I get the equation $$2e^{3t-30} = \frac{|y-2|}{|y+1|}.$$
Let $f(t) = 2e^{3t-30}$.
Since it's for $t>10$, $f(10) = 2$, and we have $2=\frac{|y-2|}{|y+1|}$. Depending on the sign I choose to use, I get either that $y=-4$ or $y =0$. Since $t: 10 \rightarrow \infty$, either $y=-4$ or $y=0$ is the lower bound.
For $t \rightarrow \infty$, we have $\infty = \frac{|y-2|}{|y+1|}$ (I realise this is not really considered a valid equation...). But considering how the numerator and denominator are both $y$ (the largest power, that is), I don't see how it could tend to $\infty$.
Any help would truly be appreciated!
Answer: Disclaimer: the below is not a rigorous argument but an outline of one.

It is much easier to note that for $-1<y<0$ we have
$$y'=(y+1)(y-2)<0$$
That is to say, $y$ is decreasing for this range. One can note that $y=-1$ is attractive, since $y'<0$ for $y>-1$ and $y'>0$ for $y<-1$. That is, it's not possible to leave $y=-1$ once you've reached it. Likewise, there are no such other points for $y\in(-1,0)$, and so $y$ does not have an asymptote above $y=-1$. Thus, the range is given by $(-1,0)$ for $t\in(10,\infty)$.
Comment: Hello, I really do appreciate your help, but I'm a little confused because your answer and the other answer posted here are a little bit different. Could you please check this again?
Comment: I've commented on the other answer noting the loss of sign.
Answer: $$y'=(y+1)(y-2) \implies \int \frac{dy}{(y+1)(y-2)}= \int dx+C$$ $$ \implies \int \frac{1}{3} \left ( \frac{1}{y-2}-\frac{1}{y+1} \right) dy=x+c \implies \ln\frac{(y-2) }{(y+1)}=(3x+3C)$$ $$ \implies \frac{y-2}{y+1}=e^{3x+3C}>0 \implies y<-1 ~~or ~~ y>2.$$
 Hence the range is $y \in (-\infty, -1) \cup y\in (2,\infty)$.
Comment: Thank you very much, Please see my sedit now.
Comment: Hello, I really do appreciate your help, but I'm a little confused because your answer and the other answer posted here are a little bit different. Could you please check this again?
Comment: @singularly Now I have written it more clearly, please see. You a so tell what answer you are expecting.
Comment: Substituting $y(10)=0$ into the end, you get a false equation. This is due to a loss of sign, as you should have absolute value bars in the logarithms. Note also that $y+1=0$ and $y-2=0$ cannot occur in your explicit equation, which is in agreeance with my answer. So the range is restricted to one of $(-\infty,-1),(-1,2),(2,\infty)$.
Comment: $y \in (-1,2)$ would make LHS  negative but RHS is positive: $^{3x+3C}$

Find the range of $y$ in a DE


Why doesn't a cloned theme work as the original theme?

Question: I've cloned a theme, by duplicating and renaming it, in /sites/all/themes/. When I switch to the new theme, portions of the theme, a slideshow, don't work.
It looks like views_get_view_result() in template.php is not returning anything. Is there some configuration I need to set up per theme?
I'm new to Drupal and I am helping out a friend. The site is using Drupal 7.
Comment: where you have written the `views_get_view_result()` in template.php. also make sure the name of your theme is properly replaced wherever required
Comment: Can you clarify where the name of the theme is to be replaced? If I have a function call `theme_preprocess_page` should that be renamed `theme_clone_preprocess_page`?
Comment: If the original theme was named `theme`, and the new one is named `theme_clone`, then yes, exactly that. Also make sure you've updated the .info filename
Comment: Depending on which user you used for the "*I've cloned a theme*", it could also be a file permission issue ...
Answer: In template.php the functions that begin with the template name e.g. themename_preprocess_page need to be renamed to have the new theme name in them e.g. newthemename_preprocess_page.


Migrate ESXi vm to qcow2 with settings preserved?

Question: I have attempted to export a vm in ESXi which produced 3 files:

vm_name.ovf (12KB)
disk-0-2.vmdk (73KB)
disk-1.vmdk (1.2GB)

I assumed the larger file (disk-1.vmdk) was the flat file and therefore uploaded that to an appropriate folder where I am running EVE-ng within an Ubuntu KVM environment.
I successfully converted the disk-1.vmdk file using qemu-img command and it boots up ok in EVE-ng, however it does not preserve the state/settings of the vm that was operating in ESXi - Am I doing something wrong like exporting or converting the wrong file?
Does just converting the larger vmdk file contain all the info it needs?
In particular it screws the licensing up of the old vm when converting to qcow2 perhaps because it says the digital signature has changed?  (the instance is an F5 BIGIP vm) - I cannot reuse the licenses on another vm - Is there anything I can do to preserve the original vm for this migration between environments?
Answer:
Am I doing something wrong like exporting or converting the wrong
  file?

You're literally only converting the virtual disk file, not the VM description file - for a VMware VM that data is in a .vmk file, once exported it's in the .ovf file - no idea if there's a converter for you but it's usually readable text.
Answer: The BIG-IP license will "become" invalid because the software detected a hardware signature change and it no longer matches is initial dossier state when it was created (system hash for a deployed instance). This is on purpose due to it's nature as a security device.
However, you CAN call F5 support and get the license released so you can relicense the system. I do this on occasion for my dev lab BIG-IP license when I move it around virtual states. As long as it's a valid system serial & license, it's not an issue.


What would be the set operations of my set?

Question: Let's suppose I wanted to create the states a light switch could be in and the ways I could operate one using a set. The switch looks like this (which is an istock photo from user crrussel):

Consider a set $L$ of the following elements:
{up, down}
What operation would I use to go from switching up or down? Could it be something like this?
$up + down = down$?
Or would I have to define some operator $switch$ such that it turns element $a \mapsto b$ where $b$ is the other element of the set $L$? Like this:
$switch\ up \mapsto down$
Just trying my hand at understanding a general intuition of sets by creating my own and seeing if my rules hold properly.
Answer: Consider a set $L := \{ U,D \}$ whose elements correspond to the switch being in the up or down position respectively. What you can do is define two functions called "switch up" $SU: L \to L$ and "switch down" $SD: L\to L$. The notation $L \to L$ means that the functions map element from $L$ to elements in $L$. The action of $SU$ is that it will take either element of $L$ and map it to the up position (since if the switch is already up, pushing it upward will do nothing). Similarly the action of $SD$ is that it will take either element of $L$ and map it to the down position. The two functions acting on this finite set can be visualized as
$\hskip{6cm}$
$\hskip{6cm}$
This is simply one of many ways to represent these operations. We could also look at the matrix representations of these operators. If we define the two elements as column vectors $U := \begin{pmatrix} 1 \\ 0 \end{pmatrix}$ and $D := \begin{pmatrix} 0 \\ 1 \end{pmatrix}$ then we can represent the switch operators as $$SU =\begin{pmatrix} 1 & 1\\ 0 & 0 \end{pmatrix}$$ and $$SD =\begin{pmatrix} 0 & 0\\ 1 & 1 \end{pmatrix}$$ as then $SU(U) = U, SU(D) = U, SD(U)=D$ and $SD(D)=D$ so the operators have the correct action on the elements of $L$. This representation is nice as composing operations corresponds to matrix multiplication, i.e. if the switch is initially in the down position and the operations performed are switch up, switch down, switch down the resulting state of the switch can be calculated as $$SD \cdot SD \cdot SU \cdot D$$ and by the associative property of matrix multiplication you can calculate $SD \cdot SD \cdot SU$ first and then apply it to $D$.
Answer: Since this is kind of a loose question, I would say the most natural thing would be to have the operator $switch$ operate on the set, to transform up to down and down to up. More natural though, I would say, is to have the group $\{\text{Leave Alone}, \text{Switch}\}$ to act on the set $\{\text{Up}, \text{Down}\}$ in the obvious ways.
Answer: Binary or unary (or other) operations?
For unary operations:  $*:L\rightarrow L$. A unary operation can basically be thought of as a function with $f(x) = *x$.  $|L|=2$ there are $2^2=4$ possible operations.  (there are two possible outcomes for each of the two possible inputs).  They would be $*u = u; *d=u$ (Always switch  up), $*u=u; *d=d$ (Leave switch alone), $*u=d;*d=u$ (Always toggle switch), $*u=d; *d=d$(Always switch down).
For binary operations: $*:L\times L \rightarrow L$.  There are $|L\times L| =4$ and so there are $|L|^{|L\times L|} = 2^4 = 16$ possible operations.  (There are two possible outcomes for each of the four possible pairs).  Each operation can be listed as a list of the four possible pairs and the value returned by combining them.
The sixteen are:
1)$d*d=d;d*u=d;u*d=d;u*u=d$. Or $x*y=d \forall x,y$. This can be thought of as a trivial operation.
2)$d*d=d;d*u=d;u*d=d;u*u=u$.  Or $x*y=u \iff x=y=u$. This can be thought of as "multiplication" with $u\equiv 1; d\equiv 0$.
3)$d*d=d;d*u=d;u*d=u;u*u=d$.  Or $x*y=u \iff x=u;y=d$. This is not associative.
4)$d*d=d;d*u=d;u*d=u;u*u=u$. Or $x*y=x$.
5)$d*d=d;d*u=u;u*d=d;u*u=d$. Or $x*y= u \iff x=d;y=u$.
6)$d*d=d;d*u=u;u*d=d;u*u=u$. Or $x*y=y$.
7)$d*d=d;d*u=u;u*d=u;u*u=d$. Or $x*y = u \iff x=y$.  This can be that as "addition" if $d\equiv 1; u\equiv 0$.
8)$d*d=d;d*u=u;u*d=u;u*u=u$. Or $x*y = d \iff x=y=d$. This can be multiplication with $d\equiv 1$.
... etc.
Comment: 1) For the unary operations (which I think is more what I was naturally inclining to), why are the operations "Always switch up" or "Always switch down" or "Always toggle switch"? Why not "Operation resulting in up" and "Operating resulting in down" and "Operation resulting in leave the switch alone"? Especially "Always toggle switch". Not sure how that's unique and not a combination of up and down operation results. I think my confusion on the matter highlights a key misunderstanding I have. 2) The binary op bit confuses me, such as $d * u = d$. Sounds like first down, switch up = down?
Comment: "Always switch up" = "operation resulting in up".  "Not sure how that's unique and not a combination of up and down operation results. "  Um... you never said an effing thing about uniquess or combinations. But they are unique in that toggle (u->d;d->u),stay(u->u;d->d),up(u->u,d->u) and down(u->d,d->d) are four different things.  ANd they are not combinations as they are conditional dependent.  The binary op is not an operation on one switch.  It's an operation on two switches that results in a single switch result.  It is not what you want at all.


Checking solution question for radius of convergence.

Question: I'm checking if work is correct here: find radius of convergence for these:
a) $\sum \frac{(x-1)^n}{n^2+5}$
b) $\sum \frac{3(x+2)^n}{n^n+1}$
c) $\sum \frac{(n+2)!(3x)^n}{4 (5)^n+3^n}$
d) $\sum\frac{n^4 (2x+5)^n}{\sqrt{n^2+n+1}}$
So these all from $1$ to $\infty$. I make the test for radius of convergence $\lim{n \to \infty}|\frac{a_{n+1}}{a_n}|$, and the answers I have:
a) $L=0$
b) $L=0$
c) $L=\frac{83}{5}$ (but it might be wrong)
d) $L=1$
If $L=0$, then it's all infinity. So a, b is infinity for radius of convergence. For c), is $\frac{5}{83}$? I can't know if my limit is correct for c). For d), the radius is 1.
Comment: Can someone check answers? It's one day now
Answer: c) Writing $(3x)^n=3^{n}x^{n}$ we have
$$\frac{a_{n+1}}{a_n}=\frac{(n+3)!3^{n+1}}{4 (5)^{n+1}+3^{n+1}} \frac{4 (5)^{n}+3^{n}}{(n+2)!3^{n}}
=3(n+3) \frac{4+(0.6)^n}{20+3 (0.6)^n} \to \infty $$
hence radius of convergence is $0$.
Comment: Note, for the other examples I'm getting as radius R of convergence
a) $R=1$, b) $R=\infty$ d) $R=\frac{1}{2}$


Automatically localize all numbers on a web page

Question: I'm wondering if there is a programmatic way of detecting all instances of numbers on a web page (e.g. 1, 34, 558, 6, etc.) and convert them to equivalents in other languages of the site.
For example, if I have a bilingual site that has English and Arabic. On the English page there is a number "12345". It's coming from the database, so the numbers are stored as 12345 etc. in the database. Now, on the Arabic version of the site, I can translate all words etc. but numbers still show as 12345. I want to display Arabic numbers instead. It's impossible to translate the numbers because they are generated dynamically and keep changing.
I guess some sort of "on-the-fly" solution is what I'm looking for?
Comment: @albert Arabic numbers are definitely different from English. There is a bit of confusion regarding the naming of the two since the current English numbers [are originally Arabic](http://en.wikipedia.org/wiki/Arabic_numerals). [These](http://en.wikipedia.org/wiki/Eastern_Arabic_numerals) are the current Arabic numbers.
Comment: It's certainly possible. There's not really a particularly smart way to do it, just replace the numbers when they are being added to the page content if you are serving the arabic version of the page
Comment: If you could elaborate more with an example/code etc. it would be helpful, because this is still vague to me :)
Comment: are Arabic numbers different from English? clearly there is some difference, but I can't figure it out. quick google, this Arabic font has English looking numbers. http://www.dafont.com/alhambra.font  but I'm not so sure that's a font for Arab language, in context of your question, makes me think its just styled to look like Arabic. I think I have a solution for you, without programming anything, but I need an Arabic font for the demo.
Comment: @Hassan i was pretty sure about that, thanks for clarification. know where i can get an open source font with those numbers?
Comment: @albert, no particular font is in my mind now, but i've found a couple on cooltext.com including [this one](http://cooltext.com/Download-Font-B+Jadid)
Comment: @hassan i can't see characters on my box. probably bc its westernized? i'll look for a solution. essentially you want to create two font-family declarations, english and arabic, and use ltr or rtl attribute on html element to swap out fonts for reach. or that is what i am thinking. can't test without proper materials. pretty sure it'll work though.
Comment: It would be best to do the formatting when you "assemble" the pieces together (the web page template + the data from the database). Global tinkering with the final page is unreliable.
Answer: I don't believe there will be a way in HTML on the fly, you're going to need a language with a bit more umph, Javascript or PHP for example. Someone else will have to show you a JS example, but for PHP, you can do:
function eng_to_arabic($strTextToChange)
  {
    $strArabicNumbs = array('٩','٨','٧','٦','٥','٤','٣','٢','١','٠');
    $strEnglishNumbs = range(0, 9);

    return str_replace($strArabicNumbs, $strEnglishNumbs, $strTextToChange);
  }

Then you can call the function with
echo eng_to_arabic($strSomeNumber);


Gravar um cód na tarja magnética

Question: Eu tenho uma impressora Evolis Dualys 3 que tem a opção de gravar um cód na tarja magnética do cartão, pelo software de terceiros a gravação foi realizada com sucesso, agora eu gostaria de fazer essa gravação pela minha aplicação, alguém já fez algo parecido?
Me enviaram um SDK do fabricante mas ao tentar executar o mesmo aparece o seguinte erro:
Answer: Tente mudar a configuração de ANYCPU para x86 nas configurações do projeto:
Comment: Era isso msm, vlw..

Gravar um cód na tarja magnética


When is partial differentiation commutitive

Question: Consider a function: $$f:\mathbb R ^2\to\mathbb R $$
when does $$\dfrac {\partial f(x,t)}{\partial t\partial x}=\dfrac {\partial f(x,t)}{\partial x\partial t}$$
Thinking about it in terms of the limit definition of derivative,
and thinking about it as taking slices of surfaces and measuring the slope on the edge,
seems to be giving me the feeling that answer is always.
However I have some memories of there being requirements like piecewise continuous, and smooth.
What is the full set of conditions?
Comment: It's true where the partial derivatives are all continuous. (But not an iff statement as far as I'm aware).
Comment: ah11950: That sounds like an answer (not a comment). Why don't you post it as an answer?
Comment: The point is that the discrete version of your formula, that is
$$\Delta_t\Delta_x f = \Delta_x \Delta_t f, $$
where $\Delta_t f(x, t)=f(x, t +h)$ for a fixed increment $h$, is always true. However, to infer from this that partial derivatives commute you need a limiting process and so you need at least some continuity.
Comment: See also [this related question](http://math.stackexchange.com/q/29536/8157)
Answer: It's true where the mixed partial derivatives are all continuous. (But not an iff statement as far as I'm aware).
An example of a function that fails to satisfy equality of mixed partial derivatives is
$$f(x,y) = \begin{cases} \frac{xy(x^2-y^2)}{x^2+y^2} \; &\text{if}\; (x,y) \neq 0\\
0 &\text{if}\; (x,y) = 0\end{cases}$$
At the origin we have $f_{xy}(0,0) = 1 \neq -1 = f_{yx}(0,0)$
Comment: How did you calculate $f_{xy}, f_{yx}$ so easily? Is there some special technique to this?


Vector substring out of range

Question: I'm currently working on a problem and I've been stumped on an error for about 3 hours now. Thus, I've given up being hard headed and I'm looking to the internet to see if someone else's wealth of knowledge can help to solve my problem.
A jist of the program, it takes in input from the command line of any number of numbers. It inserts them into a vector and then performs a series of statistical analysis' on the data set.
Currently, I'm having difficulty with the quintiles function (as my teacher says or "quantiles" for those of you looking it up on Wikipedia).
Logically, my code should work. However, it's seeming to hit an out of range error two before the actual end of the vector that I've created.
Heres the function followed by the functions called inside:
string quintile(vector<double> v) {
    ostringstream oss;
    oss << "Quintile means" << endl;
    vector<unsigned> quintile{ 0 };

    // get range of quintiles and insert into vector
    for (unsigned i = 1; i <= 5; ++i)
        quintile.push_back((v.size() * 0.2) * i);

    // get the mean for each quintile
    for (unsigned i = 0; i < 5; ++i)
        oss << "Q" << (i + 1) << ": " << mean_sized(v, quintile[i], quintile[i + 1]) << "  (" << quintile[i] << ".." << quintile[i + 1] << ")" << endl;

return oss.str();
}

double mean_sized(vector<double> v, int first, int last) {
    double mean = 0.0;
    vector<double> sub;
    for (unsigned i = v[first]; i < v[last]; ++i)
        sub.push_back(v[i]);

    return (accumulate(sub.begin(), sub.end(), mean) / sub.size());
}

Any input is much appreciated as I'm seriously stumped.. I'm going to move on to the last function and hopefully by the time I'm done someone will have graced me with the knowledge to solve that issue.
Thanks!
Comment: Your teacher is correct in calling these "quintile"s as [that's the name for 5-quantiles](https://en.wikipedia.org/wiki/Quantile#Specialized_quantiles), which are what you are dealing with here.
Comment: Good to know! I was wondering why no one mentioned that the Wiki page didn't match up to the name he was using. Makes more sense now, quantiles are the individual parts of a quintile.
Comment: Not quite. If you separate your value population into `q` subpopulations, the values "between" those subpopulations are called "q-quantiles". Thus, if `q`= 5, those are "5-quantiles". "Quintile" is just a synonym for "5-quantile". (Like "Median" is a synonym for the first (and only) 2-quantile, and "percentiles" is a synonym for "100-quantiles", so quantiles for when the population is separated into 2 or 100 subpopulations, respectively.)
Comment: Interesting, so quantile is more of a universal term used for a subset of the population and there can be n number of quantiles (which will essentially change the synonym used to reference the group). Whereas, quintile is a synonym specifically referring to a subset of 5-quantiles, correct?
Comment: Almost. Yes, "quantile" is a more general term than "quintile". And yes, "quintile" is more specific insofar, as the number of same-size subsets is 5 for them. But both terms refer to the values "between" those subsets (the values at the boundaries), **not to the subsets** themselves.
Comment: For a better explanation of the terminology, http://math.stackexchange.com might be the place to go.
Answer: This loop is wrong:
for (unsigned i = v[first]; i < v[last]; ++i)
    sub.push_back(v[i]);

You're using the values in the vector as the range of indexes. You should just be using the range from first to last:
for (unsigned i = first; i <= last; i++) {
    sub.push_back(v[i]);
}

P.S. See Why is it considered a bad practice to omit curly braces?
Comment: You got it! MAN, it's always the easy ones that get away from me.

I'll totally check out that link. To be honest, I only take out the curly braces because the programs I've been writing thus far aren't that complex and it doesn't seem to bother my teacher.

Vector substring out of range


WebSocket Handshake Error with AWS

Question: I'm running a Java server (Jetty, to be specific) on an AWS EC2 instance using WebSocket to connect to a client's browser. When I do this locally (hosting the server on my computer, not AWS), it runs fine. However, when I move the code to an EC2 instance, I get the following error message on the client-side:
WebSocket connection to 'ws://Elastic_IP:8080/?username=name_of_user' failed: Error during WebSocket handshake: Unexpected response code: 500
I made sure that the EC2 instance will accept traffic on port 8080.
On the server-side, I'm getting many java.lang.NoClassDefFoundError when the connection is attempted. I do not get these error when I run it locally. Perhaps there's an issue when I'm compiling on the EC2 instance, however it does compile without error. I'm compiling and running the code using Eclipse locally, but I'm compiling and running the code on EC2 by hand (javac with lots of classpaths). It's likely that I made an error when compiling by hand, but I'm not sure what the error could be.
Any help would be greatly appreciated.
EDIT
After a little trouble-shooting on my own, I realized that JSON.ParseException was the source of issue. After I removed all calls to this class from the server code, the handshake completed and I was able to establish a connection between the server and the client.
However, I am now running into the following error when I receive a message from the client:
WARN:MyWebSocketHandler:qtp990368553-16: Unhandled Error (closing connection)
java.lang.RuntimeException: Cannot call method public void
MyWebSocketHandler#onMessage(org.eclipse.jetty.websocket.api.Session, java.lang.String) with args:
[org.eclipse.jetty.websocket.common.WebSocketSession, java.lang.String]

It seems that I defined the argument to be org.eclipse.jetty.websocket.api.Session, but during runtime the argument is actually org.eclipse.jetty.websocket.common.WebSocketSession. Any ideas on how this is happening or which one (Session vs WebSocketSession) I should use? The only capability I need is to send strings between the server and the client.
Comment: Could you provide the full stacktrace, so that we can see which class, specifically, the JVM is complaining about?  Also, rather than using Eclipse to run your server code locally, could you try running it locally just as you would on the EC2 instance, so that your local environment is closer/more like the one that's on the EC2 instance?
Comment: @Castaglia I fixed the main issue for the handshake (I had to remove an import on the server code, but it does work on the local side with the import), but I'm hitting another road block. I updated the questions to reflect my misfortune.
Answer: I figured out a possible solution to my problem. Through Eclipse, I can Export the Java project to a runnable jar ("packing" the libraries into the jar). Then running it with java -jar <jar_filename> will work on the server and function the same as on the local machine. However, I've notice some performance issues (slow start), so I do not think this is the best solution, however it is a solution.

WebSocket Handshake Error with AWS


Getting a lot of redefinition errors

Question: I am getting a lot of errors, i haven't been able to run this at all, the code isn't mine(code is given online).
Is it my header that's the problem? I know the question is very broad but i'm new to C and these errors are giving me some real trouble. I'm not expecting much but if someone could point me in the correct direction that would be great...
node0.c
   #include <stdio.h>
#include "prog3.h"
extern struct rtpkt {
  int sourceid;       /* id of sending router sending this pkt */
  int destid;         /* id of router to which pkt being sent
                         (must be an immediate neighbor) */
  int mincost[4];    /* min cost to node 0 ... 3 */
  };

extern int TRACE;
extern int YES;
extern int NO;

struct distance_table
{
  int costs[4][4];
} dt0;

/* students to write the following two routines, and maybe some others */

void rtinit0()
{

}

void rtupdate0(rcvdpkt)
  struct rtpkt *rcvdpkt;
{

}

printdt0(dtptr)
  struct distance_table *dtptr;

{
  printf("                via     \n");
  printf("   D0 |    1     2    3 \n");
  printf("  ----|-----------------\n");
  printf("     1|  %3d   %3d   %3d\n",dtptr->costs[1][1],
     dtptr->costs[1][2],dtptr->costs[1][3]);
  printf("dest 2|  %3d   %3d   %3d\n",dtptr->costs[2][1],
     dtptr->costs[2][2],dtptr->costs[2][3]);
  printf("     3|  %3d   %3d   %3d\n",dtptr->costs[3][1],
     dtptr->costs[3][2],dtptr->costs[3][3]);
}

linkhandler0(linkid, newcost)
  int linkid, newcost;

/* called when cost from 0 to linkid changes from current value to newcost*/
/* You can leave this routine empty if you're an undergrad. If you want */
/* to use this routine, you'll need to change the value of the LINKCHANGE */
/* constant definition in prog3.c from 0 to 1 */

{
}

node1
#include <stdio.h>
#include "prog3.h"
extern struct rtpkt {
  int sourceid;       /* id of sending router sending this pkt */
  int destid;         /* id of router to which pkt being sent
                         (must be an immediate neighbor) */
  int mincost[4];    /* min cost to node 0 ... 3 */
  };

extern int TRACE;
extern int YES;
extern int NO;

int connectcosts1[4] = { 1,  0,  1, 999 };

struct distance_table
{
  int costs[4][4];
} dt1;

/* students to write the following two routines, and maybe some others */

rtinit1()
{

}

rtupdate1(rcvdpkt)
  struct rtpkt *rcvdpkt;

{

}

printdt1(dtptr)
  struct distance_table *dtptr;

{
  printf("             via   \n");
  printf("   D1 |    0     2 \n");
  printf("  ----|-----------\n");
  printf("     0|  %3d   %3d\n",dtptr->costs[0][0], dtptr->costs[0][2]);
  printf("dest 2|  %3d   %3d\n",dtptr->costs[2][0], dtptr->costs[2][2]);
  printf("     3|  %3d   %3d\n",dtptr->costs[3][0], dtptr->costs[3][2]);

}

linkhandler1(linkid, newcost)
int linkid, newcost;
/* called when cost from 1 to linkid changes from current value to newcost*/
/* You can leave this routine empty if you're an undergrad. If you want */
/* to use this routine, you'll need to change the value of the LINKCHANGE */
/* constant definition in prog3.c from 0 to 1 */

{
}

node2
#include <stdio.h>
#include "prog3.h"
extern struct rtpkt {
  int sourceid;       /* id of sending router sending this pkt */
  int destid;         /* id of router to which pkt being sent
                         (must be an immediate neighbor) */
  int mincost[4];    /* min cost to node 0 ... 3 */
  };

extern int TRACE;
extern int YES;
extern int NO;

struct distance_table
{
  int costs[4][4];
} dt2;

/* students to write the following two routines, and maybe some others */

void rtinit2()
{
}

void rtupdate2(rcvdpkt)
  struct rtpkt *rcvdpkt;

{

}

printdt2(dtptr)
  struct distance_table *dtptr;

{
  printf("                via     \n");
  printf("   D2 |    0     1    3 \n");
  printf("  ----|-----------------\n");
  printf("     0|  %3d   %3d   %3d\n",dtptr->costs[0][0],
     dtptr->costs[0][1],dtptr->costs[0][3]);
  printf("dest 1|  %3d   %3d   %3d\n",dtptr->costs[1][0],
     dtptr->costs[1][1],dtptr->costs[1][3]);
  printf("     3|  %3d   %3d   %3d\n",dtptr->costs[3][0],
     dtptr->costs[3][1],dtptr->costs[3][3]);
}

node3
#include <stdio.h>
#include "prog3.h"
extern struct rtpkt {
  int sourceid;       /* id of sending router sending this pkt */
  int destid;         /* id of router to which pkt being sent
                         (must be an immediate neighbor) */
  int mincost[4];    /* min cost to node 0 ... 3 */
  };

extern int TRACE;
extern int YES;
extern int NO;

struct distance_table
{
  int costs[4][4];
} dt3;

/* students to write the following two routines, and maybe some others */

void rtinit3()
{
}

void rtupdate3(rcvdpkt)
  struct rtpkt *rcvdpkt;

{

}

printdt3(dtptr)
  struct distance_table *dtptr;

{
  printf("             via     \n");
  printf("   D3 |    0     2 \n");
  printf("  ----|-----------\n");
  printf("     0|  %3d   %3d\n",dtptr->costs[0][0], dtptr->costs[0][2]);
  printf("dest 1|  %3d   %3d\n",dtptr->costs[1][0], dtptr->costs[1][2]);
  printf("     2|  %3d   %3d\n",dtptr->costs[2][0], dtptr->costs[2][2]);

}

header file
/* libraries */
#include <stdlib.h>

/* definitions */

#define INF 999

#ifndef FALSE
#define FALSE (0)
#endif
#ifndef TRUE
#define TRUE (!FALSE)
#endif

struct rtpkt {
    int sourceid;       /* id of sending router sending this pkt */
    int destid;         /* id of router to which pkt being sent
                                                 (must be an immediate neighbor) */
    int mincost[4];    /* min cost to node 0 ... 3 */
};

struct event {
   float evtime;           /* event time */
   int evtype;             /* event type code */
   int eventity;           /* entity where event occurs */
   struct rtpkt *rtpktptr; /* ptr to packet (if any) assoc w/ this event */
   struct event *prev;
   struct event *next;
};

struct distance_table
{
    int costs[4][4];
    int link[4];
};

/* forward declarations */
void init();
void tolayer2(struct rtpkt packet);
void insertevent(struct event *p);
void rtupdate0(struct rtpkt *rcvdpkt);
void rtupdate1(struct rtpkt *rcvdpkt);
void rtupdate2(struct rtpkt *rcvdpkt);
void rtupdate3(struct rtpkt *rcvdpkt);
void linkhandler0(int linkid, int newcost);
void linkhandler1(int linkid, int newcost);
void rtinit0();
void rtinit1();
void rtinit2();
void rtinit3();
void sendpkt0();
void sendpkt1();
void sendpkt2();
void sendpkt3();
void printdt0(struct distance_table *dtptr);
void printdt1(struct distance_table *dtptr);
void printdt2(struct distance_table *dtptr);
void printdt3(struct distance_table *dtptr);

main:
http://gaia.cs.umass.edu/kurose/network/prog3.c
i added the following at the top:
#include "stdafx.h"
#include "prog3.h"

Answer: Haven't looked closely enough to see if it is your only problem, but the redefinition errors are undoubtedly coming from including the header at the top of each c file without any sort of precompiler checking to determine if the header's symbols have already been declared.
Put something like this at the top of the header:
#ifndef _PROG3_H
#define _PROG3_H

And at the bottom of your header file:
#endif

This ensures that if each file is inspected individually by the compiler, the compiler knows you have declared the required symbols. However, if all files are being linked together, you do not get all of the symbols in the header file defined once for each object file you try linking.
EDIT: Now I have looked through some of that code, and, although the header file problem I mentioned definitely needs to be addressed, it is not the only place you are redefining things. Again and again you declare rtpkt as extern in the C files even though you have also included a definition of it from the header file. If it is in the header, you do not want to put it in the C file as well. I see you have distance_table defined numerous times as well. Again, if it is in the header and included that way, do not redefine it in your C file.
Comment: so can i just get rid of the header file completely then?
Comment: well, you need to understand the intention of the code. Headers are very useful for allowing multiple classes to use the same data structures in a type-safe manner. Again, without actually spending the extra time to understand the ins and outs of the code you posted above, it looks like the header is a good place to put the `rtpkt` definition because it is the same def in every file. Remove the `extern rtpkt` defs from each C file. On the other hand, the `distance_table` structs are given a different alias in each C file, for whatever reason, so remove that def from the header.
Comment: Because decisions like "what to put in a header file" can be such broad discussion topics and you will gain an understanding for the conventional wisdom on the topic as you write more code and read more tutorials, StackOverflow is not a very good forum for discussing it further. Feel free to try and remove duplicate definitions based on my suggestions, but I get the impression that modifying the above code might be a bit beyond your experience level at the moment. The internet is great, but you might find a good book on C programming a lot more helpful.

Getting a lot of redefinition errors


Extend java class in clojure: how to override only one of two similar methods?

Question: I have the following java class.
public class Toto {
    public void aMethod(A a) {
        System.out.println("A " + a);
    }

    public void aMethod(B b) {
        System.out.println("B " + b);
    }
}

I want to override aMethod(A a) but not aMethod(B b). The only way I could do that was:
(ns titi
    (:gen-class :extends Toto
     :exposes-method {aMethod parentMethod}))

(defn- -aMethod [this x]
    (if (= (type x) A)
        (println "ok do something here")
        (.parentMethod this x)))

Is there a better way to do this? (I mean without checking type of x myself).
Answer: According to http://dishevelled.net/Tricky-uses-of-Clojure-gen-class-and-AOT-compilation.html, with :gen-class it is possible to override by signature but I couldn't find documentation on that, so I guess it can be considered "internals" and it may break in the future.
Anyway, supposing you have your Toto class in package jpkg together with two empty classes A and B, this works for me:
(ns Titi
(:import [jpkg A])
    (:gen-class :extends jpkg.Toto
                :exposes-method [aMethod]))

(defn- -aMethod-A [this x]
    (println "clj a"))

As the following main namespace:
(ns main
    (:import [jpkg A B]))

(set! *warn-on-reflection* true)

(defn -main []
    (. (new Titi) aMethod (new A))
    (. (new Titi) aMethod (new B)))

prints:
clj a
B jpkg.B@6631f5ca

instead of:
clj a
clj a

Type hints instead seem not to help here.