Alterar valor de elemento select (Ajax + php) com innerHTML

Question: Olá, estou fazendo o famoso combo de estado carrega cidade.
Está funcionando tudo perfeitamente, conforme depurei no meu script, até o momento que deve alterar o valor do select (options retornados da função).
Segue meu código (index.php):

    Endereço*

        <select class="selectpicker" data-width="auto" id="estado" name="estado">
    <?php
            $query = "SELECT SIGLA, CODIGO FROM estado ORDER BY TX_SIGLA";
            $result = mysqli_query($conectar, $query);
            while ($resultado = mysqli_fetch_assoc($result)) { ?>
                <option value="<?php echo $resultado['CODIGO']; ?>"><?php echo $resultado['SIGLA']; ?></option>
    <?php   } ?>

        </select>

        <select data-width="auto" id="municipio" name="municipio" class="selectpicker">
            <option value="0" disabled="disabled">Escolha o estado</option>
        </select>

Código (cidade.php):
<?php
if (isset($_POST["cd_estado"])) {

    $cod_estado = $_POST["cd_estado"];
    $query = "SELECT NOME, CODIGO FROM municipio WHERE ESTADO = '$cod_estado' ORDER BY NOME";
    $result = mysqli_query($conectar, $query);

    while ($resultado = mysqli_fetch_assoc($result)) {
        echo '<option value="' . $resultado['CODIGO'] . '">' . $resultado['NOME'] . '</option>';
    }
} else {
    echo "<option value='0'> Sem cidade </option>";
}
?>

Script:

Já tentei alterar o valor do select "municipio" com as seguintes alternativas:
$("#municipio").html(data);
$("#municipio").append(data);
document.getElementById("municipio").innerHTML = data;
$("select[name=municipio]").html(data);

Nenhuma funciona. Mas no "console.log(data);" o valor está sendo retornado corretamente.
O que estou fazendo de errado?
Comment: Como está vindo o retorno `data` na função Ajax?
Está vindo no formato `Cidade X` ?
Comment: Sim, está retornando corretamente. Meu problema é não conseguir alterar o conteúdo da Div. Nem mesmo com o valor `Cidade X ` dentro do próprio script.
Comment: Estou pensando que possa ser algo com o Bootstrap mesmo, mas ainda não sei o que é. Pois testei meu código em uma página limpa, sem framework, e ele funciona de todas as maneiras.
Answer: Para inserir os options no seu select faça da seguinte forma:
municipios = document.getElementById('municipio');

municipios.options[municipios.options.length] = new Option('Texto', 'Valor');

e para zerar os valores basta apenas usar:
municipios.options.length = 0;

Comment: Obrigada pela resposta. Neste caso tentei enviar duas variáveis do php (cidade.php) através de:        echo json_encode($retorno); Sendo o $retorno um array com os dados do banco, e no script receber através do         var resultado = JSON.parse(data); . Porém não consegui.
Comment: Almer, não deu certo sua sugestão. Apesar de conseguir resolver o meu problema com Json, não está alterando os options.
Answer: Olá, eu mudaria algumas coisas, coisas simples.
No seu PHP eu retornaria um array de cidades, ficaria mais ou menos assim:
<?php
$response = [];
if (isset($_POST["cd_estado"])) {

    $cod_estado = $_POST["cd_estado"];
    $query = "SELECT NOME, CODIGO FROM municipio WHERE ESTADO = '$cod_estado' ORDER BY NOME";
    $result = mysqli_query($conectar, $query);

    while ($resultado = mysqli_fetch_assoc($result)) {
        $response[$resultado['CODIGO']] = $resultado['NOME'];
    }
} else {
    $response[0] = "Sem Cidade";
}
echo json_encode($response);
?>

No arquivo javascript, eu faria da seguinte forma:

Answer: Eu já tive um problema parecido, e se for o mesmo que o meu, seu problema está no refresh do Selectpicker e não do retorno, estou assumindo que você está usando o Selectpicker(bootstrap-select). Veja se isso te ajuda, eu fiz algumas melhorias na sua requisição.
No seu código o retorno é em HTML, então acrescentei o dataType: 'HTML', coloquei também a variável $this_estado ela possibilita você acessar os elementos navegando pelo DOM, no caso aqui ela assume o valor do caminho absoluto do seu elemento #estado.
Também adicionei o beforeSend, que ajuda a configurar um load mais real, baseado no tempo do retorno do seu código, se quiser ver ele em conexões rápidas coloque um sleep(1), no topo do seu arquivo cidade.php.
E o grande ponto aqui é $('.selectpicker').selectpicker('refresh'); que atualiza o Selectpicker para mostrar seus dados na tela.
OBS: Não entende o pq do innerHTML, mas se ele for obrigatório por algum motivo é só você adaptar, mas como já está usando jquery o código abaixo funciona da mesmo forma.


Prove $\lim_{x\to a} f(x)$ exists $\implies \lim_{x\to a} f(x^2)$ exists

Question: Want to prove rigorously (if possible, since I was not able to think of any counter-example) that  $\lim_{x\to a} f(x)$ exists $\implies \lim_{x\to a} f(x^2)$ exists.  (I also have a feeling that the limits equate.)
I started with the $\epsilon-\delta$ definition of $\lim_{x\to a} f(x) = l$ which states that $\forall \epsilon >0 \exists \delta>0 \forall x:0<|x-a|<\delta \implies |f(x)-l| < \epsilon$.
Now I want to show that $\forall \epsilon >0 \exists \delta>0 \forall x:0<|x-a|<\delta \implies |f(x^2)-l_1| < \epsilon$ where $l_1 \in \mathbb{R}$.
I've got no clue how to continue.  All help is appreciated.
As an additional note: I believe the converse ($\lim_{x\to a} f(x^2)$ exists $\implies \lim_{x\to a} f(x)$ exists) is not true as $f(x)=\frac{|x|}{x}$ is a counter-example.
Edit: A counter-example was found for the statement but I was wondering whether it is true for $a = 0$?  So in other words, I would like to prove or disprove the statement $\lim_{x\to 0} f(x)$ exists $\implies \lim_{x\to 0} f(x^2)$ exists
Comment: The claim is false if $f$ doesn't have a limit at $a^2$.
Answer: This is false, as evidenced by the choices $a=2$ and $f(x) = \begin{cases} x, & x \leq 4 \\ x+1, & x>4.\end{cases}$
Comment: You asked a question, got a good answer. Please don't change it now. You can ask a new question if you want.
Comment: @SaranWrap I don't think that's fair, you should post a new question.
Comment: Right.  I was then wondering if it was true if a = 0?
Comment: Well that's a different question.
Comment: Yea let me edit that on sorry about that
Comment: Alright thats fair sorry about that
Comment: Anyway, do you know how to define a limit using sequences? You can try using it for the case $a=0$. If $x_n$ is a sequence of non-zero real numbers which converges to $0$, then what happens to the sequence $f(x_n^2)$?
Comment: @Mark No I'm not familiar with that method, however I can try looking into it.
Comment: Alright, then you can work with $\epsilon$ and $\delta$, it's also easy. For a given $\epsilon$ there is some $\delta_0$ such that $|x|<\delta_0$ implies $|f(x)-L|<\epsilon$. So now simply take $\delta=\sqrt{\delta_0}$. If $|x|<\delta$ then $|x^2|<\delta_0$ and hence $|f(x^2)-L|<\epsilon$.
Answer: It is always true for $a=0$ and $a=1$ otherwise just assume a discontinuous function at $x=a^2$.


Showing that an element generates the kernel of a homomorphism

Question: I have the ring homomorphism $\phi:\mathbb{Z}[\sqrt{-3}]\rightarrow \mathbb{Z}_{19}$ given by $\phi(a+b\sqrt{-3})=\overline{a+4b}$.
I am being asked to find an element $a+b\sqrt{-3}$ such that $\ker(\phi)=(a+b\sqrt{-3})$, and show that the element does indeed generate $\ker(\phi)$.
I have shown that $\ker(\phi)=(4-\sqrt{-3})$. However I am not really sure what the second part is asking.

Does this mean that $\ker(\phi)$ cannot be written as any other ideal, i.e. cannot be written in the form $(a+b\sqrt{-3})$ for different $a$ or $b$, or $(a+b\sqrt{-3},c+d\sqrt{-3})$ for example?
Answer: As Chris Custer says, if you show $\ker\phi = (a + b\sqrt{-3})$, then you have shown that this element generates the kernel. But it is not necessarily true that this is the only element generating the ideal, for instance, if $u$ is a unit in $\mathbb Z[\sqrt{-3}]$, then $u\cdot (a + b\sqrt{-3})$ will generate the same ideal.
By solving the equation $a^2 + 3 b^2 = 1,$ we see that the only units in the ring are $1$ and $-1$, so in a sense, $4 - \sqrt{-3}$ and $-4 + \sqrt{-3}$ are the only elements that generate the kernel as a principal ideal.
I'm thinking that the question might have been "find an element $a+b\sqrt{-3}$ such that $(a + b\sqrt{-3}) \subset \ker\phi$, and show that this element does indeed generate $\ker\phi$". Which would then turn our focus to proving $4 -\sqrt{-3}$ is irreducible.
To do so, we have a look at the norm function $N(a+b\sqrt{-3}) = a^2 + 3b^2$, which we have already used to find units ($a+b\sqrt{-3}$ is a unit if and only if it has norm $1$). This function satisfies $N(\beta\gamma) = N(\beta)N(\gamma)$. We have $N(4-\sqrt{-3}) = 27$, so factorisations of $4-\sqrt{-3}$ correspond roughly to factorisations of $27=1\cdot 27 = 3\cdot 9$.
Looking for an $\alpha$ such that $N(\alpha) = 3$, we find $\alpha = \pm\sqrt{-3}$. However, neither of these divide $4-\sqrt{-3}$: if $4-\sqrt{-3} = (c+d\sqrt{-3})(\pm\sqrt{-3}) = \mp 3d \pm c\sqrt{-3}$, which cannot happen since $3$ doesn't divide $4$. Hence, if $4 - \sqrt{-3} = \beta\gamma$, we must have $N(\beta\gamma) = N(\beta)N(\gamma) = 27$, with $N(\beta) = 1$ and $N(\gamma)=27$. This implies that $\beta$ is a unit, and so $4-\sqrt{-3}$ is irreducible.
Answer: If you have shown that $\operatorname{ker}\phi=(4-\sqrt{-3})$, then you have completed the task.
The other questions you asked are just that, other questions.  For instance, if it turns out you have a unique factorization domain (UFD), or a principal ideal domain (PID), then we could probably answer both questions in the affirmative.  But this would require some proof.
Actually, since $\Bbb Z_{19}$ is a field, the ideal $(4-\sqrt{-3})$ is maximal.  I suspect that means that the generator, $4-\sqrt{-3}$, is prime.
Then the answers to the other questions appear to be yes, but I am going to have to defer to authority here, as ring theory is not my strong suit.


Accessing HealthMonitoring Provider settings programmatically

Question: I have set up ASP.Net health monitoring in web.config:
<healthMonitoring enabled="true">
<providers>
<clear />
<add name="CriticalMailEventProvider" type="System.Web.Management.SimpleMailWebEventProvider"
from="email@example.com" to="firstname.lastname@example.com"
bodyHeader="Application Error!" bodyFooter="Please investigate ASAP."
subjectPrefix="ERROR: " buffer="true" bufferMode="Critical Notification"
maxEventLength="8192" maxMessagesPerNotification="1"
/>
</providers></healthMonitoring>

And I am attempting to read the configuration of this provider in code:
Dim HealthMonitoring As System.Web.Configuration.HealthMonitoringSection
Dim ToAddress As String
HealthMonitoring = CType(WebConfigurationManager.GetWebApplicationSection("system.web/healthMonitoring"), HealthMonitoringSection)
ToAddress = HealthMonitoring.Providers(0).ElementInformation.Properties("to").Value.ToString

[Note: not actual production code, hard-coded & condensed for brevity]
The problem: While the ElementInformation.Properties collection contains the keys as expected, the Value is "Nothing" and so are all other properties of "Properties("to")".
How can I access the settings of the Provider?
Comment: anysolution , any sample complete code?
Answer: In C#:
HealthMonitoringSection section = WebConfigurationManager.GetWebApplicationSection("system.web/healthMonitoring") as HealthMonitoringSection;

section.Providers[3].Parameters["to"] returns "firstname.lastname@example.com".
(3 assumes that the providers list wasn't cleared in web.config.)
Comment: I'm sure I tried the Parameters collection but it works now, cheers.
Answer: I've resorted to reading the web.config file as an XML document and using the nodes selected with the XPath: configuration/system.web/healthMonitoring/providers/*[@name]
Answer: Based on AUSteve's answer I used the below code.
Dim xmldoc As New System.Xml.XmlDocument
xmldoc.Load(HttpContext.Current.Server.MapPath("Web.config"))
Dim xmlnsManager As System.Xml.XmlNamespaceManager = New System.Xml.XmlNamespaceManager(xmldoc.NameTable)
xmlnsManager.AddNamespace("nc", "http://schemas.microsoft.com/.NetConfiguration/v2.0")

Dim emailTo As String = xmldoc.SelectSingleNode("/configuration/system.web/healthMonitoring/providers/add", xmlnsManager).Attributes("to").Value.ToString

Answer: You can use the Initialize method to access the attributes you specified in the web.config. Just access the NameValueCollection (and remove it your custom attributes before base.Initialize is being called)
This article shows a C# implementation: http://www.tomot.de/en-us/article/6/asp.net/how-to-create-a-custom-healthmonitoring-provider-that-sends-e-mails


How do we stop the heartbeat module from recording node update activity for certain specific content types we have created?

Question: How do we stop the heartbeat module from recording node update activity for certain specific content types we have created?
We created a content type that collects voting information. When a user votes, a new node is created or an existing node is updated for this content type.
The heartbeat module seems to be recording this event and creating a new activity. In Drupal Commons this activity is displayed in a block called the "Recent Activity" block. We would like to avoid having this update to our "voting" content type from being recorded as an activity, and being shown in the "recent activity" block.
How would we do this?
Answer: seems like you use D6 since you mentioned Commons. I've only used Heartbeat in D7. Click on the "heartbeat streams" settings and you have an option for "Choose message types you want to deny from display". There you can select the ones you do NOT want to record. Repeat that for each of the streams.
Also, checkout the "heartbeat templates" for "add_node" and "edit_node", there is an option "Disable the message - Defines whether this message template is disabled from logging and viewing."


Construct a special $C_0^\infty$ function

Question: I'am quite curious about how to construct a nonnegative $C_0^\infty$ function $f(x)$ satisfying for $1<p<\infty$
$$
f(0)=1~~~~~\text{and}~~~~~\sum_{k\in \mathbb Z^n}f(x+k)^p=1.
$$
It seems easy to construct such a function in $\mathbb R^1$.
We first construct a nonnegative radial function $f\in C_0^\infty(\mathbb R^1)$ and $\operatorname{supp}f\subset (-1,1)$. $f$ also satisfies $f(0)=1$ and $f(\tfrac 12)=\tfrac 12$. (We can ask for such $f$ equals to 1 in a small neighborhood of $0$.)
Then we ask that $f(x)+f(x-1)=1$ for $x\in [0,1)$. Note that this can be done if we first aske for the smoothness in $[0,1/2)$ and just by let $f(1-x)=1-f(x)$ for $x\in (0,1/2)$.
And just by letting $g(x)=f(x)^{1/p}$, we finish this.
My question is:
(1) We know that the lattices contained in the unit ball is related to the dimension, and how to extending the construction to $\mathbb R^n$ (It can not be just rotation to get a $\mathbb R^n$ function.)
(2) I think there are some other convenient way to constrcut such a funcion.
(3) I think the construction has nothing to do with $p$, is it right?
Thanks in advance. I hope to get some help from you.
Comment: take a look into the [Rvachëv function](https://oeis.org/A288163)
Comment: also on the [Fabius function](https://en.m.wikipedia.org/wiki/Fabius_function)
Comment: Yes, thank you for your comments
Answer: The answer is rather simple.
First, let $h(x) = e^{-1/x}$ for $x>0$, otherwise $0$. And let $f(x)=\frac{h(1-|x|)}
{h(1-|x|) + h(|x|)}$ for $x \in \mathbb{R}$.
Also, constructing such a function in $\mathbb{R}^n$ is not difficult:
$$F_n(x) = \prod_{j=1}^{n} f(x_j)$$
Where $x = (x_1,x_2, \cdots, x_n)$.
We can prove that
$$ \sum_{k \in \mathbb{Z}^n} F_n(x+k) = \sum_{k_1, \cdots, k_n \in \mathbb{Z}}\prod_{j=1}^{n} f(x_j+k_j) = \prod_{j=1}^{n} \sum_{k_j \in \mathbb{Z}}f(x_j+k_j) =  \prod_{j=1}^{n}1=1$$
Then let $G_n = F_n^{1/p}$.
Does this solve your problem? I think this construction is convenient enough.
Comment: It looks right and convenient in you way.  Where may have fault is where $f(x)\in C^{\infty}$ since we often use $|x|$ in $\mathbb R^n$. And I think it may be better if we use $h(x)=e^{-1/x^2}$ for $x>0$. And also, it look this has noting to do with $p$.
Comment: Yes, $f(x) \in C^\infty$. You only need to check that all orders of derivatives of $f$ are zero at $x = -1,0,1$. However, this part is rather boring.
Answer: General process of creating of a partition of unity does the job when we let the inherent symmetry manifest.

Take a covering: $G_k := Q(k,1)$ (cubes). Let us skip this step.

Take some function supported by $G_k$, or, in our case, we just take some functions: Let $h_0$ be a any smooth non-negative function which is positive on the closure of the unit cube $Q(0,1/2)$ and whose support is bounded.
Let $h_k(x) = h_0(x -k)$, for all $k\in \mathbb Z^n$.

We normalise the sum to 1:
Let $g_k(x) = h_k(x) / \sum_l h_l(x)$.

Now we have a partition of unity. The formula preserves the relation $g_k(x) = g_0(x-k)$. Hence if $f=g_0^{1/p}$, we have $\sum_{k\in \mathbb Z^n}f(x+k)^p=1$.
Now what is $f(0)$ ? This is some number $p$ in $[0,1]$, and if you review steps 1 and 2, you see you get any of that numbers. For $p=1$, we find $g_0$ which satisfies $g_0(1)=1$, which is positive on the closure of the unit cube $Q(0,1/2)$ and whose support is contained in $Q(0,1)$. For other value $p\in [0,1]$, instead of messing with $g_0$, let us chose $a$ such that $g_0(a)=p$ and shift the function sideways, $f(x)=g_0(x-a)^{1/p}$
The next question is if we can get $f(0)=p$ for other $p$ then in $[0,1]$.


Indentation error in for loop

Question: The problem is:

Finish the function sum_of_over_fives that loops over number_list and adds to the total only the numbers greater than 5. Then it should return the total.

def sum_of_over_fives(number_list):
       total = 0
       for number in number_list:
           number >5
             total += number
       return total

I get an indent error for "number >5" line but I have this gut feeling that the line is wrong.
Comment: Does the indentation look correct to you? If so, why? What are you expecting to happen with `number > 5`?
Comment: I tried indenting different ways the main error is " IndentationError: expected an indented block.
Comment: Stephen - I had tried  using 'if' as well I still get the indentation error.
Answer: As pointed out by @Mitch and @StephenRauch, your logic is fine, the only problem is with your indentation and the number > 5 which should be an if statement.
According to the PEP 8 documentation, you must make sure that the indentation of your function body is 4 ,  at the moment, it is 8.
Then the only thing left will be to put the if and the : to go with the number > 5. Here is your final code with the corrected indentations and the correct if statement:
def sum_of_over_fives(number_list):
    total = 0
    for number in number_list:
        if number > 5:
            total += number
    return total

print(sum_of_over_fives([1,2,3,4,5,6,7]))
>>>
13

But like @a_guest said, there is a better way of doing what you are trying to do.
I hope that help :).
Comment: @ Tshilidzi Mudau I appreciate your response. Thank you for your explanation.
Answer: You can use the built-ins filter and sum:
total = sum(filter(lambda x: x > 5, number_list))

Comment: @a_guest Suppose Python is my first language. What do you think I learn first - raw loop control flow, or built-in function abstractions? Come on.
Comment: If he turned that in for his assignment, the prof would know he got it here.
Comment: @a_guest I suppose we'll agree to disagree. I find it to be a low-quality answer to a low-quality question that should be closed.
Comment: Well but this is how you solve the problem in Python. The OP's code is C-style, not Python.
Comment: @a_guest The OP's question is presumably why they have a syntax error. You have not answered that question, but rather provided a one-liner.
Comment: @Mitch My "one-liner" produces the desired result and does not raise an indentation error so I'd say I answered it quite certainly.
Comment: @StephenRauch No I don't agree, this is not how you teach Python. Python is all about "batteries included" and so you should use it. There is no point in programming C in Python really.
Comment: @Mitch If someone's not managing to do something in a bad way I won't help him doing so but instead show a better alternative. Everything else is quite narrow minded i.m.o. Regarding teaching Python: _loops_ are abstract concepts, not specific to a programming language, and so you can teach those concepts independently of the language. I also don't see how `sum` or `filter` are "abstractions"; `sum(some_list)` is quite naturally doing what it's saying. Also there are plenty of cases where `for` loops are useful in Python so it's much better to teach it using such examples not redundant ones.
Comment: Since there is no Teacher involved (I am learning alone) no worries. Your code worked. Now I will study it and make sure that I really understand the problem. Thank you.

Indentation error in for loop


Pegar o resultado do ng-repeat e usar no moment.js

Question: Tenho uma aplicação que utiliza um ng-repeat para listar informações. Uma dessas informações vem com uma data como exemplo abaixo, o que acontece é que eu queria usar a função relativa do moment.Js. A minha dificuldade é pegar esse valor recebido e usar nos parâmetros certo do moment.js.

            {{ x.TempoEspera }}

valor recebido= "TempoEspera":"11/13/2014 17:17:47"
Comment: leozado você quer formatar sua data em um formato especifico?
Comment: sim, gostaria que ela não retorna-se essa data 'BRUTA' e sim neste seguinte formato por exemplo.
1 minutos atras ou 10 horas atras.
Comment: Você quer mostrar o tempo decorrido da data informada até agora?
Answer: Pode fazer um filtro que receba a data e a formate como desejar:

angular.module("app", []);

angular.module('app').controller("myctrl", function() {

  var ctrl = this;
  ctrl.names = [{tempoEspera: "2015-01-01T01:00:00"}, {tempoEspera: "2016-01-01T23:00:59"}]

});

// cria um filtro que receba uma data e formata-a atraves do momentjs
angular.module('app').filter('formatarData', function() {
  return function(input) {

    if (!input) {
      return '';
    }

    return moment(input).format("LLLL"); // formata conforme a localização do utilizador. Alterar esta linha para alterar a forma como a data e formatada.
  }
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

        Test

        {{x.tempoEspera | formatarData}}

No exemplo atrás, e declarado um filtro chamado formatarData que recebe uma string que representa uma data e formata-a usando o momentjs.
Neste caso especifico, esta a formatar a data com o formato LLLL - Month name, day of month, day of week, year, time.
No entanto, pode alterar o codigo do filtro para formatar a data para o formato que precisar.
Comment: consegui, muito obrigado
Comment: certo, mas ali voce recebe o valor de uma variável e como eu conseguiria filtrar o valor que vem de um outro lugar que no caso foi declarado dessa forma:

var app = angular.module('myApp', []);

 app.controller('customersCtrl2', function($scope, $http, $ctrl) {
       $http.get("http://192.168.0.235:8037/webrun/FluxoWEB002.rule?sys=EXP")
    .then(function (response) {$scope.names = response.data.pedidos;});

   });
Comment: O valor {TempoEspera: "2000-01-01T01:00:00"} vem dessa pagina "http://192.168.0.235:8037/webrun/FluxoWEB002.rule?sys=EXP", junto com outras informações, e eu precisaria formatar apenas o valor TempoEspera.
Comment: nao sei se entendi, da forma como mostra, continua a funcionar desde que o `$scope.names` tenha objectos que por sua vez tenham a propriedade `TempoEspera`.
Comment: Quando vem outras informaçoes que não é data ele retorna isso
{ Invalid date}
Comment: Nossa eu estava tão focado que nos teste que estava fazendo acabei cabaçando.
Comment: estava retorando invalid data porque mantive os filtros nas outras chamadas nos teste que estava fazendo através do seu código, porem quando vou usar o filtro na minha aplicação ele não funciona corretamente teria como me ajudar a consertar o filtro para que ele funciona- se apartir desse codigo

var app = angular.module('myApp', []); app.controller('customersCtrl2', function($scope, $http, $ctrl) { $http.get("192.168.0.235:8037/webrun/FluxoWEB002.rule?sys=EXP") .then(function (response) {$scope.names = response.data.pedidos;}); });
Comment: tem de registrar o filtro antes de o pode usar no HTML, veja a linha `angular.module('app').filter('formatarData', function() ` do codigo da resposta.


How to show that $b_n(n) \neq 0$ for $b_n(x) = -\frac{16 x}{n} b_{n-1}(x) - \frac{48 x}{n} b_{n-2}(x)$?

Question: Lets define the recursive polynomial:
$b_0(x) = 1$
$b_1(x) = -16 x$
$b_n(x) = -\frac{16 x}{n} \left( b_{n-1}(x) + 3 b_{n-2}(x) \right) = -\frac{16 x}{n} b_{n-1}(x) - \frac{48 x}{n} b_{n-2}(x)$ ; with $x \in \mathbb{R}$ and $n \in \mathbb{N}$
Question 1: How can I show that $b_n(n) \neq 0$ ?
I can show that for the following recurrence relation $a_n \neq 0$.
$a_0 = 1$
$a_1 = -16$
$a_n = -16 \left( a_{n-1} + 3 a_{n-2} \right) = -16 a_{n-1} - 48 a_{n-2}$
The characteristic polynomial will be:
$\lambda^2 + 16\lambda + 48 = 0$
with the solutions $\lambda_1 = -12$ and $\lambda_2 = -4$.
Therefore I am able to express $a_n$ as:
$a_n = A_1 \lambda_1^n + A_2 \lambda_2^n = \frac{3}{2}(-12)^n - \frac{1}{2}(-4)^n = (-1)^n \frac{12^n - 4^n}{2} \neq 0$
My motivation was numerical evidence and that:
$b_n(n) = -16 \left( b_{n-1}(n) + 3 b_{n-2}(n) \right)$ which is like $a_n$ but
$b_{n-1}(n) = -16 \frac{n-1}{n} \left( b_{n-2}(n) + 3 b_{n-3}(n) \right)$ for example is only similar to $a_{n-1}$ in the long run when $n \to \infty$.
Question 2: Is it possible in any way to proof $b_n(n) \neq 0$ by using $a_n$ ?
Comment: Sorry I don't have a proof yet. But from the first glimpse, your recursive definition of $a_n$ is wrong.You mixed the notation of $n$ and $x$.
Comment: assuming you define $a_n = b_n(n)$, but $b_{n-1}(n)$ is not in the definition of $a_n$ series.
Comment: I checked my definition of $a_n$. The definition, as I want to be, is correct written down.
Comment: @MoonKnight I have here broken down my big question to this specific example. In a general definition I see numerically an asymptotic connection between $b_n(n)$ and $a_n$ for many more similar examples.
Answer: If we fix $n$ and define $a_k=b_k(n)$, then indeed we obtain a recursion
$$a_0=1,\quad a_1=-16n,\quad a_k=-16a_{k-1}-48a_{k-2}. $$
From here we infer that
$$\tag1 a_k=A(-12)^k+B(-4)^k$$
for suitable $A,B$.
The desired result is that this makes $a_n\ne0$.
Clearly, $a_0\ne 0$. Also, when $n=1$, we have $a_1=-16\ne 0$, so that we need only consider the cases with $n\ge 2$.
From $(1)$ and the given values for $a_0,a_1$,  we  infer $$\tag2A+B=1,\quad -12A-4B=-16n,$$
Or more explicitely
$$ \tag3A=2n-\frac12,\quad B=\frac32-2n.$$
Note that $a_n=0$ implies
$$\frac BA=-3^n\le -9, $$whereas $(3)$ leads to
$$\frac BA=\frac{\frac32-2n}{2n-\frac12}=-1+\frac1{2n-\frac12}>-1. $$
Comment: I am familiar with your way of solving. I have done it the same way, too. But for me it is unclear if I can say directly that $b_n(x) \neq 0$ at the position where $x = n$ because the defined $a_k = b_k(n) \neq 0$. For example $b_3(3) = -16 \left( b_2(3) + 3 b_1(3) \right) \neq a_3 = -16 \left( a_2 + 3 a_3 \right)$
Comment: Edit: For example $b_3(3) = −16 \left( b_2(3)+3 b_1(3) \right) \neq a_3 = −16 \left( a_2 + 3 a_1 \right)$


Como pegar o último digito de um número no ActionScript 3

Question: Tenho uma variável com um valor qualquer (var qtdd = 758) dentro de uma função e gostaria de pegar somente o último dígito desta variável, no caso o número 8. Alguém sabe como fazer isso no ActionScript 3?
Segue o código:
this.addEventListener("tick", capta_x.bind(this));

function capta_x() {

    var qtdd = 758;

}

Comment: Poste o código pra facilitar a quem possa te ajudar amigo
Comment: Acrescentei. Obg amigo.
Answer: Divida o numero por 10 e pegue somente o resto da divisão, mas como o % serve justamente para retornar o resto da divisão, o primeiro calculo e desnecessário:
function capta_x() {
    var qtdd = 758;
    return qtdd % 10;
}

Comment: Resolvido! Obrigado amigo.
Answer: Outra forma, Em AS3 :
var qtdd = 758;
var qtddString:String = qtdd.toString(); // converte para string
var ultimoChar = qtddString.charAt(qtddString.length - 1)); // pega o ultimo character e retorna "8"
var ultimoNum = Number(ultimoChar); // converte para numero e retorna 8


How to convert java.awt.Image to byte arrays in java?

Question: I have the java.awt.Image object and I want to convert it into bytes array that contain RGB value of each pixel. For example,
byte[][][] image_color = new byte[3][image.getWidth()][image.getHeight()];

Big Thanks
Answer: Check the overloads of java.awt.image.BufferedImage.getRGB(), or the methods of java.awt.image.Raster, which can be obtained through BufferredImage.getRaster(). You can find some sample usage here.


Redirect from http to https stopped working after update of Moodle

Question: After Moodle elearning system update, the redirection from http to https is not working anymore.
Environment: Debian 9, Bitnami Moodle appliance, Apache web server
Port 80 and 443 are opened in firewall. You can access the web site via https and it's working.
I tried this
https://docs.bitnami.com/installer/apps/moodle/#how-to-force-https-redirection-with-apache
with no effect.
Everytime I enter URL without https, I get

Bad Request Your browser sent a request that this server could not
understand. Reason: You're speaking plain HTTP to an SSL-enabled
server port. Instead use the HTTPS scheme to access this URL, please.

This is from apache log:

[Wed Aug 08 16:16:45.827527 2018] [mpm_event:notice] [pid 3827:tid
140588913918464] AH00491: caught SIGTERM, shutting down
[Wed Aug 08
16:16:49.917673 2018] [ssl:warn] [pid 4503:tid 140413525754368]
AH01909: localhost:443:0 server certificate does NOT include an ID
which matches$
[Wed Aug 08 16:16:49.954349 2018] [ssl:warn] [pid
4504:tid 140413525754368] AH01909: localhost:443:0 server certificate
does NOT include an ID which matches$
[Wed Aug 08 16:16:49.966243
2018] [mpm_event:notice] [pid 4504:tid 140413525754368]
AH00489:Apache/2.4.29 (Unix) OpenSSL/1.0.2n configured -- resuming
norm$
[Wed Aug 08 16:16:49.966287 2018] [core:notice] [pid 4504:tid
140413525754368] AH00094: Command line:
'/opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/ap$

I also tried to modify /opt/bitnami/apps/moodle/conf/httpd-prefix.conf with this lines:
DocumentRoot "/opt/bitnami/apps/moodle/htdocs"
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/(.*) http://www.moodle.mysite.com/$1 [R,L]
Include "/opt/bitnami/apps/moodle/conf/httpd-app.conf"

Didn't help.
After every change I restarted Apache, deleted browser cache and tried to load the web page.
Thank you.
Comment: Are you running this behind a load balancer or something?
Comment: Hi Michael, no, there is no load balancer. It worked before the update. The only change was the update of Moodle.
Answer: According to https://docs.bitnami.com/installer/apps/moodle/#how-to-force-https-redirection-with-apache the RewriteRule should be https instead of http as appear in the above message, also the DocumentRoot directive should reference the Apache directory, not the moodle one:
<VirtualHost _default_:80>
  DocumentRoot "/opt/bitnami/apache2/htdocs"
  RewriteEngine On
  RewriteCond %{HTTPS} !=on
  RewriteRule ^/(.*) https://%{SERVER_NAME}/$1 [R,L]
  ...
</VirtualHost>

Comment: Thank you, Carlos, you are right, I changed it to https, but when I change the DocumentRoot to apache, I get Moodle inicialization screen when I enter https://moodle.mysite.com and when I enter http://... I still get Bad request. :(


If there is a constant in the solution to an ODE is that assumed to be the initial condition?

Question: I have
$$\frac{dy}{dt} = e^t \sin(y)$$
and Wolfram Alpha gives the solution as
$$y(t) = 2\cot^{-1}(e^{c_1 - e^t})$$
Why is it giving me some unknown constant $c_1$ with no mention of what it is? Is it assumed that this is $y_0$, the initial condition?
Comment: This is an example of an 'integration constant', corresponding to the fact that finding the solution of such an ODE often amounts to computing an indefinite integral. It is generally not identical to the initial condition(s), but it is _determined_ by them.
Comment: You can force WA by adding `y(0)=a` to the request to incorporate the initial condition in the solution. and indeed, the request `y'(t)=exp(t)*sin(y(t)), y(0)=a` gives as solution $y(t) = 2 \cot^{-1}(e^{1-e^t} \cot(\frac a2))$.
Answer: You have
$$y_0=y(0)= 2\cot^{-1}(e^{c_1 - e^0})$$
hence
$$c_1=\ln\left(\cot\left(\frac{y_0}2\right)\right)+1.$$
Comment: Thanks. Strange that Wolfram Alpha doesn't give you this info
Comment: @jphollowed: did you provide the initial condition ? If not, Alpha is innocent.
Comment: @jphollowed: Try [this `y'(t)=exp(t)*sin(y(t)), y(0)=a`](https://www.wolframalpha.com/input/?i=y%27%28t%29%3Dexp%28t%29*sin%28y%28t%29%29,+y%280%29%3Da)
Answer: No, it is not $y(0)$.  $y(0) = 2 \cot^{-1}(e^{c_1 - 1})$.


Is there a simplistic model to disaggregate census data based on years and smaller zones?

Question: In a nutshell, here's what I have:

Annual population estimates for the State
Periodical (5 years) age, population, and basic census data per zones

Here's what I want to do:

Create a simplistic model to generate the data for the missing years between the period for each zone, and have the total sums add up to where the yearly state population estimate is.

All in all, I'm looking for a non complicated statistical model that is able to generate values with an acceptable (doesn't have to be super high) precision.
Answer: About the simplest thing you can do is interpolate normalized counts over time and (almost) the simplest form of interpolation is linear.
Specifically, suppose $y_i$ is the state population at time $i$ and $x_i$ is some other count (by age, tract, or whatever).  Define $\xi_i = x_i/y_i$.  Suppose $i$ is a year for which you do not have the periodic data.  Let $i_{-}$ and $i_{+}$ be the years immediately preceding and following $i$, respectively, for which $x_i$ is available.  The linearly interpolated estimate of $\xi_i$ is
$$\hat{\xi}_i = \frac{\xi_{i_{-}} (i_{+} - i) + \xi_{i_{+}} (i - i_{-})} {i_{+} - i_{-}} \text{.}$$
The estimate of $x_i$ is
$$\hat{x}_i = \hat{\xi}_i y_i.$$
The sums will come out correctly because this estimator is linear with weights summing to unity.  For example, suppose you are tracking two variables $x$ and $z$ which count complementary parts of the population (such as males and females), so that $x_i+z_i = y_i$ whenever you have all three counts.  Defining $\xi_i = x_i/y_i$ as before and, similarly, $\zeta_i = z_i/y_i$, the two fractions sum to unity: $\xi_i + \zeta_i = y_i/y_i = 1$ for all $i$.  Therefore the interpolated fractions also sum to unity:
$$\hat{\xi}_i + \hat{\zeta}_i = \frac{\xi_{i_{-}} (i_{+} - i) + \xi_{i_{+}} (i - i_{-})} {i_{+} - i_{-}} +  \frac{\zeta_{i_{-}} (i_{+} - i) + \zeta_{i_{+}} (i - i_{-})} {i_{+} - i_{-}}$$
$$= \frac{(\xi_{i_{-}} + \zeta_{i_{-}}) (i_{+} - i) + (\xi_{i_{+}} + \zeta_{i_{+}}) (i - i_{-})} {i_{+} - i_{-}}$$
$$= \frac{(i_{+} - i) + (i - i_{-})} {i_{+} - i_{-}}$$
$$= 1.$$
Whence $\hat{x}_i + \hat{z}_i = y_i(\hat{\xi}_i + \hat{\zeta}_i) = y_i$ as desired.  This generalizes to population partitions of any size, such as age distributions.
Comment: Thanks @Whuber, with your GIS experience, what do you recommend to do?
Comment: @das It depends on what you need the data for and how accurate you need them to be.  If you have related questions that will primarily be of interest to GIS people, why not post them on GIS.SE?  You can reference this thread to provide context, make progress, and avoid repeating yourself.
Comment: I'm not sure GIS is the place, as really i'm trying to disaggregate census data. MY zones are already identified, although I might ask there what is the proper way to divide census zones so they're relatively the same size
Comment: @das What is the motivation for making them the same size?  And do you mean same *area* or same *population*?
Comment: @whuber The same area size. The end goal is to disaggregate the data as much as possible sort of like going from object to atoms
Comment: @dass It's unclear then why area is of interest.  The "atoms" in population data are individual people, households, and housing units.  They are rarely distributed equally by area.
Comment: @whuber, true, but I don't have any of that data, and I'm trying to figure out a way to disaggregate it. I have census data, which roughly the zones are 2,500 -> 4,000 people per zone, I would like to disaggregate it up to 25 to 40 people per zone
Comment: @dass One approach is to model the tract-only data in terms of the data also available at the block level.  This sounds like [a question I asked here last year](http://stats.stackexchange.com/questions/4445/model-for-population-density-estimation).
Comment: @whuber, seems interesting especially the use of raster objects. Did you get a paper out of it, any recommendations or pitfalls to avoid?


What is the average ice time for an NHL player?

Question: What is the formula for determining it myself?
Comment: The formula is: total ice time divided by the number of games played
Answer: The time on ice for a player per game really determines on the player's level. Just like in any sport, the more a player is skilled, the more time he plays. In hockey, the issue is no different.
Usually, out of the 60 minutes, average players get around 22-24 minuets per game while the best usually go for 28-30 minutes. In fact, the minutes per ice per game leader of the 13/14 regular season, Ryan Suter, went for just under 30 minutes per game.
Source.


Temporary list won't append at each iteration

Question: I'm a beginner and I have this piece of code here:
<code>alleles=['DPY','DPX']
n_dict={'DPY':[['AA561_P4',5781],['AA562_P2',5712]],'DPX':[['AA561_P3',5324],['AA565_P2',5742]]}
n_list = []
for item in alleles:
    f_list=[item]
    for sub in n_dict[item]:
        t=sub[0].split('_')
        t1=t[1]+','+t[0]
        f_list.append(t1)
    n_list.append(f_list)
print(f_list)
</code>
It's supposed to go through each item in allele and use the item as a key to recover a list of lists. Subsequently for each item (sub) in the list of lists, it has to take the element at the zero position and re-arrange it and append this re-arranged string to a list(f_list). Finally, once it has gone through the complete list of lists for an allele, it has to append the list of strings (f_list) to n_list.
Instead of giving a list of lists, with each list containing a list of re-arranged strings, I get only the last list of strings. I suspect it may be a problem that could be fixed the .copy module but I still have not found a solution.
Comment: How do you expect the result to look like (example) ? Your description sounds more complicated as it is.
Comment: `print(n_list)`, it seems to give you what you need.
Comment: What you have is a typo
Answer: I think the problem is that you define your f_list variable inside the loop. As such the result of the first iteration gets overwritten with the one from the next, throwing away its results. Moving the initial definition of f_list up by a line, initialising it to an empty list, and appending item to it inside the loop should fix your problem.
Answer: Cahnge the following two lines of code:
<code>    n_list.append(f_list)
print(n_list)
</code>
into
<code>    n_list.append(list(f_list))
print(n_list)
</code>
I think is what you are looking for.


Are posterior probabilities from a Naive Bayes classifier reliable?

Question: I have read that the posterior probabilities of Naive Bayes classifiers are unreliable. Is this true? and if so, in what sense, and why?
Specifically, I am interested to know if the probabilities can be used as some measure of confidence of the predictions. For example, can I say that higher posteriors are more likely to be correct, or use a threshold to say that if the posterior is below some value then it is low-confidence.
Comment: When something is called "Naive Bayes", it usually means either "not really Bayes" or "Bayes with an obviously false assumption" such as independence. So your confidence becomes empirical: in machine learning you use training data, validation data and test data as part of this empirical process.
Comment: Do you have the source of that statement?
Comment: @RobertSmith for example here: http://scikit-learn.org/stable/modules/naive_bayes.html - "although naive Bayes is known as a decent classifier, it is known to be a bad estimator, so the probability outputs from predict_proba() are not to be taken too seriously".
Comment: @Henry empirically I found that the posterior probabilities **are** predictive of actual errors on the test set. The question is if this is merely a coincidence (I suspect not), or if I can expect this to also work on similar datasets.
Answer: Sorry, too long for a comment.
Very interesting. The quote

although naive Bayes is known as a decent classifier, it is known to be a bad >estimator, so the probability outputs from predict_proba() are not to be taken >too seriously

is taken from this paper that in turn is citing Bennett and Monti and Cooper. I don't think Bennett is very convincing since he only claims that "many people" think that NB produces estimates too close to 1 and 0, but gives no proof. He offers as additional evidence the fact that for long documents, there is a tendency to push values to 0 or 1, even when they are completely wrong. Monti and Cooper's paper is a bit tricky because they're comparing finite mixture models (FM), finite mixture augmented Naive-Bayes model (FAN) and Naive Bayes, so they tend to describe more about this comparison than to describe in detail why Naive Bayes are poor estimators.
On the other hand, you can find the same claim for decision trees and SVMs, so maybe people think that a given classifier gives poor estimates when it is not an issue intrinsically associated to that classifier.
I think we simply need better references and better evidence. I hope other people can provide more information.
Comment: Thanks, this is helpful. I would also be happy to hear what other people think.


Does the input notation to this fitness function describe (represent) a Kleene star?

Question: Does the input notation to this fitness function describe (represent) a Kleene star?

In an optimization problem; given an input space $X$ and a fitness function $f\;:\;X\mapsto\mathbb{R}$; the goal is to find the best $x^* \in X$ such that $f(x^*)=max_{x} f(x)$

If so would this $f(x^*)=max_{x} f(x)$ then read: The fitness function, given 0 to many values of $x \in X$ finds the maximum value of $x$?
Comment: No, $x^*$ is an element of $X$, namely the one where $f$ attains its largest value.
Comment: My "interpretation" is just restating what you already quoted: "$x^*\in X$ such that $f(x^*)=\max_xf(x)$. No special knowledge about the author or his intention is needed, just a reading of what he wrote.
Comment: @AndreasBlass How is your interpretation determined? What steps could I have taken to better understand the intent of the author of the function. Without having to find the author and ask.

In-short, is that the common interpretation?
Comment: @AndresBlass , Understood. Post/paste your answer and ill accept it.
Answer: Using $x^*$ to denote a particular element of some larger set $X$ is a fairly common convention.
For it to be a Kleene star, you'd need a separate $x$ for it to be a Kleene star of. But in $f(x*)=\max_{x}f(x)$, $x$ is a bound/dummy variable, so there is no independent $x$ to take the Kleene star of. Therefore, the author can't have meant Kleene star.


Correlation coefficient percentage is low considering relationship between variables

Question: I am creating a model in R Studio for NCAA football games and am encountering values that seem lower than they should be.  Here is my function and returned R-squared value.
lm(formula = rushing_yards ~ yards_per_rush_attempt, data = games.box)

This is the end of the model summary:
Multiple R-squared:  0.778, Adjusted R-squared:  0.7779

While 78% is nothing to scoff at I would have thought it would have been higher considering how closely related rushing_yards and yards_per_rush_attempt are to each other.  Am I missing something?  Is something wrong with my dataset or should I not worry about the results?
Comment: I would have thought the correlation of about $0.882$ was high, since you need to consider that the number of rush attempts will not be constant
Comment: What does your scatterplot look like? Would answer a lot of doubts by taking a quick peak and sharing it here.
Comment: Scatterplot added above.
Answer: Yards per rush explains a lot of the variation in rush yards per game but leaves some of that variation explained. Another source of variation, not considered in your model, is how many rush attempts per game, so it is unsurprising that you leave some of the variation unexplained.
I think I agree with the comment that your $R^2$ is surprisingly high for a model that does not consider rush attempts, but you have such a simple model that I don't believe there to be any overfitting concerns.
Comment: So after adding rushing_attempts the R2 increases significantly.

   Multiple R-squared:  0.962, Adjusted R-squared:  0.9619
Comment: @AaronMorris I'm not surprised. Those are the determinants of rushing yards in a game. The only reason you have any errors is because you should be multiplying them instead of adding.
Comment: Yes, makes sense.  This is the result after multiplying.

          Multiple R-squared:  0.9998, Adjusted R-squared:  0.9998.
Comment: Your predictions would probably be perfect if not for some rounding issues (which are just part of your data, nothing to do with poor modeling by you).


java.lang.ExceptionInInitializerError exception

Question: <code>    Exception in thread "main" java.lang.ExceptionInInitializerError
            at org.apache.tools.ant.util.FileUtils.<clinit>(FileUtils.java:63)
            at org.apache.tools.ant.Project.<clinit>(Project.java:131)
            at Pv.plugin_execute(Pv.java:140)
            at Pv.main(Pv.java:194)
    Caused by: java.lang.NullPointerException
            at org.apache.tools.ant.taskdefs.condition.Os.<clinit>(Os.java:31)
            ... 4 more
</code>
This is my code to run an ant target from my java file.
 I have set all the parameters for it.
 Code runs on Linux environment.
<code>File buildFile = new File(bDir + "/" + pBDir + "/"+ atBFile);
Project p = new Project();
p.setUserProperty("ant.file", buildFile.getAbsolutePath());
p.init();
ProjectHelper helper = ProjectHelper.getProjectHelper();
p.addReference("ant.projectHelper", helper);
helper.parse(p, buildFile);
p.executeTarget(target);
</code>
Can anyone help me with this? Yesterday it was running fine, today it gave me this exception...
Answer: Given the source code it looks like you don't have the system property of "os.name" set for some reason. You should look into why that's not set, but you could always specify it manually from the command line if necessary.
Comment: When i do    System.out.println("os.name="+System.getProperty("os.name"));            I get Linux as the property value. so that is not the reason
Comment: @user1731553: Are you running that code in *exactly* the same way as you are in the code that invokes Ant? (You might also want to check the other properties shown in that file.)
Comment: the error comes for line: Project p = new Project();                Also: the command I am using to run it is:                          java -Xmx256m -cp '.:/sc/su/repo/pro/ant/lib/*:/sc/su/repo/pro/lib/*' Pv
Comment: @user1731553: So did you try printing out the os.name property on this line before that?
Comment: Thanks! so much....I got it now....did not knew that System.setPropery() appends to the existing list of property. where as System.setProperties() removes and creates a new list. Thanks again for the help.
Answer: The problem was that since I was using System.setProperties() it removed the existing list of properties and created a new one.
however System.property() apends the property to the existing list.


How often do Olympic divers score a zero?

Question: I've been amazed at the headlines about so many Olympic divers scoring zeros during competition. Is this common in Olympic diving? If so, is there an easy explanation? It just seems odd to me that divers could misjudge their dives so badly as to do so many bellyflops. If gymnasts did this, they would be leaving on stretchers a LOT!
Answer: It is never common in a diving competition which is usually held in indoor swimming pools. The biggest cause of those belly flops and misjudgement of dives was a very strong wind.
The diving pool at the London Olympics was indoor and there was no wind. However, as you can see in the below image, the diving pool at Rio is outdoor

The diving pool has been a big embarrassment for Rio organizers and they should be blamed for not having anticipated the effect of strong gush of wind on divers when it could be powerful enough to knock down aerial camera and cables injuring seven people.
Rio Olympics: Seven injured when aerial camera, cables fall in Olympic Park
Diving: Winds help knock Chinese world champion out in preliminaries

"It was the wind that really affected the start of my dive. We didn't
  train in these kinds of very windy conditions before at all,"

I am confident that future Olympic organizers will take the wind factor more seriously than Rio organizers did. It's another shame for Rio.
Comment: Is this the same pool that had to be completely drained and cleaned because it was infested with algae a couple of days ago?


contour integration of log.

Question: I am looking at a contour integration of the following function:
$f(z)=\frac{z\log(z)}{1-z^2}$ for $z\ne 1$ and $-\frac{1}{2}$ for $z=1$.
I should find the real part of the integral of $f$ in the first quadrant, namely that $z=e^{i\theta}$ for $\theta\in [0,\pi/2]$.
I first found the poles, which are $z=\pm 1$, since $z=-1$ is not in the above area, I only concerned myself my $z=1$, by applying L'Hospital rule, I found that the residual of $f(z)$ is $\frac{-1}{2}$.
Therefore I found the contour integral to be:
$I_c=2\pi\cdot i\cdot (-1/2)=-\pi\cdot i$. Which then has a zero real part.
I think this is wrong, does anybody how what I did wrong?
Thank you.
Comment: Integral about what contour?
Comment: The task is to evaluate the above stated function in the first quadrant, It is further defined that z=exp(i*t), where t runs from 0 to pi/2
Comment: so you with to evaluate $\int_C \frac{z\log(z)}{1-z^2}dz$, where $C=\{e^{it}:0\le t \le \pi/2\}$ ? (assuming we have redefined the integrand to achieve continuity, as you do in your post)
Comment: Yes exactly, I am new to complex integration, do you know how to do this?
Comment: Thank you, I see, what are the criterias that allow use of poles and residues for integration?
Comment: Note that there may be simpler ways to solve this than in my answer, but when threw the parameterized form in Wolfram Alpha and saw $-\frac{\pi^2}{16}$ the connection to the basel problem became obvious. At some point you'll inevitably end up using the basel problem, or else you'll have proved the basel problem in the course of your proof! (a decent undertaking)
Answer: There is no pole at $1$. $1$ is a removable singularity since $\frac {z \log z} {1-z^{2}} \to -\frac 1 2 $ as $\to 1$.
Comment: The definition is: $\int_C f(z) \, dz=\int_0^{\pi /2} f(e^{it}) ie^{it}\, dt$.
Comment: Do you know how to solve this problem?
Comment: You have not told us what the contour is which means you have not stated your question in a way we can understand.
Comment: Ok, sorry. I have the complex plane in R^2 and we are removing (Re(z)<=0 and Im(z)=0) from it. Define this area as D. I further assume that |Im log (z)|<pi. Then I define f(z) as stated above. Inside D, I define a path called C which is given as z=exp(it) for t=0..Pi/2. I now want to integrate f(z) over this path C. This is where I am struggling
Comment: Since your path is not a closed contour you cannot evaluate the integral using poles and residues. You have to evaluate it directly by writing down the definition of integral of $f$ over $C$.
Comment: How would that be possible then? How can I integrate over the complex surface?
Comment: Thank you, I see, what are the criterias that allow use of poles and residues for integration?
Comment: @JonathanKiersch integrating an analytic function on a closed contour.
Comment: I see, wouldn't there come a minus in front of the integral above? Or does there apply another rule?
Comment: @JonathanKiersch not sure where you would get a negative sign. We simply let $z=e^{it}$ and note $dz = i e^{it} dt$ since $\frac{dz}{dt} = i e^{it}$
Comment: You have the minus in the integration below, but not in the above, I assume that the below is correct then?
Comment: @JonathanKiersch the negative comes from the logarithm. Note $\frac{z \log(z)}{1-z^2} dz = \frac{e^{it} \log(e^{it})}{1-e^{2it}} (ie^{it}dt) = \frac{e^{it} (it)}{1-e^{2it}} (ie^{it}dt) = \frac{-te^{2it} }{1-e^{2it}}dt$. I used the exact formula Kavi gave above.
Comment: But when you let u=exp(2it), how do you get the minus in front of the 1/4 then dosent that disappear?
Answer: We can parameterize:
$$\begin{align*}
&\text{Re}\!\int_C \frac{z\log(z)}{1-z^2}dz \\
&= -\text{Re}\!\int_0^{\pi/2} \frac{te^{2it}}{1-e^{2it}}dt&\text{(parameterize)}\\
&= -\frac{1}{4}\text{Re}\!\int_{C'}\frac{\log(z)}{1-z}dz&\text{(let } u=e^{2it}\text{)} \\
&=-\frac{1}{4}\text{Re}\!\sum_{k=0}^\infty\int_{1}^{-1}\log(z)z^kdz&\text{(geometric series)}\\
&=-\frac{1}{4}\text{Re}\!\sum_{k=0}^\infty \left(-i\pi\frac{(-1)^n}{n+1}+\frac{(-1)^n}{(n+1)^2}+\frac{1}{(n+1)^2}\right)dz&\log(z)\to-t\\
&=-\frac{1}{4}\text{Re}\!\left(-i\pi\log(2)+\frac{\pi^2}{12}+\frac{\pi^2}{6}\right)&\text{(basel problem)}\\
&=-\frac{\pi^2}{16}\\
\end{align*}$$

contour integration of log.


Remove one key from array in Javascript

Question: I have an object 'myObjects':
let myObjects = {
  "obj1":["X1","1.2"],
  "obj2": "2",
  "obj3": "3"
};

I am trying to only remove the X1 from the obj1 section. I have tried doing:
delete obj1[0];

however end up with
 [null,"1.2"]

how do I get rid of the null?
Comment: `myObjects.obj1.splice(0,1)`
Comment: btw... `obj1` isn't an object... it's an array.
Answer: You are going to remove element from Array not Object. In that case, you can use Array.splice as follows.

let myObjects = {
  "obj1":["X1","1.2"],
  "obj2": "2",
  "obj3": "3"
};

delete myObjects.obj1.splice(0, 1);
console.log(myObjects);
Comment: Please search for duplicates instead of adding just another copy of an already written answer.
Comment: What's the purpose of `delete`?
Comment: @MrUpsidown Quality >>> Reputation :)
Comment: @Andreas finally I feel like I am not alone, especially when looking at the JS tag...

Remove one key from array in Javascript


How can I load text into my screen on screen change in Kivy?

Question: I am working on an application where one of my screens has some labels and text input fields. Whenever the user navigates to this screen, I'd like for some kind of load() function to check for data in a JSON file. If it finds data, it can load this data into the screen in the respective text input fields. If not, then no worries.
I am able to store and retrieve data form a JSON file easily enough, but for the life of me I can't seem to figure out how to store this information into the screen in question whenever I navigate there! Is there some way to have a function run every time the screen appears that will fill in these text input fields?
texttest.kv
WindowManager:
    MainWindow:
        id: main_screen
    SetupWindow:
        id: setup_screen

<SetupWindow>
    name: "setup"
    hostpy: hostkv
    GridLayout:
        cols:1

        GridLayout:
            cols: 2

            Label:
                text: "Host or IP: "

            TextInput:
                id: hostkv
                multiline: False

texttestapp.py
...
...
...
class MainWindow(Screen):
    pass

class SetupWindow(Screen):
    hostpy = ObjectProperty(None)

    def __init__(self,**kwargs):
        super(SetupWindow,self).__init__(**kwargs)
        self.hostpypy.Text = "This is a test"

class WindowManager(ScreenManager):
    pass

...
...
...

As you can see, I tried with __init__(self,**kwargs), but this seems to be the wrong solution. What can I do to accomplish what I need?
Answer: I was able to find the answer: Kivy actually has it's own API for this, which I had overlooked. Specifically, you can use on_pre_enter() or on_enter() to get this to work. The documentation for it is located here: https://kivy.org/doc/stable/api-kivy.uix.screenmanager.html#kivy.uix.screenmanager.Screen


Sass Undefined variable: "$navbar-height" in Rails

Question: I am trying to precompile the assets, but I get the below error. The problem is with one of the css files being used from gems. How to resolve that?
rake aborted!
Sass::SyntaxError: Undefined variable: "$navbar-height".

Complete log:
rake assets:precompile
rake aborted!
Sass::SyntaxError: Undefined variable: "$navbar-height".
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/spree_backend-3.1.4/app/assets/stylesheets/spree/backend/components/_sidebar.scss:3
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/spree_backend-3.1.4/app/assets/stylesheets/spree/backend/spree_admin.css.scss:6
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/script/tree/variable.rb:49:in `_perform'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/script/tree/node.rb:58:in `perform'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/script/tree/operation.rb:64:in `_perform'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/script/tree/node.rb:58:in `perform'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:397:in `visit_prop'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/base.rb:36:in `visit'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:160:in `block in visit'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/stack.rb:79:in `block in with_base'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/stack.rb:115:in `with_frame'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/stack.rb:79:in `with_base'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:160:in `visit'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:433:in `block (2 levels) in visit_rule'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:433:in `map'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:433:in `block in visit_rule'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:181:in `with_environment'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:431:in `visit_rule'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/base.rb:36:in `visit'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:160:in `block in visit'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/stack.rb:79:in `block in with_base'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/stack.rb:115:in `with_frame'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/stack.rb:79:in `with_base'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:160:in `visit'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:328:in `block (2 levels) in visit_import'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:328:in `map'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:328:in `block in visit_import'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/stack.rb:88:in `block in with_import'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/stack.rb:115:in `with_frame'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/stack.rb:88:in `with_import'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:325:in `visit_import'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/base.rb:36:in `visit'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:160:in `block in visit'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/stack.rb:79:in `block in with_base'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/stack.rb:115:in `with_frame'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/stack.rb:79:in `with_base'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:160:in `visit'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/base.rb:52:in `block in visit_children'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/base.rb:52:in `map'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/base.rb:52:in `visit_children'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:169:in `block in visit_children'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:181:in `with_environment'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:168:in `visit_children'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/base.rb:36:in `block in visit'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:188:in `visit_root'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/base.rb:36:in `visit'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:159:in `visit'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/visitors/perform.rb:8:in `visit'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/root_node.rb:36:in `css_tree'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/tree/root_node.rb:20:in `render'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-3.4.23/lib/sass/engine.rb:281:in `render'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sass-rails-5.0.6/lib/sass/rails/template.rb:47:in `evaluate'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/tilt-2.0.7/lib/tilt/template.rb:109:in `render'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/legacy_tilt_processor.rb:25:in `call'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/processor_utils.rb:75:in `call_processor'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/processor_utils.rb:57:in `block in call_processors'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/processor_utils.rb:56:in `reverse_each'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/processor_utils.rb:56:in `call_processors'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/loader.rb:134:in `load_from_unloaded'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/loader.rb:60:in `block in load'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/loader.rb:317:in `fetch_asset_from_dependency_cache'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/loader.rb:44:in `load'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/cached_environment.rb:20:in `block in initialize'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/cached_environment.rb:47:in `yield'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/cached_environment.rb:47:in `load'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/bundle.rb:23:in `block in call'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/utils.rb:200:in `dfs'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/bundle.rb:24:in `call'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/processor_utils.rb:75:in `call_processor'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/processor_utils.rb:57:in `block in call_processors'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/processor_utils.rb:56:in `reverse_each'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/processor_utils.rb:56:in `call_processors'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/loader.rb:134:in `load_from_unloaded'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/loader.rb:60:in `block in load'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/loader.rb:317:in `fetch_asset_from_dependency_cache'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/loader.rb:44:in `load'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/cached_environment.rb:20:in `block in initialize'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/cached_environment.rb:47:in `yield'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/cached_environment.rb:47:in `load'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/base.rb:66:in `find_asset'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/base.rb:73:in `find_all_linked_assets'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/manifest.rb:142:in `block in find'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/legacy.rb:114:in `block (2 levels) in logical_paths'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:228:in `block in stat_tree'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:212:in `block in stat_directory'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:209:in `each'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:209:in `stat_directory'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:227:in `stat_tree'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:231:in `block in stat_tree'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:212:in `block in stat_directory'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:209:in `each'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:209:in `stat_directory'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:227:in `stat_tree'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:231:in `block in stat_tree'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:212:in `block in stat_directory'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:209:in `each'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:209:in `stat_directory'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/path_utils.rb:227:in `stat_tree'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/legacy.rb:105:in `each'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/legacy.rb:105:in `block in logical_paths'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/legacy.rb:104:in `each'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/legacy.rb:104:in `logical_paths'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/manifest.rb:140:in `find'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/sprockets/manifest.rb:185:in `compile'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-rails-3.2.0/lib/sprockets/rails/task.rb:68:in `block (3 levels) in define'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-3.7.1/lib/rake/sprocketstask.rb:147:in `with_logger'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/sprockets-rails-3.2.0/lib/sprockets/rails/task.rb:67:in `block (2 levels) in define'
/home/zapbuild/.rvm/gems/ruby-2.2.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
/home/zapbuild/.rvm/gems/ruby-2.2.0/bin/ruby_executable_hooks:15:in `eval'
/home/zapbuild/.rvm/gems/ruby-2.2.0/bin/ruby_executable_hooks:15:in `'
Tasks: TOP => assets:precompile

Gem file is:
source 'https://rubygems.org'

ruby '2.2.0'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 4.2.0'

# Use postgresql as the database for Active Record
gem 'pg'

gem 'sass-rails', '>= 3.2'

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'

# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer',  platforms: :ruby

gem 'bourbon'
gem 'nokogiri'

# Use jquery as the JavaScript library
gem 'jquery-rails'
gem 'jquery-ui-rails'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'

# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0',          group: :doc

# For accessing Amazon's APImini_portile2 2.1.0
gem 'vacuum'

# For calculating fba fees
gem 'fba_fee_calculator'

gem 'factory_girl_rails'

# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'

gem 'will_paginate'

gem 'kaminari'
gem 'bootstrap-will_paginate', '~> 0.0.10'
gem 'simple_form'
gem 'country_select'

gem 'paperclip', '~> 4.3'
gem 'carrierwave'
gem 'mini_magick',             '4.5.1'
gem 'fog',                     '1.38.0'
gem 'iconv'
gem 'prawn'
gem 'masonry-rails'
gem 'stripe', :git => 'https://github.com/stripe/stripe-ruby'
gem 'dotenv-rails', :groups => [:development, :test]
gem 'selenium-webdriver'
gem "rails-erd"
gem "byebug"

gem 'spree', '~> 3.1.0'
gem 'spree_auth_devise', '~> 3.1.0'
gem 'spree_gateway', '~> 3.1.0'

group :production do
  gem 'rails_12factor'
  gem 'sprockets-rails'
end

group :development do
  gem "better_errors"
  gem "binding_of_caller"
end

group :development, :test do
  gem 'rspec-rails'
  gem 'capybara'
  gem 'launchy'
end

Answer: Try to shift require directive for spree.css at the top
Ex:-
*= require file1
*= require file2
*= require spree.css

To:-
*= require spree.css
*= require file1
*= require file2

Chances are the variables are being overridden by some other files or frameworks like bootstrap-sprockets, etc. Probably that's why spree components unable to read the variables.


Change background color text in Eclipse

Question: I'm working with PHP in Eclipse (PDT), but when there is code of HTML and PHP, the HTML color is with a black background and this is very annoying and difficult to read. Is there a way to change that background color?
Answer: Go to Window -> Preferences -> PHP -> Editor -> Syntax Coloring and then navigate through the list and find the ones that have the black background and change it back to white.
If the color preference isn't in there, search for Syntax Coloring and see if you have something else overriding it.
Comment: +1. Easier way: type color into the search bar of the preferences window. Works flawlessly.
Comment: Thanks! the only problem is that I have to search colors of every attribute, everything has foreground white and background black.
Answer: I was typing something similar to what jprofitt said, but less complete.
Another option would be to install the Eclipse Color Theme plugin and use those settings.

Change background color text in Eclipse


How to present a splash/login view controller using storyboards

Question: I've seen this question in various forms without a clear answer.  I'm going to ask and answer here.  My app needs to do work on startup... inits, a few network calls, login, etc.  I don't want my main view controller working until that's done.  What's a good pattern for doing this?
Requirements:

iOS5+, storyboards, ARC.
the main vc's view cannot appear until the startup work is done.
want a choice of transition styles to the main vc when the startup work is done.
want to do as much layout as possible in storyboard.
the code should be cleanly contained somewhere obvious.
Answer: EDIT, July 2017
Since the first writing, I've changed my practice to one where I give the start up tasks to their own view controller.  In that VC, I check startup conditions, present a "busy" UI if needed, etc.  Based on the state at startup, I set the window's root VC.
In addition to solving the OP problem, this approach has the additional benefits of giving better control of the startup UI and UI transitions.  Here's how to do it:
In your main storyboard, add a new VC, called LaunchViewController and make it the app's initial vc.  Give your app's "real" initial vc an identifier like "AppUI" (identifiers are on the Identity tab in IB).
Identify other vcs that are the starts of main UI flows (e.g. Signup/Login, Tutorial, and so on) and give these descriptive identifiers, too.  (Some prefer to keep each flow in it's own storyboard.  That's a good practice, IMO).
One other nice optional idea: give your app's launch storyboard's vc an identifier, too (like "LaunchVC"), so that you can grab it and use it's view during startup.  This will provide a seamless experience for the user during launch and while you do your startup tasks.
Here's what my LaunchViewController looks like....
@implementation LaunchViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // optional, but I really like this:
    // cover my view with my launch screen's view for a seamless start
    UIStoryboard *storyboard = [self.class storyboardWithKey:@"UILaunchStoryboardName"];
    UINavigationController *vc = [storyboard instantiateViewControllerWithIdentifier:@"LaunchVC"];
    [self.view addSubview:vc.view];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self hideBusyUI];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self showBusyUI];

    // start your startup logic here:
    // let's say you need to do a network transaction...
    //
    [someNetworkCallingObject doSomeNetworkCallCompletion:^(id result, NSError *error) {
        if (/* some condition */) [self.class presentUI:@"AppUI"];
        else if (/* some condition */) [self.class presentUI:@"LoginUI"];
        // etc.
    }];
}

#pragma mark - Busy UI

// optional, but maybe you want a spinner or something while getting started
- (void)showBusyUI {
    // in one app, I add a spinner on my launch storyboard vc
    // give it a tag, and give the logo image a tag, too
    // here in animation, I fade out the logo and fade in a spinner
    UIImageView *logo = (UIImageView *)[self.view viewWithTag:32];
    UIActivityIndicatorView *aiv = (UIActivityIndicatorView *)[self.view viewWithTag:33];
    [UIView animateWithDuration:0.5 animations:^{
        logo.alpha = 0.0;
        aiv.alpha = 1.0;
    }];
}

- (void)hideBusyUI {
    // an animation that reverses the showBusyUI
}

#pragma mark - Present UI

+ (void)presentUI:(NSString *)identifier {
    UIStoryboard *storyboard = [self storyboardWithKey:@"UIMainStoryboardFile"];
    UINavigationController *vc = [storyboard instantiateViewControllerWithIdentifier:identifier];

    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    window.rootViewController = vc;

    // another bonus of this approach: any VC transition you like to
    // any of the app's main flows
    [UIView transitionWithView:window
                      duration:0.3
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:nil
                    completion:nil];
}

+ (UIStoryboard *)storyboardWithKey:(NSString *)key {
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *storyboardName = [bundle objectForInfoDictionaryKey:key];
    return [UIStoryboard storyboardWithName:storyboardName bundle:bundle];
}

@end

The original answer below, though I prefer my current approach
Let's express the app's readiness to run the main vc with a boolean, something like:
BOOL readyToRun = startupWorkIsDone && userIsLoggedIn;

Create an AppStartupViewController and lay it out in app storyboard.
Don't drag any segue's to it, and don't make it the staring vc, just leave it floating somewhere.
In the vc's attributes inspector in storyboard, set it's identifier as "AppStartupViewController".

In the AppStartupViewController.m, when the readyToRun conditions have been met, it can dismiss itself:
self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;   // your choice here from UIModalTransitionStyle
[self dismissViewControllerAnimated:YES completion:nil];

Now, whenever the app becomes active, it can check for readiness to run, and present the AppStartupViewController if it's needed.
In AppDelegate.h
- (void)applicationDidBecomeActive:(UIApplication *)application {

    BOOL readyToRun = startupWorkIsDone && userIsLoggedIn;

    if (!readyToRun) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
        AppStartupViewController *startupVC = [storyboard instantiateViewControllerWithIdentifier:@"AppStartupViewController"];

        [self.window.rootViewController presentViewController:startupVC animated:NO completion:nil];
        // animate = NO because we don't want to see the mainVC's view
    }
}

That's mostly the answer, but there is one hitch.  Unfortunately the main vc gets loaded (that's okay) and gets a viewWillAppear: message (not okay) before the AppStartupViewController is presented.  It means we have to spread a little extra startup logic, like this, in MainViewController.m:
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    if (readyToRun) {
        // the view will appear stuff i would have done unconditionally before
    }
}

I hope this is helpful.
Comment: If you dont mind me asking, I tried your solution out for my app but I did get the hitch you were mentioning.
Do you mind explaining what the statement "the view will appear stuff I would have done unconditionally before"
Comment: Sure - in the soln I offer, the main vc in your app is going to get two invocations of viewWillAppear: - first before your AppStartup vc is presented, and the second before the main vc is really about to appear.  The problem is that first one.  I'd like my main vc to assume that everything is ready to go before it gets any view messages, but that first (and wrong by Apple, I think) message to viewWillAppear: occurs before I have run my startup logic.  (It's not about to appear, so why should it get that message?) continued...
Comment: As a result, I add the readyToRun condition there.  "the view will appear stuff ..." is anything you plan to do in that method, anything that should only run when the app is ready.  It's tough to express.  Will think about how to edit my soln there for more clarity.
Comment: If I've understood correctly, you're spreading the logic into MainViewController's `viewWillAppear()` however there's no guarantee that this will be the active view controller at the time is there? Or you have to start peppering that check for "readyToRun" all over your app, which is sub-optimal. Wouldn't it be better to encapsulate this logic inside AppDelegate itself?
Comment: @cleverbit - I've changed my approach since writing this article to one that I've described fully in a major edit, and one that shares a key similarity with one of your recent answers -- replace the root window view. (not sure why your answer was down-voted, but I did my part to correct that with a plus one).  My new current practice gives all of this work to a startup vc.  This has several benefits that I describe in the edit.
Comment: @cleverbit - I appreciate your comment because, after I devised my newer approach, I realized that it deprecated this answer, but never dug around SO to find this and fix it.  As to your point about needing to make "readyToRun" calls everywhere, I haven't found this to be the case, maybe because of the app states where the check's I do have been needed (e.g. on launch vs. becoming active).
Comment: Thanks @danh glad I could help. I've asked (and answered) a similar question here, which might provide further insight for people looking for more information on this topic: https://stackoverflow.com/questions/45321570/swift-changing-the-rootviewcontroller-in-appdelegate-to-present-main-or-login-o
Answer: Another solution when using a navigation controller.

Your navigation controller being the initial view controller, set your main controller as the navigation controller root's view.
Add your loading controller to the storyboard and link with a named segue of style modal.
In your main controller's viewWillAppear trigger the segue (only once per app run).

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if(_isFirstRun)
    {
        _isFirstRun = NO;
        [self performSegueWithIdentifier:@"segueLoading" sender:nil];
    }
}

It will not work if you trigger the segue in viewDidLoad probably because the navigation controller's animation is not done yet and you will receive an unbalanced calls to begin/end appearance transitions


Statistical test for a significant change in time series (sales) trend after policy change

Question: My apologies if this has been addressed before, however my experience with statistics is a bit limited, particularly when it comes to time series analyses.
My current question relates to the analysis of a trend in monthly sales before and after an event for a single product. Suppose there is a new product with increasing monthly sales, however the company decides to initiate a promotion 12 months after it launches to further increase sales. A year later, the company wants to examine if the sales trend after the promotion is significantly different from the trend prior to the promotion (ideally the unit sales would be increasing at a faster rate after initiation of the promotion). So essentially, I want to determine if I had forecasted 12 months into the future just prior to the promotion, are the sales significantly different from what they actually turned out to be.
What statistical test is the most appropriate to use to determine if the monthly sales trend is significantly different before vs. after the promotion? I only have one data point for each time point (monthly sales) before and after, and since the sales are increasing I have come across problems due to the "stationarity" requirement for many tests, as well as the fact that I would only have 12 historical data points on which to base the initial forecast.
Answer: Would a time series intervention analysis suit your needs?  It estimates how much an intervention has changed a time series, if at all.
how to in R: http://www.r-bloggers.com/time-series-intervention-analysis-wih-r-and-sas/
example use case: What test should I use to determine if a policy change had a statistically significant impact on website registrations?
online course notes: https://onlinecourses.science.psu.edu/stat510/?q=node/76
Answer: I realise this answer is a bit late for the poster of this question, but I thought it may help others reviewing this question.
There is an excellent tutorial paper on interrupted time series analysis by Bernal et al:

Bernal, J. L., Cummins, S., Gasparrini; A. (2017). Interrupted time
  series regression for the evaluation of public health interventions: a
  tutorial, International Journal of Epidemiology, 46(1): 348–355.

You can download it free at:
https://www.researchgate.net/publication/303883790_Interrupted_time_series_regression_for_the_evaluation_of_public_health_interventions_A_tutorial
And best of all the paper's supplementary material includes R code for all of the examples discussed in the paper.
It is particularly relevant to the poster's question since it uses segmented linear regression which is more appropriate for smaller data sets (i.e. less than 100 time points) than ARIMA.
Answer: Without knowing more about the data, especially the independent variables (the regressors), it will be impossible to give a one-fits-all solution for anyone here.
However the issue you are adressing falls into the area of Econometrics. As such, there are a couple of good texts which will bring you further.
They easiest book which will give you the tools to tackle this issue is Introduction to Econometrics by Stock&Watson. It is an undergraduate textbook which offers a very modern approach. Your small sample might give you issues.
The standard books one would recommend in this instance are either "Econometrics" by Fumio Hayashi or Econometric Analysis by Greene.
Finally, if you really want to dig deep into this problem, the go to guide is the landmark "Time Series Analysis" by Hamilton. It is, however, a challenging book.
Be aware that there are other approaches in Statistics, often with their own terminology and goals. However in this case Econometrics is the best fit as it is designed exactly for problems such as this.
Which tests you'd have to run specifically depend very much on data and model and approach. It will be some kind of structural break test, if you want to look into what's available there. But, as you already realized, with 12 observations the sample size and therefore the model selection will be an issue before you even get to these tests.
Comment: The Wikipedia article on structural breaks provides a good place to start, and cites a variety of approaches. http://en.wikipedia.org/wiki/Structural_break
Answer: SSD For R is a package that makes this type of intervention analysis fairly easy. You just need an value and a phase column, and ABRegres will give you the data to determine if the trends in the baseline and intervention phases are statistically significant. https://ssdanalysis.com


Can I speed this query up without storing the group by and order by value?

Question: I have the following query:
<code>SELECT IF(dissolution_date IS NULL,
          YEAR(CURDATE()) - YEAR(incorporation_date),
          YEAR(dissolution_date) - YEAR(incorporation_date)) as length,
   COUNT(DISTINCT(id_company)) as count
FROM company
WHERE incorporation_date IS NOT NULL
GROUP BY length
ORDER BY length ASC
</code>
Given that I have the dissolution date (or a replacement for it) and the incorporation date it seems redundant to add an additional column to the table which stores the difference between the two dates (especially as if a company hasn't dissolved, the dissolution date would need updating every day year).
The EXPLAIN output is as follows:
<code> id | select_type | table   | type | possible_keys      | key  | key_len | ref  | rows    | Extra
----|-------------|---------|------|--------------------|------|---------|------|----------------------------------------
 1  | SIMPLE      | company | ALL  | incorporation_date | NULL | NULL    | NULL | 9128995 | Using where; Using filesort
</code>
and currently the query takes 10's of seconds, whereas similar queries on non-calculated columns take milliseconds, which is what I'd like to achieve here.
Is it possible to group and order by length without using filesort and without adding the length column to the original table? Or should I just add the length column in, in which case what would be the best way of updating the dissolution_date every day year?
Comment: What about replacing the `IF( ... )` with `YEAR(COALESCE(dissolution_date, CURDATE())) - YEAR(incorporation_date) AS length`
Comment: Thanks for the heads-up re: COALESCE, but it didn't make any difference :(
Comment: What's the use of `COUNT(DISTINCT id_company)`? Isn't the `id_company` the PK? If yes, you could replace that with `COUNT(*)`
Comment: @ypercube good shout, not sure I've completely got my head wrapped around when to use DISTINCT COUNTS and when to use COUNT(*)
Comment: One more thing. In MysQL, the `GROUP BY length ORDER BY length ASC` can be shortened to `GROUP BY length ASC` with guarenteed same results (and usually better performance). You can actually skip the `ASC` too but I prefer it there to identify to any future code reader what the query is supposed to do.
Answer: What you are referring to in Database theory is called a derived attribute. You do not want to implement such an attribute because although it will work fast, it's not very accurate. So we dont create a column for such an attribute but rather calculate it when needed.
There is no need for the file sorting, it's what the order by clause is doing.
Assuming that your query is correct, I would suggest creating a B Tree index on the company table using search key attributes (dissolution_date, incorporation_date) since they appear to be heavily used in your query.
Could you give an idea of the company table?
Comment: However, I'm getting `Using where; Using index; Using temporary; Using filesort` when I `EXPLAIN` the query... it does use the new key (of length 4) but I'd like to get it to stop filesorting if possible
Comment: Also could you expand on "Assuming your query is correct" please?
Comment: well an index is created for a specific query so: assuming the query is correct


Passing User-Agent through Cloudfront for Facebook scraper

Question: This question is borderline stackoverflow/serverfault, so don't hold it against me that it's here please :)
I have a service hosted on AWS, nginx with node.js behind it.
I have a cloudfront distribution setup to serve requests where the origin is the service (to be able to grow w/o adding application servers)
Amazon suggests filtering most headers from forwarded requets when setting up cloudfront distributions, specifically User-Agent, which they claim can vary dramatically, thus reducing the effectiveness of the CDN setup.
This works great for most cases, except when trying to share pages on facebook, in which case I need to know that the user agent is actually facebook (facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)) to be able to return a custom response.
I would create a special path for facebook share in order to use a custom cloudfront behaviour for such cases, but unfrotunately I can't control what the users will do so the shared url may be the same as "regular" server urls.
Suggestions?
Answer: If you need to know the user-agent for one case, there's little you can do other than whitelisting the User-Agent: header in the relevant CloudFront behavior.
CloudFront caches responses against the request headers it sends, so the net result will be that for a given request, a cached response that was obtained by forwarding a request with User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 will not be considered usable by CloudFront for serving a future request for User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36 even though for all practical purposes, it's the same browser.

When you configure CloudFront to cache based on one or more headers and the headers have more than one possible value, CloudFront forwards more requests to your origin server for the same object. This slows performance and increases the load on your origin server. If your origin server returns the same object regardless of the value of a given header, we recommend that you don't configure CloudFront to cache based on that header.
— http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html

The phrase "configure CloudFront to cache based on one or more headers" is synonymous with "whitelisting headers" to be forwarded to the origin.
This is the reason to forward only as much as you need -- to do otherwise hurts your cache hit ratio, in this case because of the variation of User-Agent: strings, which means you're not getting the full benefit of the edge caches, there are more requests processed by the origin server and more bandwidth used between the origin and CloudFront... but there isn't really an alternative.  CloudFront doesn't charge anything for storage in the edge caches, so the only cost difference will be whatever is found in those other factors.
The phrase "slows performance" (above) doesn't mean CloudFront gets slower -- it only refers to the reduced likelihood of any particular request being a cache hit, because of the variation in possible header values.
Incidentally, the behavior of CloudFront is correct, in this regard, since a varying User-Agent: can mean a varied response, as indeed you've indicated it does.
Judicious use of path patterns and multiple cache behaviors is the key to getting the best possible use of the CDN cache, given the circumstance you've described.  Only whitelisting User-Agent: on path patterns that need it, such as /images/* (which is, of course, a path I just made up) would be advisable.  This same advice also applies to cookies and query strings as well as headers.  For path patterns where you don't need the cookies and/or query strings, don't enable cookie and/or query string forwarding -- otherwise, cached responses will only be served to users who present the same cookie or for a request where the path and the query string match a cached response -- so, obviously, there would not be a lot of cache hits in such a situation.
Answer: It is now possible to use an origin request policy.
https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html
This allows us to forward headers to the origin without considering them for caching purposes. While the policy can be fine-tuned as needed, there is a predefined origin request policy called Managed-UserAgentRefererHeaders, which makes the origin User-Agent header visible at the origin (or at an origin request Lambda@edge function for that matter).
https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-origin-request-policies.html


Capturar datetime ajax com jquery

Question: Tenho um array contendo alguns objetos de uma chamada AJAX. Os valores estão sendo passados por meio de um data: "res.data.tags"
Em umas das respostas objetivo o seguinte resultado:
2016-07-15T10:00:00-0300

Como faço para capturar apenas o valor de "10:00" do datetime acima?
Answer: Utilize a biblioteca Moment.js para converter data/hora. Exemplo:
moment('2016-07-15T10:00:00-0300').format('hh:mm');

https://jsfiddle.net/j51b2mqn/

Capturar datetime ajax com jquery


golang binary not running on mips

Question: I'm using Go 1.11.4 on Windows 10 and I want to compile code for a MIPS 74Kc processor (Qualcomm Atheros QCA9558) running Linux.  I compile with:
GOOS=linux GOARCH=mips go build
Get an executable, upload and run it and get:
Illegal instruction
Try again w/ GOARCH=mipsle and get:
./hello_mipsle_linux: line 1: syntax error: unexpected "("
What am I missing?
Comment: We're you able to solve this? I'm having a similar issue
Comment: Yes.  See my answer below.  Simply add `GOMIPS=softfloat`.
Answer: My host doing the build had an FPU but the board does not.  Adding GOMIPS=softfloat fixed it:
GOOS=linux GOARCH=mips GOMIPS=softfloat go build
Comment: FYI: These MIPS binaries also run on Unifi AC access points! :D
Answer: To list all possible MIPS architects available to your current build toolchain, use the go tool e.g.
$ go version

go version go1.12 darwin/amd64

$ go tool dist list | grep mips

linux/mips
linux/mips64
linux/mips64le
linux/mipsle

so probably one of the remaining GOARCH permutations you have not tried e.g. mips64 or mips64le.
uname -m would help to determine your target system's machine architecture.
Answer: I have a similar issue and it's solved by setting GOARCH=mipsle. This should work
GOOS=linux GOARCH=mipsle GOMIPS=softfloat go build

My core is MIPS 24KEc V5.0, see my blog https://zyfdegh.github.io/post/202002-go-compile-for-mips/
If it's not OK, try these steps

Check the CPU architecture, Big-Endian or Little-Endian, by

$ lscpu | grep "Byte Order"

cat /proc/cpuinfo would also be helpful.

Check kernel info, mips or mips64, for me it's mips (32)

$ uname -a
Linux OpenWrt 4.14.151 #0 Tue Nov 5 14:12:18 2019 mips GNU/Linux

If it's Little-Endian, set GOARCH=mipsle, if it's 64bit Little-Endian, set set GOARCH=mips64le

Another related question Writing and Compiling Program For OpenWrt hope it helps.

golang binary not running on mips