Erro ao redirecionar depois de enviar formulário

Question: Meu código:
     <?php
        header('Content-Type: text/html; charset=utf-8');

        $email=$_POST[email];
        $nome=$_POST[nome];
        $cor=$_POST[cor];
        $nascimento=$_POST[nascimento];
        $cep=$_POST[cep];
        $endereco=$_POST[endereco];
        $numero=$_POST[numero];
        $complemento=$_POST[complemento];
        $referencia=$_POST[referencia];
        $bairro=$_POST[bairro];
        $cidade=$_POST[cidade];
        $uf=$_POST[uf];

        mail("email@example.com","Assunto do email","
        Nome: $nome
        Data de nascimento: $nascimento
        CEP: $cep
        Endereço: $endereco
        Número endereço: $numero
        Complemento: $complemento
        Referência: $referencia
        Bairro: $bairro
        Cidade: $cidade
        Estado: $uf
        ");

    /* Este header faz o redirecionamento, com alguns GET's que
serão usados na página na qual foi redirecionada. Exemplo, no
formulário foi colocado "João" no campo name="nome",
então nome é = a João. */

        header ("location: obrigado/?cor=$cor&nome=$nome&email=$email&cep=$cep&endereco=$endereco&numero=$numero&complemento=$complemento&bairro=$bairro&referencia=$referencia&cidade=$cidade&uf=$uf");

        ?>

Como podem ver, neste exemplo ele pega os dados que são preenchidos, mandam para esse script PHP através de um <form name="formulario" method="post" action="concluido.php">.

Esse script além de enviar um email pra mim com esses dados cadastrados, ele também pega esses dados e insere nos GET's contidos na url para qual será redirecionada.

Isso costumava funcionar antigamente, porém não consigo mais fazê-lo funcionar. Sempre achei ele muito simples, talvez seja por isso que ele está tendo problemas.

É possível fazer isto funcionar?

Observação: Está a redirecionar perfeitamente ao utilizar em localhost, mas utilizado em uma hospedagem web ocorre ESTE ERRO:

Não envia o e-mail para mim, e nem redireciona.
Comment: Qual erro acontece?
Comment: Vou postar aqui nos comentários o erro :) Só um momentinho...
Comment: @rray https://s11.postimg.org/9h98l00s3/Sem_T_tulo20161026093345.png
Comment: Removi a tag do título pois não precisa;
Answer: A página php que você colocou como exemplo esta recebendo via POST para capturar os "atributos" más pelo exemplo que você postou do formulário parece estar enviando via GET.
Mude o method de seu formulário para POST simples.
Comment: Lauro, na verdade era `POST`, eu tinha errado. Eu atualizei a pergunta :)
Answer: Alexandre,
tente este código formatado em (UTF-8 sem BOM) e refeito.
<?php
    $email              = addslashes($_POST['email']);
    $nome               = addslashes($_POST['nome']);
    $cor                = addslashes($_POST['cor']);
    $nascimento     = addslashes($_POST['nascimento']);
    $cep                = addslashes($_POST['cep']);
    $endereco           = addslashes($_POST['endereco']);
    $numero         = addslashes($_POST['numero']);
    $complemento        = addslashes($_POST['complemento']);
    $referencia     = addslashes($_POST['referencia']);
    $bairro         = addslashes($_POST['bairro']);
    $cidade         = addslashes($_POST['cidade']);
    $uf             = addslashes($_POST['uf']);

    $destinatario    = "email@example.com";
    $assunto         = "Assunto Exemplo";
    $msg             = "Nome: $nome
    Data de nascimento: $nascimento
    CEP: $cep
    Endereço: $endereco
    Número endereço: $numero
    Complemento: $complemento
    Referência: $referencia
    Bairro: $bairro
    Cidade: $cidade
    Estado: $uf ";

    $headers         = "MIME-Version: 1.1\r\n";
    $headers        .= "Content-type: text/plain; charset=UTF-8\r\n";
    $headers        .= "From: firstname.lastname@example.com\r\n"; // remetente
    $headers        .= "Return-Path: firstname.lastname@example.com\r\n"; // return-path
    $envio           = mail($destinatario, $assunto, $msg, $headers);

    if($envio){
       header ("location: obrigado/?cor=$cor&nome=$nome&email=$email&cep=$cep&endereco=$endereco&numero=$numero&complemento=$complemento&bairro=$bairro&referencia=$referencia&cidade=$cidade&uf=$uf");
    }else{
     echo "A mensagem não pode ser enviada";
    }
?>

Comment: Ok estou editando
Comment: @AlexandreLopes teste agora
Comment: Espero que de certo ;)
Comment: @AlexandreLopes Isso pode ser resolvido, usando **SMTP** ou algum outro método de enviar emails. Vou dar uma pesquisada e te mando!

Que bom que funcionou! HEHE **:P**
Comment: Está dando o erro `Parse error: syntax error, unexpected ';' in /home/xnshoptm/public_html/br/p/124678139/concluido.php`
Comment: O erro está nas linhas que contém esses `= addslashes`, pois o erro aparece em uma, e eu apago a linha, quando tento denovo, o erro pula pra próxima linha com `= addslashes`
Comment: Vou testar! Lucas :D
Comment: Funcionou!!! Está redirecionando e não apareceu nenhum erro. Único problema é que não está chegando o e-mail pra mim, estou usando meu email do Gmail. :/
Comment: Chegou!!! Só que tá indo pra caixa de spam! :) Kkkkkk...
Comment: Acho que é porque é como se meu próprio e-mail tivesse mandado para ele próprio, kkkkkk
Comment: Mas não tem muito problema não, o importante é chegar, nem que seja na caixa de spam, kkk :D
Answer: No topo tem isso:
header('Content-Type: text/html; charset=utf-8');

Essa linha escreve informações no cabeçalho.
No final tem outro header que serve para redirecionar para outra página.
header ("location: obrigado/?cor=$cor&nome=$....

Esse segundo header também precisa escrever no cabeçalho, mas como já foi disparado o cabeçalho no primeiro header(), acontece esse conflito, emitindo o famoso erro
Cannot modify header information..

Para resolver esse erro específico, remova ou desabilite o primeiro header()
//header('Content-Type: text/html; charset=utf-8');

Esse primeiro header não faz sentido pois se está a redirecionar sem precisar imprimir nada na página corrente, não precisa invocá-lo.
Comment: Interessante... ;)
Answer: O erro parece estar na hora de pegar as informações do $_POST, onde faltam aspas simples nos nomes das chaves em versões antigas isso era permitido e funcionava nas mais novas um warning é gerado ex: Notice: Use of undefined constant email - assumed 'email'.
Como o seu código tem uma chamada de header() e uma saida de texto não desejada (warning), acontece o erro Cannot modify header information - headers already sent by.
Para corrigir mude:
$email=$_POST[email];

Para:
 $email=$_POST['email'];

Sugestão de melhoria:
No lugar de gerar essa querystring na mão use a função http_build_query() para simplificar o trabalho, passado um array associativo ela gera a querystring.
Mude:
header ("location: obrigado/?cor=$cor&nome=$nome&email=$email&cep=$cep&endereco=$endereco&numero=$numero&complemento=$complemento&bairro=$bairro&referencia=$referencia&cidade=$cidade&uf=$uf");

Por:
$queryString = '?'. http_build_query($_POST);
header('location: obrigado/'. $queryString);

Não confie na função mail() faça uma verificação se o email realmente foi enviado. Como por exemplo:
if(!mail(......)){
   die(print_r(error_get_last()));
}

Comment: Vou testar agora :)
Comment: Continua o mesmo erro: https://s11.postimg.org/9h98l00s3/Sem_T_tulo20161026093345.png
Comment: @AlexandreLopes o encode do seus arquivos é utf-8 without BOM?
Comment: Tem algum problema ou algo errado na resposta? posso corrigir
Comment: `charset=utf-8`, @rray, teria como editar sua resposta? colocando o código por completo, eu sou novo com PHP, aí eu não saquei muito bem como fazer funcionar, se você fizer isto, eu vou entende-lo perfeitamente :)
Comment: @AlexandreLopes qual editor de texto vc usa? geralmente o encode do arquivo fica na parte de baixo. vc precisa adicionar aspas simples em todas as chaves, do `$_POST['email']` até o `$_POST['uf']`. Para montar o teste rápido, comente a linha do `header()` assim é possível ver os erros antes dele direcionar a página.
Comment: Utilizo o Sublime Text. Adicionei todas as aspas simples como você mencionou.
Comment: @AlexandreLopes agora que vi, remova aquele primeiro `header('Content-Type: text/html; charset=utf-8');`
Comment: Veja o erro permanece: https://s13.postimg.org/3ylky6u4n/Sem_T_tulo20161026100711.png
Comment: @AlexandreLopes a linha 43 e anterior são quais?
Comment: Parece que tem um caracter invisivel na primeira linha do seu arquivo, tente mudar o encode dele para utf-8 without BOM.
Comment: @AlexandreLopes a linha 31 é do echo?
Comment: A linha do header com location. O erro parece está ai.
Comment: Veja: https://s12.postimg.org/rqp5q7s3x/Sem_T_tulo20161026102248.png
Comment: @AlexandreLopes sobre o como mudar o encode do arquivo veja [essa pergunta](http://stackoverflow.com/q/21289157/1342547)
Comment: Agora eu salvei aqui. Vou testar :)
Comment: O erro continua o mesmo: https://s12.postimg.org/rqp5q7s3x/Sem_T_tulo20161026102248.png essa linha 31, é a linha do `header ("location:`
Comment: @AlexandreLopes o erro diz que algum texto foi enviado na primeira de `concluido.php` imagino que seja o arquivo da pergunta ou ele é um include?
Answer: Bom valos lá,
Primeiramente olhe a mensagem :

"Cannot modify header information - headers already sent by"*
"Não é possível modificar a informação de encabeçamento - encabeçamentos já enviada pelo (concluido.php line 1)

Oque podes fazer é usar um echo "";
<?php
    header('Content-Type: text/html; charset=utf-8');

    $email       = $_POST['email'];
    $nome        = $_POST['nome'];
    $cor         = $_POST['cor'];
    $nascimento  = $_POST['nascimento'];
    $cep         = $_POST['cep'];
    $endereco    = $_POST['endereco'];
    $numero      = $_POST['numero'];
    $complemento = $_POST['complemento'];
    $referencia  = $_POST['referencia'];
    $bairro      = $_POST['bairro'];
    $cidade      = $_POST['cidade'];
    $uf          = $_POST['uf'];

    mail("firstname.lastname@example.com","Assunto do email","
    Nome: $nome
    Data de nascimento: $nascimento
    CEP: $cep
    Endereço: $endereco
    Número endereço: $numero
    Complemento: $complemento
    Referência: $referencia
    Bairro: $bairro
    Cidade: $cidade
    Estado: $uf
    ");

/* Este header faz o redirecionamento, com alguns GET's que serão usados na página na qual foi redirecionada. Exemplo, no formulário foi colocado "João" no campo name="nome", então nome é = a João. */

    echo "";

    ?>

Ps: não seria a forma totalmente ideal, más serve!
Comment: Ele continua dando o mesmo erro, a diferença é que depois de exibir o erro, ele é redirecionado. Apenas isso :/
Comment: @AlexandreLopes Copie este código agora, este problema deve ser dado pois antes de abrir a tag **<?php** estava com espaços em branco! teste agora!
Comment: O problema não é esse não :(
Comment: @AlexandreLopes esté o código completo da tua página ?


Is the Beukers-Kolk-Calabi substitution incorrect?

Question: Consider the sum following sum:
$$ I=\sum_{i = 0}^{\infty}\frac{(-1)^{i}}{(2i+1)^{2}(2i+2)}. $$
Clearly this can be transformed into a triple integral:
$$ I=\int_{0}^{1}\int_{0}^{1}\int_{0}^{1} \frac{x}{1+x^{2}y^{2}z^{2}}dxdydz.$$
However, because of symmetry I can rewrite the integral as follows:
$$ I=\int_{0}^{1}\int_{0}^{1}\int_{0}^{1} \frac{y}{1+x^{2}y^{2}z^{2}}dxdydz=\int_{0}^{1}\int_{0}^{1}\int_{0}^{1} \frac{z}{1+x^{2}y^{2}z^{2}}dxdydz.$$
Now apply the following substitution to each of the integrals:
$$ x = \frac{\sin(u)}{\cos(v)},\space y = \frac{\sin(v)}{\cos(w)},\space z = \frac{\sin(w)}{\cos(u)} $$
and you will find out that suddenly, those integrals are not mutually equal. Why is that so? The same substitution can be used to evaluate, for instance, the alternating sum of the reciprocals of odd cubes, in which case it yields a correct result.
$$ \sum_{i = 0}^{\infty}\frac{(-1)^{i}}{(2i+1)^{3}}=\int_{0}^{1}\int_{0}^{1}\int_{0}^{1} \frac{1}{1+x^{2}y^{2}z^{2}}dxdydz = \frac{\pi^{3}}{32}. $$
Comment: These two are not equal: https://www.wolframalpha.com/input/?i=integrate%5Bintegrate%5Bintegrate%5B++sin%28u%29%2Fcos%28v%29+%2Cw%2C+0%2C+pi+%2F+2+-+v%5D%2C+v%2C+0%2C+pi+%2F+2+-+u%5D%2C+u%2C+0%2C+pi+%2F+2%5D   https://www.wolframalpha.com/input/?i=integrate%5Bintegrate%5Bintegrate%5B++sin%28w%29%2Fcos%28u%29+%2Cw%2C+0%2C+pi+%2F+2+-+v%5D%2C+v%2C+0%2C+pi+%2F+2+-+u%5D%2C+u%2C+0%2C+pi+%2F+2%5D
Comment: OK, I see. But are you really integrating over the correct domain? According to the original B-K-C paper, it's supposed to be $\{ u>0, v>0, w>0, u+v<\pi/2, v+w<\pi/2, w+u<\pi/2 \}$, and if you use the triangle $\{ u>0, v>0, u+v<\pi/2 \}$ as your "bottom plate" in the $uv$-plane, then you should split it into two parts along the line $u=v$, since the "ceiling" is given by $w = \min(\pi/2-u,\pi/2-v)$ and you need to deal with the two cases $u \gtrless v$.
Comment: Compare to the result you get using $\int_{w=0}^{\min(\pi/2-u,\pi/2-v)}$ instead: [WA link](https://www.wolframalpha.com/input/?i=integrate%5Bintegrate%5Bintegrate%5B++1+%2Cw%2C+0%2C+min%5Bpi%2F2+-+u%2C+pi+%2F+2+-+v%5D%5D%2C+v%2C+0%2C+pi+%2F+2+-+u%5D%2C+u%2C+0%2C+pi+%2F+2%5D).
Comment: Yes, turns out the bounds were a problem. Thank you! Could you please post it as an answer so that I could tick the question off?
Comment: What makes you say that they are not equal? What do you get after doing the substitutions? Two integrals can of course have the same value even if it's not "visually obvious".
Comment: The area of integration is exactly the same as in the case of computing the sum of cubes, where I do get the correct result.
Comment: You've written exactly the same integral for the sum of cubes as for the first sum $I$. Is it supposed to be like that, or is it a copy-and-paste error. If it is indeed the same, then the same argument could be used to criticize your sum-of-cubes calculation, couldn't it?
Comment: Thank you for noticing. That was a mistake, I have now edited the post.
Comment: OK, but with 1 in the denominator, the integral over your domain becomes $\pi^3/24$, not $\pi^3/32$ as you claim, so in fact you *don't* get the correct result in that way. ([WA link.](https://www.wolframalpha.com/input/?i=integrate%5Bintegrate%5Bintegrate%5B++1+%2Cw%2C+0%2C+pi+%2F+2+-+v%5D%2C+v%2C+0%2C+pi+%2F+2+-+u%5D%2C+u%2C+0%2C+pi+%2F+2%5D))
Answer: The conditions are that $u$, $v$ and $w$ are all positive, while $u+v$, $v+w$ and $w+u$ are all less than $\pi/2$, so the correct way of integrating is
$$
\int_{u=0}^{\pi/2} \int_{v=0}^{\pi/2-u} \int_{w=0}^{\min(\pi/2-u,\pi/2-v)} \cdots
$$
Comment: In fact, there is a way to evaluate the volume of this Beuker, Calabi, Kolk polytope in any dimension. See my answer or this joint paper by Daniele Ritelli and myself for more details: https://www.ams.org/journals/qam/2018-76-03/S0033-569X-2018-01499-3/
Comment: @VivekKaushik: I wasn't able to access your paper (no subscription), but the volume of the polytope was evaluated (in terms of Euler or Bernoulli numbers depending on the parity of the dimension) already in the original Beukers–Calabi–Kolk article, wasn't it?
Comment: sorry, here is the ArXiv preprint https://arxiv.org/abs/1710.03637. Yes Beukers, Calabi, Kolk, as well as Elkies, Stanley, and plenty of others evaluated the polytope in terms of Euler and Bernoulli numbers. But my paper I referenced (as well as my asnwer to this question), show the generalization of your answer through an alternative combinatorial means without using Bernoulli/Euler numbers (it amounts to evaluating certain monomial functions over simplices).
Comment: @VivekKaushik: OK, thanks.
Answer: To answer your question in general, one can evaluate the sum $S(k)=\sum_{n \ge 0} \frac{(-1)^{nk}}{(2n+1)^k}$ for $k \in \mathbb{N}$ via evaluating  the multidimensional integral $$I_k=\int_{(0,1)^k} \frac{1}{1-(-1)^k x_1^2 \ \dots \ x_k^2} \ dx_k \ \dots \ dx_1.$$
With some rigorous justification, we can use Calabi's change of variables $x_i=\frac{\sin(u_i)}{\cos(u_{i+1})}$ for $1 \le i \le k,$ with $u_{k+1} :=u_1$ to evaluate this integral $I_k.$ Calabi's change of variables has Jacobian determinant:
$$\left |\frac{\partial(x_1, \ \dots \ ,x_k)}{\partial (u_1, \ \dots \ , u_k)} \right|=\left(\frac{\pi}{2} \right)^k \left(1-(-1)^k x_1^2 \ \dots \ x_k^2\right),$$ and diffeomorphically maps the open cube $(0,1)^k$ to the convex polytope
$$\Delta^k = \left \lbrace (u_1, \ \dots \,  u_k): u_i+u_{i+1} < 1, u_i>0, i \in \lbrace 1, \ \dots \ , k \rbrace \right \rbrace.$$ Thus,
$$S(k)= \left( \frac{\pi}{2} \right)^k \text{Volume}(\Delta^k).$$
There is a general way to compute the volume of $\Delta^k,$ which amounts to dissecting $\Delta^k$ into a disjoint union consisting of the open cube $(0,1/2)^k$ and simplices in $\mathbb{R}^k$ based on combinatorial arguments. See this joint paper by Daniele Ritelli and myself: https://www.ams.org/journals/qam/2018-76-03/S0033-569X-2018-01499-3/
I used a special case $k=4$ of the general argument to answer this question: https://math.stackexchange.com/a/1794967/169367.
When it is all said and done, the result is the following:
$$S(k)= \left(\frac{\pi}{4} \right)^k +\left(\frac{\pi}{4} \right)^k  \sum_{n=1}^{ \left \lfloor \frac{k}{2} \right \rfloor} \sum_{\substack{(r_1, \dots, r_n) \in [k]^n: \\ |r_p-r_q| \notin \lbrace 0,1,k-1 \rbrace, \\ p,q \in [n]} } \prod_{i=1}^{n} \frac{1}{i+\sum_{j=1}^{i} \alpha_j},$$
where $[m]:= \lbrace 1, \dots, m \rbrace$ and
$$\alpha_j=2- \delta(k,2) - \sum_{m=1}^{j-1} \delta(|r_m-r_j|,2)+\delta(|r_m-r_j|,k-2)$$ and $\delta(a,b)$ is the Kronecker Delta Function. In particular, the inner sum in the second term of that gargantuan formula above is taken over all tuples $(r_1, \dots, r_n) \in [k]^
n$ having cyclically pairwise nonconsecutive entries.


For what prime numbers $p$ is $x^2+x+1$ irreducible in $\mathbb{F}_p[X]$

Question: I think it's enough to search for the prime numbers where $x^2+x+1=0$ is not solvable, but I am not sure where to start. Thank you
Comment: It is irreducible for $p=2,5,11,...$
Answer: $ax^2+bx+c$ is reducible precisely if $b^2-4ac$ has a square root (PS in response to comments: EXCEPT when the characteristic of the field is $2$.  The usual formula for solving quadratic equations cannot apply in that case since dividing by $2a$ would be dividing by $0$.).  In the case of $x^2+x+1$, we have $b^2-4ac=-3$.  So the question is, for which primes $p$ does $-3$ have a square root modulo $p$?
PS: What happens if you try to complete the square in $x^2+\dfrac b a x$ in a field of characteristic $2$?  Usually we're told to find half of $b/a$. In a field of characteristic $2$, you can't take half of anything except $0$.
Comment: ...And this is solved by the theorem on quadratic reciprocity.
Comment: **Counterexample** $\, x^2+x+1\, $ is irreducible over $\Bbb F_2$ but has square discriminant $=1.\ \ $
Answer: Hint: If $x^{2} + x + 1$ has a non-trivial factor in $\mathbb{F}_{p}[x]$ (and $p \neq 3$), then $x^{3} - 1 = (x-1)(x^{2}+x+1)$ has a root other than $1$ in $\mathbb{F}_{p}$.
Comment: OP, please use this and not quadratic reciprocity.
Answer: In order that $x^2+x+1$ splits over $\mathbb{F}_p$ (with $p>3$), the discriminant of $x^2+x+1$, i.e. $-3$, must be a quadratic residue $\!\pmod{p}$. That happens iff $p\equiv 1\pmod{3}$: for a proof, see this other question.


AWS Timestream query to detect when I am not getting data

Question: AWS Timestream uses a query language based on SQL. I have a Timestream database table that is receiving a heartbeat from senders every 4 minutes. The thought is to detect is something is down. The data looks like this:
Thing    measure_name    time                       measure_value::bigint
Machine1    Time    2022-06-10 20:27:51.095000000   1654892871095
Machine1    Time    2022-06-10 20:27:29.676000000   1654892849676
Machine2    Time    2022-06-10 20:25:31.654000000   1654892731654
Machine2    Time    2022-06-10 20:25:30.689000000   1654892730689

The data drops out of the table after a week.
I need to somehow write a query that determines for all things in the table if each thing is in the table does not have any heartbeats in the last x minutes. I feel like this is possible but I just don't know how. I have written a static query for a particular thing like so:
SELECT
CASE
    WHEN count(Thing) > 0 THEN 'Up'
    ELSE 'Down'
END AS Status
FROM "Uptime"."Uptime" WHERE time between ago(15m) and now() and Thing = 'Machine1'

It has some weaknesses though. I don't want to write a new query for each thing as they are created and remove a thing specific query when the thing is destroyed.
I guess I want to get all the things in the table and then do a query for each thing and return a list of things that are down. I just need to do this in a single query.
How?
Answer: OK, I have an answer (not necessarily the right answer). What I needed to do in a sub-query and then a main query. In the sub-query I would get the max time grouped by thing. IN the main query get the count of the things that have a max time of less then x seconds. The query looks like this:
select count(Thing) from
(
select distinct Thing, max(time) as last
from "Uptime"."Uptime"
group by Thing) as t1
where t1.last < ago(5m)

This gives a count of the number of things that we have not heard from within the last 5 minutes.


Acessa controller de um outro projeto na mesma solution

Question: Pessoal eu eu tenho 3 projetos na mesma solution:
KnockDocWeb, KanoDockModels e KnodockApi como mostra a imagem abaixo:

Quando eu compilo o projeto ele inicia o KanoDockWeb, porém eu quero Acessar uma Controller que esta no KanoDocApi  pelo KanoDockWeb.
Eu quero acessar uma controller chamada UsuarioApiController e o método Login;
Eu quero saber, na URL como eu acesso aquela controller?
Eu já tentei:
<code>localhost:18459/UsuarioApi/Login
localhost:18459/api/UsuarioApi/Login
localhost:18459 /KnockDocApi/UsuarioApi/Login
</code>
Nenhum eu obtive êxito.
Mais uma coisa:
Quando eu dou um brakpoint em qualquer controller de KnockDocApi eu tenho a seguinte mensagem: The breakpoint will not currently be hit. No symbols have been loaded for this document.
Só ressaltando que o KanoDockApi é um projeto do tipo Web Api
Por favor, alguém me ajuda???
Agradeço desde já.
Comment: Um projeto faz `using` do outro? Como você está fazendo com o Service Locator?
Answer: Robson, você está trabalhando com 2 projetos do tipo Web Application, para rodar, eles precisariam estar publicados (num servidor web ou numa web server virtual como está fazendo aí).
O que você está querendo fazer é o mesmo que 2 websites se comunicarem e trocarem informação.
Para conseguir rodar os 2, você teria que abrir uma porta para cada aplicação. Porém, mesmo assim não seria possível fazer essas chamadas, somente independentes. Suas tentativas não funcionam pois o KnockDocWeb está rodando na porta 18459, e não o KnockDocApi.
Te aconselho a criar um novo projeto do tipo Class Library que conterá a lógica desta controller que você está precisando chamar. Assim, ela pode ser compartilhada em ambos web sites.


Mixing strings and numbers with Excel Interop

Question: I'm using F# and Excel Interop. I'm doing something like:
workbook.Range("A1:A10").Value2 <- [| "foo"; "3"; "bar"; "6"; "8" |]

When I look at the resulting spreadsheet, it is storing the "3", "6", and "8" as strings instead of numbers. This means that formulas and such fail. Is there a way to make Excel convert strings to numbers where appropriate?
My current workaround is this:
workbook.Range("A1:A10").Value2 <- [| "foo" :> obj
                                      3 :> obj
                                      "bar" :> obj
                                      6 :> obj
                                      8 :> obj |]

It produces the desired effect, but it awkward. Is there a better way to do this?
Answer: let a : obj[] = [| "foo"; 3; ... |]

give the array a type annotation, and it will auto-upcast the elements.


Are any keyboard methods or music theory concepts based on keyboard mirror symmetry?

Question: About a year ago I noticed there is a kind of mirror symmetry on the piano keyboard regarding the shape/distance of the black and white keys when starting at C major and then chromatically descending for the minor keys and chromatically ascending for the major keys.
I tried to make this chart to demonstrate...

MINOR                     │ MAJOR
                          │
key sig. key. piano triad │ piano triad. key. key sig.
                          │
2 #      Bm   w w B       │ B w w        Bb   2 b
5 b      Bbm  B B w       │ w B B        B    5 #
0        Am   w w w       │ w w w        C    0

etc...

The w's and B's mean white or black piano keys.
Each 'pair' has the triads as a sort of inversion of the other. The count of accidentals in the key signatures is the same, but the sharps/flats are flipped.
I also noticed an inverted or retrograde symmetry regarding the scales on these tonics.
The retrograde of the 5th mode of one scale produces the sequence of the 'symmetrical' matching scale, ex...

Bb major: B w w B w w w
                  |
          b minor w B w w B w w (retrograde of the 5th mode of Bb)

I figured this out when trying to compare the fingering issues betwwen left and right hands and realizing that, for example, B minor is the left hand isn't really like B minor in the right hand. Rather B minor is like B♭ major in the right hand. At least it is in terms of shape.
I applied this to 5 finger position for stuff like little scale turns shakes in thirds, etc.
Are there any piano methods based on this kind of symmetry?
The only theory concept I know which seems related is Riemann 'dualism' with the scale inversion.
Are there other related theory ideas? Something like a harmonic sequence or modulations?
Comment: Not an answer, but if you find this sort of thing interesting, you might want to read Dmitri Tymoczko's "A Geometry of Music". If I remember correctly, he makes very similar observations to yours.
Answer: German pianist and composer Victor Alcántara has studied the subject of the keyboard's mirror symmetry in depth; he has published a book ("Palindromorphy") on this.
Answer: Some melodies are the "inversion" of another melody about an axis which need not be contained within the melody or starting key. Your example could be used to invert a melody around the C axis.
Another similar notion occurs in the "omnibus progression" (AKA wedge progressions.)
Answer: My observations on this topic:

(Applicable to all instruments) If we divide a major scale 7 notes by the middle note(4th note), the left three notes will have similar intervals that of right three notes.

Example: In C Major,
Left Side
C to D is Whole and D to E is Whole
Right Side
G to A is Whole and A to B is Whole

(Applicable to all instruments) If we divide a minor scale 7 notes by the middle note, the left three notes will have the mirror intervals that of right three notes.

Example: In Bb minor,
Left Side
Bb to C is Whole and C to Db is Half
Right Side
F to Gb is Half and Gb to Ab is Whole

(Applicable to Piano) If we divide a major/minor scale 7 notes by the middle note, the left three notes will have the same number of black and white keys that of right three notes, In case of odd number of white/black keys, left side will get extra black and right side will get extra white for key signatures with b while right side will get extra black and left side will get extra white key for key signatures with #.

Example: In C Major,
Left Side
<code> C,D,E are White, 3 white and 0 black
</code>
Right Side
<code> G,A,B - 3 white and 0 black
</code>
Example: In Bb minor,
Left Side
<code> Bb,C,Db - 2 black, 1 white
</code>
Right Side
<code> F,Gb,Ab - 2 black, 1 white
</code>
Example: In Bb Major, (5 bs)
Left Side
<code> Bb,C,D - 2 white, 1 black (extra black in left side)
</code>
Right Side
<code> F,G,A - 3 white, 0 black (extra white in right side)
</code>
Example: In A Major, (3 #s)
Left Side
<code> A,B,C# - 2 white, 1 black (extra white in left side)
</code>
Right Side
<code> E,F#,G# - 1 white, 2 black (extra black in right side)
</code>
Note: Also when we play melodies in these left and right sections in same rhythm consequently, we will get some kind of call and response melody feelings.


Why is an ${m \times n}$ matrix a transformation from $\mathbb R^n$ to $\mathbb R^m$?

Question: Probably basic, but I just don't get the concept.
Comment: @Bernard Considering the context, I'd assume they almost certainly mean the real numbers.
Answer: Taking a matrix $A \in R^{m \times n}$, a vector $v \in R^n$, how many entries does $A\cdot v$ have?
Answer: A $m \times n$ matrix $A$ is not a transformation!
Rather, given basis of $\mathbb{R}^n$ and $\mathbb{R}^m$, it represents a transformation $u$.
eg say you have a basis $v_1, \dots, v_n$ of $\mathbb{R}^n$ and a basis $w_1,\dots, w_m$ of $\mathbb{R}^m$. Let $u : \mathbb{R}^n \mapsto \mathbb{R}^m$ be a linear function.
Any vector $v \in \mathbb{R}^n$ can be written uniquely
$v = \sum_{i=1}^n \lambda_i \cdot v_i$ for some scalars $(\lambda_i)_{1\leqslant i \leqslant n} \subset \mathbb{R}$. One can see that $u(v) = \sum_{i=1}^n \lambda_i \cdot u(v_i)$.
Hence, $u$ is determined by the way it acts on the basis  of $\mathbb{R}^n$.
In other words, a compact way of describing $u$ is to describe only the vectors $u(v_1),\dots,u(v_n)$. We will now describe these vectors in the basis $w_1,\dots,w_m$ :
Take any $i$, there are scalars $\alpha_{i,1},\dots,\alpha_{i,m}$ such that
$$u(v_i) = \sum_{j=1}^m \alpha_{i,j} \cdot w_j$$
So, given these two basis, $u$ is fully described by the matrix
$$A := \begin{pmatrix} \alpha_{1,1} & \dots & \alpha_{n,1}\\
\vdots & \ddots & \vdots \\
\alpha_{1,m} & \dots & \alpha_{n,m} \end{pmatrix}$$
Answer: This is not so much an answer as an observation. We normally write functions on the left, as in applying a linear transformation $T$ to a vector $v \in \mathbb{R}^n.$ So, when we determine a matrix representation $A$ of $T,$ say the standard matrix, we multiply $v$ on the left by $A,$ treating $v$ as a $1$ column matrix, so $A$ will be $m \times n$ if we wish to obtain a vector in $\mathbb{R}^m.$
When I first learned linear algebra years ago, there was a fashion among some algebraists to write functions and operators on the right, so that the composition of functions $f$ and $g$ would be written $f \circ g,$ the natural left to right order. In this situation, the value of $T$ at $v$ would be $vT.$ Now, the matrix multiplication by the standard matrix $A$ of $T$ would be on the right, so we have $vA,$ treating $v$ as $1 \times n$ matrix. In this setup, $A$ would indeed be an $n \times m$ matrix, probably what people would expect.
Although I have read some algebra where authors used "function on the right" notation, my original exposure to linear algebra was the only time I actually used it. It took a bit of concentration to deal with the traditional "function on the left" when I met it in later encounters with linear algebra. By now, it is second nature. The right-hand notation has its benefits, but the tradition of left-hand notation is difficult to oppose.


Western musical instruments that can be played with one hand

Question: https://www.google.com/search?q=western+musical+instruments
Will it be very few western musical instruments that can be played by human beings with one hand only?
Example : Mouth organ.
Comment: Paul Wittgenstein famously played the piano with one hand only since he lost his right arm during the First World War.  He commissioned many works for this purpose from famous composers.  Many percussion instruments can be played with one hand - tubular bells, castanets, maracas, tam tam, etc.
Comment: it's an interesting question, but it needs a lot more research.
Comment: Is mouth organ another term for harmonica? Or melodica? Any keyboard instrument can be played with one hand.
Comment: Are feet allowed?
Comment: Do you accept being able to play an instrument within a limited but still useful range, like e.g. keyboard instruments
Comment: Lots of percussion instruments can be played one-handed.
Comment: @ToddWilcox - mouth organ = harmonica = 'harp'. No, not the harp one needs to wear in order to play it!
Comment: Possible better question - what instruments **cannot** be played properly with only one hand?
Comment: Do you mean the "country and western" tag? You could crack a whip one-handed (a-la the Blues Brothers version of Theme from Rawhide)?
Comment: @Tim Yeah, I know about "harp", that's what I usually call them (been a blue harp player for decades). Just never heard "mouth organ" before.
Comment: Check out Ben Clements: https://www.youtube.com/watch?v=ZFs0xlpGnl8&list=RDZFs0xlpGnl8&start_radio=1&t=0
Answer: Bugles are one-handed. Trumpets, tenor and French horns would be playable to some extent. The pipe of a pipe and tabor! Flexatones are lovely things. I've seen virtuoso bass guitarists play whole pieces with one hand.
At OHMI (One handed musical Instruments) there are all kinds of instruments and adapted instruments. The one-handed clarinets and Chapman Sticks look good. They also have supports for the trumpet and trombone.
Answer: Keyboard instruments such as piano, plucking instruments such as harp, .... many can be played with one hand only.
Answer: Drums. Rick Allen, the drummer with Def Leppard, lost an arm in a car crash may years ago, but has carried on ever since (using an adapted kit, but nothing that any drummer couldn't put together using midi)
Answer: Three hole pipe. Usually used in conjunction with a drum to form the pipe and tabor, but the pipe part is a one-hander
Comment: I think that's the pipe I mentioned above. Do you play it btw?
Comment: Yes it is, sorry for the duplication. And yes I do play, not very much but it gets a run out occasionally


How to syncronize a working queue with a file directory

Question: In Blue Prism, I want my work queue to consist of alle files added to a file directory. The item key is the filename. I solve this by reading all the filenames, and then loop through each one, check if it is in the queue, and if not, add it.
There will be thousands of files in the directory, so I don't want to loop through all files every time the process starts.
Alternatively, using "get all completed items", I can get the itemID of the completed items, but then I have to use "get item data" on each one to get the filename to check if the file needs to be added to the queue. Any better ideas ?
Comment: Well, IMO the easiest thing to do would be to differentiate the input. For example use separate directory for new files and move them to target directory after they're added to the queue or processed, or add some prefix to the file names that will help BP filter through them (e.g. new__filename; old__filename).
Comment: You can move the file from one directory to another (lets say Success/Completed) which you added to BP queue. So the input directory will always be empty when new batch of files are coming. Once the BOT starts next time, BOT will pick new files from file directory and it will not loop through the previous available and new files, it will loop through only new available files.
Answer: That's a interesting problem.
It must be possible to achieve that by doing SQL query on BP database. If you have an access to it, then this might be the simplest and best solution. I can't help you with that though, as I've never done that.
A simpler solution would be to make a snapshot of the input folder whenever the queue in populated and store it. I've did similar thing in my recent project :)
Example flow that would involve a snapshot:
First, I create an Excel workbook with data from current run (in a sheet "New") and a previous run (in sheet "Old"). I'd save it in some kind of internal location.

Get a list of all input files
Open a previous excel workbook
Remove data from "Old" worksheet
Move data from worksheet "New" to "Old"
Paste a list of all input files to "New" worksheet
Save and close Workbook
Run OleDB query to retrieve a list of files that are in "New" sheet, but are not in "Old" sheet.
Comment: While using BP to do SQL queries on a BP database might be the simplest and most stable solution, it is not the best in regards to RPA, as it violates the ROM dictate of replicating the the users work process with the bot while still ensuring the user can replicate the work process of a bot should it fail.


Guardar varios valores em campo da tabela mysql

Question: Queria arrumar um jeito de guardar, por exemplo, os códigos de uns médicos que participaram de uma consulta de um animal.
Queria guardar mais de um veterinário na consulta.(quantos for necessario)
create table if not exists consulta(
codConsulta character(8) not null primary key,
crv character(5) ,
codAnimal character(8) not null,
diagnostico text not null,
constraint fk_crv foreign key (crv) references veterinario(crv),
constraint fk_codAnimal foreign key (codAnimal) references animal(codAnimal))engine=INNODB default charset = utf8;

Comment: Leia sobre Normalização de Dados (Formas Nornais) , está no caminho errado acredite.
Answer: A melhor maneira seria ter três tabelas (consulta, veterinario e veterinario_consulta ).
A tabela veterinario_consulta seria n para n guardando os códigos da consulta e veterinário
N para N (explicação)
https://fmhelp.filemaker.com/help/18/fmp/pt/index.html#page/FMP_Help/many-to-many-relationships.html
Fiz um exemplo funcionando em http://sqlfiddle.com/#!9/b94c3c/5
CREATE TABLE IF NOT EXISTS `veterinario` (
  `id` int(6) unsigned NOT NULL,
  `nome` varchar(80) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

INSERT INTO `veterinario` (`id`, `nome`) VALUES
  ('1', 'Carlos Manga'),
  ('2', 'Leonardo Pires'),
  ('3', 'João Duarte');

CREATE TABLE IF NOT EXISTS `cliente` (
  `id` int(6) unsigned NOT NULL,
  `nome` varchar(80) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

INSERT INTO `cliente` (`id`, `nome`) VALUES
  ('1', 'Fernando'),
  ('2', 'Maria Inês'),
  ('3', 'Carmem');

CREATE TABLE IF NOT EXISTS `consulta` (
  `id_consulta` int(6) unsigned NOT NULL,
  `id_cliente` int(6) NOT NULL,
  `dt_consulta` date NOT NULL,
  PRIMARY KEY (`id_consulta`)
) DEFAULT CHARSET=utf8;

INSERT INTO `consulta` (`id_consulta`, `id_cliente`, `dt_consulta`) VALUES
  ('1', '1','2020-05-05'),
  ('2', '1','2020-05-13'),
  ('3', '3','2020-05-27'),
  ('4', '2','2020-06-02'),
  ('5', '4','2020-06-30'),
  ('6', '5','2020-07-16');

CREATE TABLE IF NOT EXISTS `veterinario_consulta` (
  `id_consulta` int(6) unsigned NOT NULL,
  `id_veterinario` varchar(80) NOT NULL,
  PRIMARY KEY (`id_consulta`,`id_veterinario`)
) DEFAULT CHARSET=utf8;

INSERT INTO `veterinario_consulta` (`id_consulta`, `id_veterinario`) VALUES
  ('1', '2'),
  ('1', '3'),
  ('2', '1'),
  ('3', '2'),
  ('3', '3'),
  ('4', '2'),
  ('5', '1'),
  ('3', '1');

Exemplo consulta
select c.id_consulta, l.nome cliente, v.nome veterinario
  from consulta c,
       veterinario_consulta vc,
       cliente l,
       veterinario v
 where c.id_consulta    = vc.id_consulta
  and  v.id             = vc.id_veterinario
  and  c.id_cliente     = l.id

Você pode retornar os veterinários em uma linha também usando group_concat
https://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php
select c.id_consulta, l.nome cliente, group_concat(v.nome) veterinario
  from consulta c,
       veterinario_consulta vc,
       cliente l,
       veterinario v
 where c.id_consulta    = vc.id_consulta
  and  v.id             = vc.id_veterinario
  and  c.id_cliente     = l.id
  group by c.id_consulta, l.nome

Comment: Julgo ser interessante deixar claro que "melhor" é completamente relativo. Nem sempre a normalização é, de fato, a melhor forma. É bem comum, inclusive, vermos o processo de desnormalização dos bancos para otimização. Talvez sugerir a normalização inicialmente por questões de facilidade de manutenção faça mais sentido.
Comment: mas se a consulta tiver mais de um veterinário ?
Comment: No exemplo que fiz acima http://sqlfiddle.com/#!9/b94c3c/5 a primeira consulta possui dois veterinários, conforme as duas primeiras linha no retorno.
Comment: Se deve conhecer as Formas Normais para se decidir não usá-las. Neste caso então não vejo motivo para não ser conservador, desnomarlizar só vai gerar consultas e cadastros complicados à toa.


On Wikipedia's article Carathéodory's extension theorem

Question: Wikipedia's article(https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_extension_theorem) says:

Let $R$ be a ring on $\Omega$ and $\mu: R \rightarrow [0, +\infty]$ be a pre-measure on $R$.
  The Carathéodory's extension theorem states that[2] there exists a measure
  $\mu':\sigma (R) \rightarrow [0, +\infty]$ such that $\mu'$ is an extension of $\mu$. (That is, $\mu'|R = \mu$).
  Here $\sigma (R)$ is the $\sigma$-algebra generated by $R$.
  If $\mu$ is $\sigma$-finite then the extension $\mu'$ is unique (and also σ-finite).[3]

Let $(X,\mathcal A,\nu)$ be a finite measure space, where $\mathcal A$ is a $\sigma$-algebra.
Let $Y$ be a non-empty member of $\mathcal A$ such that $X\neq Y$. Let $\mathcal R=\{E:E\subset Y,E\in \mathcal A\}$. Then $\mathcal R$ is a $\sigma$-ring on $X$. Let $\mu$ be the restriction of $\nu$ on $\mathcal R$. Let $\mathcal B = \{E: E\in \mathcal R \text{ or } X- E\in \mathcal R\}$.
$\mathcal B$ is the $\sigma$-algebra generated by $\mathcal R$.
Since $\mathcal R \subset \mathcal A$, $\mathcal B \subset \mathcal A$.
Let $\nu'$ be the restriction of $\nu$ on $\mathcal B$.
Then $\mu$ is a measure on $\mathcal R$ and $\nu'$ is an extension of $\mu$.
Define $\lambda: \mathcal B \rightarrow [0, +\infty]$ as follows.
If $E\in \mathcal R$, then define $\lambda(E) = \mu(E)$, otherwise define $\lambda(E) = \infty$.
Then $\lambda$ is a measure on $\mathcal B$ and it is an extension of $\mu$.
Since $\nu'(X) \lt \infty$ and $\lambda(X) = \infty$, $\nu' \neq \lambda$.
This seems to be a counter-example of Wikipedia's theorem above.
Am I mistaken?
Comment: You $\mu$ (i.e. $\nu |_{\mathcal{R}}$) is not $\sigma$ finite. You can not write $X = \bigcup_n E_n$ with $E_n \in \mathcal{R}$, since any $E \in \mathcal{R}$ satisfies $E \subset Y \subsetneq X$.
Comment: @PhoemueX Your definition of $\sigma$-finiteness of a measure is commonly accepted when a measure is defined on an algebra or a $\sigma$-algebra. However, if a measure is defined on a ring or $\sigma$-ring, some authors(for example Halmos) define $\sigma$-finiteness as follows.
When a measure $\mu$ is defined on a ring $R$ on a set $X$, $\mu$ is called a finite measure if $\mu(E)\lt \infty$ for all $E\in R$. It is said to be $\sigma$-finite if every member of $R$ is a countable union of members of finite measure.
Comment: Ok, I did not know that. But at least the source cited in the Wikipedia article (Ash) uses the definition of sigma-finiteness that I mentioned above :)
Comment: @PhoemueX Ash only defines $\sigma$-finiteness of measures that are  defined on algebras. He does not mention $\sigma$-finiteness of measures defined on rings, does he?
Comment: Yes, but that makes the whole Wiki article even more doubtable. They cite Ash for the uniqueness regarding sigma finite measures on rings, while he only coniders 'fields'. I just wanted to mention that on page 19 (which Wiki references) he explicitly gives the definition I mentioned above.
Answer: Seems to me you're right. The version of the theorem I know talks about algebras instead of rings; then your counterexample doesn't work.
Hmm. Of course your $\lambda$ is also typically not going to be $\sigma$-finite. Seems to me another way to fix the theorem is to say that if $\mu$ is $\sigma$-finite then there is a unique $\sigma$-finite extension.


Remove duplicates by prioritising a categorical value

Question: My database has some entries for which a categorical field has been updated and the old value wasn't removed. I want to keep only the entry with the "highest" categorical value, in an order which I define.
Input:
id | degree
=============
1  | Diploma
1  | Bachelors
1  | Masters
2  | Diploma
2  | Bachelors

Output (desired):
id | degree
=============
1  | Masters
2  | Bachelors

I tried using CASE with the "highest" value last in an attempt to overwrite the previous values, but it does not work as intended.
SELECT
    DISTINCT id,
    (CASE
        WHEN id = 'Diploma'   THEN 'Diploma'
        WHEN id = 'Bachelors' THEN 'Bachelors'
        WHEN id = 'Masters'   THEN 'Masters'
    END) as degree
FROM
    academic_record

Is there a method for this operation?
Comment: That's correct. The logic is that I wish to check each case in turn, and if the case is true, then set the value. The next case may overwrite the value. (This may not be optimal, but is sufficient. A better method may simply check all cases before setting the value, without the need to overwrite "superseded" values.)
Comment: Can you explain the logic? Am I right to assume that you meant that  Masters > Bachelors > Diploma?
Answer: Using a case for ordering is the right idea. I'd query the rank over it for each id, and then take the top ones:
SELECT id, degree
FROM   (SELECT id,
               degree,
               RANK() OVER (PARTITION BY id
                            ORDER BY CASE degree WHEN 'Diploma'   THEN 1
                                                 WHEN 'Bachelors' THEN 2
                                                 WHEN 'Masters'   THEN 3
                                     END DESC) AS rn
        FROM   academic_record) t
WHERE rn = 1

Comment: Works beautifully! Thank you.


Named Mercurial branch branched off too late. Start anonymous branch and close head or revert the changes in content but not in structure?

Question: We are currently working on a project to benchmark a program on different architectures. Most of the codebase is identical and an early version runs on all architectures. We discovered some architecture-specific optimizations and branched off one version in a named branch. However, this happened too late.
The commit tree looks like this:
  A
  |
  B
 / \
 C D
 | |
 \ /
  M
 / \
H   \
     P

At commit B, the then-anonymous branches diverged and were merged in commit M. We noticed that optimizations good for one architecture are detrimental for the second one and decided to keep the architecture-specific changes in a name branch with current head P.
D introduced some bugs which break unit tests, this was discovered after merging in M. To continue locally I reverted most of the changes in H and Commits B and H are almost identical.
I am currently at head H and noticed that the changes introduced by B are already optimized for the architecture I'm not working on.
I would now like to continue with the code from commit A, but make it as easy as possible to transplant further algorithmic changes to P. As I see it, the following options exist:

Start anonymous branch at A, close head at H. (cleanest, structure follows content)
Copy files manually from A to H and commit. (Avoids increasing the number of heads, makes updating to the current tip easier)
Start new named branch.

Which option conforms to current best practices? Are there any other options?
Comment: I finally created a new anonymous branch.
Answer: Alternatively you can continue with H and revert (some or all) files to the revision as found in A: hg up H; hg revert -rA FILENAME; hg commit -m "Restore generally useable state for FILENAME"
Or you can backout single changesets: hg up H; hg backout D
However that you now created an anonymous branch based on A is not a bad decision either.


Roots to an equation, $\frac{3-2x}{x-1}-\sqrt[4]{x^3}$

Question:
Find the number of roots to $\frac{3-2x}{x-1}-\sqrt[4]{x^3}=0$.

My method:
$\frac{3-2x}{x-1}-\sqrt[4]{x}$, we multiply $\sqrt[4]{x}$ and $x-1$ to both sides, getting $3\sqrt[4]{x}-2x\sqrt[4]{x}-x(x-1)=0$.  We let $\sqrt[4]{x}=k$.  Then we have $3k-2xk-x^2+x=0$.  Finding the discriminant ($b^2-4ac$), getting $4k^2+8k+1$, evidently greater than $0$, which means there are 2 roots.
Plotting this on Desmos gives 1 root only. How am I wrong?
Answer: Your analysis is wrong becase $k$ depends on $x$: $k=\sqrt[4]x$. Instead, write $x=k^4$:
$$3k-2k^5-k^8+k^4=0$$
$$k^8+2k^5-k^4-3k=0$$
Descartes's rule of signs tells us there is exactly one positive root for this last polynomial. $k$ cannot be negative as it is the fourth root of $x$, so the lone root of the polynomial in $k$ translates to only one root for the original equation.
Comment: @XcoderX It starts out OK, but when you get to $3k-2xk-x^2+x=0$ you need to switch tracks to mine.
Comment: sorry, I do not seem to understand how your method is different
Comment: @XcoderX Only mine explains why your method is wrong, which is what you wanted, right?
Comment: Yes.  But the k=quad root x part and x equal k^4 part seems unclear to me
Comment: @XcoderX _Because_ $k=\sqrt[4]x$, we can take the fourth power of both sides to get $k^4=x$. (This is not always correct, but if $k$ is positive like it is here it is OK.)
Comment: Wait, it is okay?  You mean my solution?
Comment: Ah okay thanks, understand now.
Answer: write your equation in the form
$$(3-2x)=(x-1)\sqrt[4]{x^3}(x-1)$$ for $x\ne 1$ and raise to the power four:
$$(3-2x)^4=x^3(x-1)^4$$
then you have to solve the equation
$$-{x}^{7}+4\,{x}^{6}-6\,{x}^{5}+20\,{x}^{4}-97\,{x}^{3}+216\,{x}^{2}-
216\,x+81
=0$$
Answer: Let $x=t^4$, where $t>0$.
Thus, $$t^7+2t^4-t^3-3=0$$ and we see that there is one changing of coefficients sing.
Thus, the polynomial $t^7+2t^4-t^3-3$ has one positive root by https://en.wikipedia.org/wiki/Descartes%27_rule_of_signs
In your reasoning you need to remember that $k\geq0,$ which gives that your method does not work.
Comment: well, do you know why my method is wrong?
Answer: Since $k$ is a function of $x$, the coefficients of your quadratric equation are functions of $x$.

The quadratic formula is useless in that context, since that would be solving for $x$ in terms of $x$.

Here's how I would approach the problem . . .

Let $f(x)={\displaystyle{{\small{\frac{3-2x}{x-1}}}-\sqrt[4]{x^3}}}$.

You want to count the number of real zeros of $f$.

Rather than trying to solve the equation $f(x) = 0$, instead, analyze the behavior of $f$.

The domain of $f$ is $[0,1)\cup(1,\infty)$.

On the interval $[0,1)$, we have
$$\frac{3-2x}{x-1}<0$$
$$-\sqrt[4]{x^3} \le 0$$
hence $f(x) < 0$.

Thus, $f$ has no real zeros in the interval $[0,1)$.

On the interval $(1,\infty)$, the functions
$$\frac{3-2x}{x-1}$$
$$-\sqrt[4]{x^3}$$
are both strictly decreasing, hence $f$ is strictly decreasing.

It follows that $f$ has at most one real root.

Letting $x$ approach $1$ from the right, we get
\begin{align*}
\lim_{x\to 1^{+}} f(x)
&=\;\lim_{x\to 1^{+}} \frac{3-2x}{x-1}-\sqrt[4]{x^3}\\[4pt]
&=\;\lim_{x\to 1^{+}} \frac{3-2x}{x-1}-\lim_{x\to 1^{+}}\sqrt[4]{x^3}\\[4pt]
&=\;\infty-1\\[4pt]
&=\;\infty\\[4pt]
\end{align*}
Letting $x$ approach $\infty$, we get
\begin{align*}
\lim_{x\to \infty} f(x)
&=\;\lim_{x\to \infty} \frac{3-2x}{x-1}-\sqrt[4]{x^3}\\[4pt]
&=\;\lim_{x\to \infty} \frac{3-2x}{x-1}-\lim_{x\to \infty}\sqrt[4]{x^3}\\[4pt]
&=\;-2-\infty\\[4pt]
&=\;-\infty\\[4pt]
\end{align*}
Since $f$ is continuous on $(1,\infty)$, it follows that $f$ has at least one real root.

Therefore $f$ has exactly one real root.


Erro ao consultar grande quantidade de dados no Entity framework,

Question: Estou montando um relatório, e nele existe a opção de consultar por período de datas. Quando faço a consulta com o intervalo de 30 ou 60 dias, consigo obter os dados, onde agrupo e retorno.
Porém, ao aumentar o período de consulta, o mesmo método retorna o erro de: 500 (Internal Server Error). Pesquisando, notei que em alguns casos o entity framework, encerra a consulta por causa do time out ou pela quantidade de dados a ser processados.
Obs: Essa mesma consulta que fiz pelo entity, realizei diretamente no sql server, passando os parâmetros, para checar se realmente retornaria dados(e retornou como o esperado).
public IQueryable ObterNotaSimplificada(DateTime compInicial, DateTime compFinal,
        PorteContribuinte? codigoPorte, string query, int? itemServico, bool? simplesNacional)
    {
        var res = this.Servicos
            .Include(x => x.Prestador)
            .Where(a => (a.Competencia >= compInicial && a.Competencia <= compFinal) &&
                        (codigoPorte == null || a.Prestador.Porte.Value == codigoPorte) &&
                        (simplesNacional == null || a.Prestador.IsSimplesNacional == simplesNacional) &&
                        (itemServico == null || a.ItemListaServico.Id == itemServico) &&
                        ((query == null || a.Prestador.RazaoSocial.Contains(query))
                         || (a.Prestador.CpfCnpj.Contains(query))))
            .Where(a => a.DataCancelamento == null)
            .GroupBy(a => a.Prestador.CpfCnpj)
            .Select(g => new
            {
                CNPJ = g.Select(x => x.Prestador.CpfCnpj),
                Competencia = g.Select(x => x.Competencia),
                RazaoSocial = g.Select(x => x.Prestador.RazaoSocial),
                SimplesNacional = g.Select(x => x.Prestador.IsSimplesNacional),
                Porte = g.Select(x => x.Prestador.Porte),
                DescricaoPorte = g.Select(x => x.Prestador.Porte.ToString()),
                QtdNotasEmitidas = g.Count(),
                BaseDeCalculo = g.Select(x => x.BaseCalculo),
                ValorDeducoes = g.Select(x => x.ValorDeducoes),
                ValorServicos = g.Select(x => x.ValorServicos),
                ValorIss = g.Select(x => x.ValorInss),
                TotalBaseDeCalculo = g.Sum(x => x.BaseCalculo),
                TotalValorDeducoes = g.Sum(x => x.ValorDeducoes),
                TotalValorServicos = g.Sum(x => x.ValorServicos),
                TotalValorIss = g.Sum(x => x.ValorIss),
                IssRetido = g.Select(x => x.IssRetido > decimal.Zero),
                ItemDeServico = g.Select(x => x.ItemListaServico.Descricao),
                CodItemServico = g.Select(x => x.ItemListaServico.Codigo)
            });
        return  res;
    }

Comment: tem que ver o que é `ItemListaServico` por exemplo... se estiver com lazy dentro de cada registro ele vai executar outro select pra buscar esse objeto... tira o count também, se estiver contando uma coleção dentro de cada objeto...
Answer: Acontece que você está retornando muitos dados, utiliza funções de agrupamento (Group By, Sum) e isso exige muito do entity framework. Quando se trabalha com muitos dados é recomendado utilizar a própria query SQL, pelo fato da perfomance ser melhor.
Tente utilizar esse exemplo, mas adaptando para sua query:
var results = context.Database.SqlQuery<string>("SELECT COLUNAS FROM NOMETABELA").ToArray();

Caso a performance continue ruim, recomendo que crie índices para sua base de dados.


How to pass Trigger type as a payload to "Method: projects.triggers.create " in cloud build

Question: I have written Python Script to create a Trigger in Google Cloud Build. So, I'm able to create it but, for Type it is setting to "None (no builds will be triggered)" and Filter "--"
Python Script
bashCommand = "gcloud auth print-access-token"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
if error:
    print(error)

headers = {
    'Authorization' : 'Bearer '+str(output)[2:-3],
    'Accept' : 'application/json',
    'Content-Type' : 'application/json'
}

cloudbuild = {"build":
                {"source":
                    {"repoSource":
                        {"projectId":"[PROJECT_ID]",
                         "repoName":"[repoName]",
                         "branchName":".*"
                         }
                    }
                },
              "description":"API TRigger for all branch",
              "name":"[TRIGGER NAME]"
              }

data = json.dumps(cloudbuild)

response = requests.post('https://cloudbuild.googleapis.com/v1/projects/[PROJECT_ID]/triggers', headers=headers, data=data)
results_output = response.json()
pprint(results_output)

payload
{"build":
                {"source":
                    {"repoSource":
                        {"projectId":"[PROJECT_ID]",
                         "repoName":"[repoName]",
                         "branchName":".*"
                         }
                    }
                },
              "description":"API TRigger for all branch",
              "name":"[TRIGGER NAME]"
              }

I have to manually go to the Cloud Build trigger console and set it there.
Can anyone suggest me how to set TYPE and FILTER through the REST API?
Thanks in Advance
Answer: Notice that the feature is still in Beta and might change or have limited support. Add the triggerTemplate field and modify your payload accordingly.
For example if you want to build a trigger on your Google Cloud Platform's project default repository you could do the following changes to your script:
import subprocess
import json
import requests
bashCommand = "gcloud auth print-access-token"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
if error:
    print(error)
headers = {
    'Authorization' : 'Bearer '+str(output)[2:-3],
    'Accept' : 'application/json',
    'Content-Type' : 'application/json'
}
cloudbuild = {
  "name": "[TRIGGER NAME]",
  "description": "[TRIGGER DESCRIPTION]",
  "triggerTemplate": {
    "projectId": "[PROJECT_ID]",
    "repoName": "gcr.io/[PROJECT_ID]/default",
    "branchName": ".*"
  },
  "build": {
    "source": {
      "repoSource": {
        "projectId": "[PROJECT_ID]",
        "repoName": "gcr.io/[PROJECT_ID]/default",
        "branchName": ".*"
      }
    }
  }
}
data = json.dumps(cloudbuild)
response = requests.post('https://cloudbuild.googleapis.com/v1/projects/[PROJECT_ID]/triggers', headers=headers, data=data)
results_output = response.json()
print(results_output)

Comment: ```"triggerTemplate": {
      "projectId": "[projectID]",
      "repoName": repoName,
      "branchName": ".*"
    }```
Comment: Added triggerTemplate things now its working perfectly fine

How to pass Trigger type as a payload to “Method: projects.triggers.create " in cloud build


Use mod_macro with environment variable

Question: Is it possible to use a macro with the value of a environment variable?
E.g.
<Macro setLog $name>
  CustomLog "|cronolog -l /var/www/logs/$name/access.log /var/www/logs/$name/%Y-%m-%d_access.log" logging
  ErrorLog "|cronolog -l /var/www/logs/$name/error.log /var/www/logs/$name/%Y-%m-%d_error.log"
</Macro>

SetEnvIf Host soup* path=soup

use setLog path

Which would 'print' the macro with path. Can I use the value for path? (in this case soup)
Answer: No, the internal variables modified by SetEnv and SetEnvIf are during request processing. Your macros are expanded when the configuration is parsed -- the logs are also opened up front and can't depend on parameters of the request.
Comment: As a clarification to the ambiguous term "*environment variable*" in the question's current version ("*Is it possible to use a macro with the value of a **environment variable**?*"): *Operating system process* environment variables, such as *Debian Apache*'s `${APACHE_LOG_DIR}`, can be used in *mod_macro* macros. ( https://salsa.debian.org/apache-team/apache2/-/blob/debian/2.4.56-1_deb11u2/debian/config-dir/envvars#L23 ... https://httpd.apache.org/docs/2.4/env.html )

Use mod_macro with environment variable


What does a red icon next to a field mean in Taleo Connect Client?

Question: While selecting fields for a Candidate Import in Taleo Connect Client, I noticed a small red icon next to a few of the fields. (IE: EmailAddressValidated, Applications,Number)

What does the red sign icon next to a field mean in Taleo Connect Client?
Answer: A red circle means this field's properties cannot be changed via Taleo Connect Client.

There are several import field types:

Search or lookup fields are identified with a magnifying glass icon.
Key fields are identified with an orange key icon (visible after checking Use the value for search or lookup).
Non updatable fields are identified with a red circle icon.
User defined fields (UDFs) are identified with a person icon.

Taleo Enterprise Connect Client User Guide v17.2 (Page 33)

Important Note: While you can't update the field's properties, you can update the value of this field with a TCC import.


PHP - Doctrine Store File (Binary in Database)

Question: I'm looking for an example of how to store files in the database with doctrine.
Unfortunately i cannot find much information online.
I thought of a schema like:
file: id, fileName, fileExt, fileSize, fileMime, modifiedAt, createdAt
fileData: id, file_id, binaryData, modifiedAt, createdAt
Could someone give me an entity example with a function to store/retrieve files?
Thanks in advance!
Answer: There are at least two ways.

Using Form Events
Using lifecycle callbacks

In both cases the main point is to open uploaded and fill its content to the entity property (after form posted but before data persisted to db). So you need to have 2 entity properties for this: uploaded file handler (not mapped to the db) and file text itself (mapped to the db).
Here is an example with the lifecycle callbacks:
Entity:
<code>/**
 * @ORM\Entity()
 * @ORM\HasLifecycleCallbacks
 */
class SomeEntity {

    /**
     * Virtual field used for handling the file
     *
     * @Assert\File()
     */
    private $fileHandler;

    /**
     * @var string
     *
     * @ORM\Column(type="text")
     */
    private $file;

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function saveFileContent()
    {
        $tmpName = md5(uniqid(mt_rand(), true)) . '.' . $this->fileHandler->guessExtension();
        try
        {
            $this->fileHandler->move(
                '../../../tmp/',
                $tmpName
            );
        } catch (\Exception $e) {}

        $this->setFile(file_get_contents('../../../tmp/' . $tmpName));
        unlink('../../../tmp/' . $tmpName);
    }
}
</code>
This also might be helpfull: How to handle File Uploads with Doctrine


how to find index path within UITableView when a custom button is pressed

Question: I have a tableview of which each cell has a custom button.  I have this method which tells me the index path where the button was located.  The method below works fantastic in iOS 6, but I am not sure how to get the same result in iOS 5 since indexPathForItem is only available in iOS 6.0 and later.
- (IBAction) checkUncheck:(id)sender
{
    UIButton *sendingButton = (UIButton *) sender;
    UITableViewCell *cell =  (UITableViewCell *)[[sendingButton superview] superview];
    PDFFile *newPDF = [_pdfDocument.pdfFileList objectAtIndex: cell.tag];
    [newPDF setCheck: [NSNumber numberWithBool: ![newPDF.check boolValue]]];

    NSIndexPath *path = [NSIndexPath indexPathForItem: cell.tag inSection: 0];

    [_table reloadRowsAtIndexPaths:[NSArray arrayWithObjects: path, nil] withRowAnimation: UITableViewRowAnimationAutomatic];
}

Comment: I think the actual answer is here: http://stackoverflow.com/a/16270198/365188
Comment: possible duplicate of [Getting row of UITableView cell on button press](http://stackoverflow.com/questions/7504421/getting-row-of-uitableview-cell-on-button-press)
Answer: There are 3 methods to find NSIndexPath in TableView
- (NSIndexPath *)indexPathForRowAtPoint:(CGPoint)point;                         // returns nil if point is outside table
- (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell;                      // returns nil if cell is not visible
- (NSArray *)indexPathsForRowsInRect:(CGRect)rect;                              // returns nil if rect not valid

You use indexPathForItem is not good method, try
NSIndexPath *path = [self.tableView indexPathForCell:cell] ;

Comment: Replacing this:
NSIndexPath *path = [NSIndexPath indexPathForItem: cell.tag inSection: 0];

With this:
NSIndexPath *path = [_table indexPathForCell: cell];
worked for me!
Answer: Use a custom UITableViewCell subclass. When you configure your (hopefully reused) cell in -tableView:cellForRowAtIndexPath:, pass the index path (row and section) to the newly configured cell (i.e., each cell 'knows' its current index path).
Next, make the custom button notify the parent cell when tapped through the usual target-action mechanism. When the button is tapped, have the cell broadcast a notification with itself as the object property. Your table view controller can listen to this notification, extract the cell from it and the index path from the cell.
e.g., in the custom table cell implementation (MyTableViewCell.m):
- (void) didTapButton:(id) sender

{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"UserTappedCellButton" object:self];
}

in the view controller:
- (id) init
{
    if(self = [super init]){
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(didTapCellButton:)
                                                     name:@"UserTappedCellButton"
                                                   object:nil];
    }
    return self;
}

- (void) didTapCellButton:(NSNotifcation*) notification
{
   MyCustomTableViewCell* cell = (MyCustomTableViewCell*)[notification object];

   NSIndexPath* path = [cell path]; // <-- You must define this property

   // Use index path...
}

Perhaps there's a simpler/smarter way, but this one is pretty straightforward and comes to mind first...


GLM tests involving deviance and likelihood ratios

Question: I'm a little confused about the different common tests for GLMs.
There is the null deviance, which is similar to a likelihood ratio for the difference between the saturated model and the model with only an intercept.
There is the residual deviance, which is similar to a likelihood ratio for the difference between the saturated model and the current fitted model.
Given these,

It seems to me that you can use the difference in residual and null deviance, which should follow a Chi-square distribution, to give something analogous to the F-test in regression, is this correct?

You can test the residual deviance itself, as it allows you to determine goodness of fit?

I'm assuming there is no test involving the null deviance alone

Unrelated to deviances, you can do likelihood ratio tests comparing for example a model with all parameters and a model lacking one of them?

R just outputs the null deviance and the residual deviance along with their degrees of freedom, so I assume the point is that you can use them to do the tests mentioned above.
If someone can elaborate (on a basic level) I would really appreciate it, because I'm really getting confused as to what the GLM tests make use of in terms of deviance etc.. And if I missed any tests please let me know as well.
Answer: The confusion probably comes from the fact that there are three models involved, and the term "deviance" refers to twice the log or the likelihood ratio between two of them.
The models are:

Null model (usually a model with only an intercept term, no influence of explanatory variables on response),
GLM of interest, modelling the response by a linear combination of the explanatory variables (connected by the link function), and
saturated model, in which the expected value of the response can freely depend on the values taken by the explanatory variables.

The residual deviance $D$ is defined as twice the log of the likelihood ratio between the saturated model and the GLM. The null deviance $D_0$ is twice the log of the likelihood ratio between the saturated model and the null model. From this it follows that $D-D_0$ is twice the log of the likelihood ratio between the GLM and the null model, and in fact you can compare any two models of different complexity nested in each other (i.e., where all parameters/explanatory variables of the less complex model also occur in the more complex model) by using the difference of their deviances (note that the log of the likelihood ratio is in fact a difference between log-likelihoods, and this means that if you compute a difference between deviances, the terms belonging to the saturated model cancel out).
All these statistics as logs of likelihood ratios are $\chi^2$-distributed under standard assumptions, with degrees of freedom as the difference between the numbers of parameters of the involved models.
To your questions:

Yes, this tests the null hypothesis that there is no influence of the explanatory variables at all.
Yes, this compares the fitted GLM with the saturated model (i.e., a model that is maximally flexible to fit the response from the explanatory variables).
In principle you could have such a test, but this doesn't involve the GLM to be fitted, and is therefore not normally of interest when fitting a GLM, and therefore not usually taught (I wouldn't say that this is never of interest; it may well, in exceptional situations).
The deviance is a log of the likelihood ratio, therefore tests based on deviances are in fact likelihood ratio tests, and all such likelihood ratio tests can be written as tests using the difference of deviances for different models (see above).


java Converting mp3 to wav 16 bit mono

Question: I'm struggling alot with converting mp3 to wav and changing the format so it's 16 bit. I have a program that downloads a mp3 file from google translate's text-to-speech which is mono, 16000Hz, 32 bit. The only thing that needs change is 32 bit -> 16 bit. I have searched alot but I think I'm just a bit noob and I'm always doing something wrong. I'm searching for the right java article but I used the wrong one and couldn't convert it.
Comment: I have looked into mp3spi xhich will probably work for me but the platform I'm currently trying to get y working on makes it really hard to add external jars. But the creator told me they are adding support for eclipse claspah creating.
Comment: _I have a program_ We can help you more if you show us the essential parts.
Comment: Check [this](http://stackoverflow.com/questions/12586949/how-can-i-convert-a-wav-file-in-java) and [this](http://stackoverflow.com/questions/10515174/conversion-of-audio-format).
Answer: Java doesn't support MP3 without additional librarys.
List of supported formats: JMF 2.1.1 - Supported Formats
However, to convert the bitrate between two .wav files, you can use javax.sound.sampled:
<code>import javax.sound.sampled.*;

public void changeBitrate(File source,File output){
  AudioFormat format=new AudioFormat(44100,16,1,true,true);
  AudioInputStream in=AudioSystem.getAudioInputStream(source);
  AudioInputStream convert=AudioSystem.getAudioInputStream(format,in);
  AudioSystem.write(convert,AudioFileFormat.Type.WAVE,output);
}
</code>

java Converting mp3 to wav 16 bit mono


A property of "function amplitude."

Question: Let $P=[a_1,b_1]\times\cdots\times[a_n,b_n]$ be a rectangle, $x\in P.$

Definition Let $f:P\to \mathbb{R}$ be a bounded function,then define the amplitude of function $f$ at the point $x$ as
  $$\omega_f(x):=\lim_{r\to 0+}\sup\left\{|f(x_1)-f(x_2)|:\ x_1,x_2\in B(x,r)\cap P\right\}.$$
  Here $B(x,r)$ represents the open ball centered at point $x$ with a radius of $r.$

If we define the function
$$B:P\to \mathbb{R},\ x\mapsto \lim_{r\to 0+}\sup_{a\in B(x,r)\cap P} f(a),$$
and function
$$A:P\to \mathbb{R},\ x\mapsto \lim_{r\to 0+}\inf_{a\in B(x,r)\cap P} f(a),$$
then we can see $$\omega_f(x)=B(x)-A(x),\ \forall\ x\in P.$$
So each interval $[A(x),B(x)]$ corresponds to the amplitude of function $f$ at the point $x$.
Define the Supremum and infimum of function $f$ as
 $$m:=\inf_{x\in P} f(x),\ M:=\sup_{x\in P} f(x),$$
then I can guess that there is
$$[m,M]\subset\bigcup_{x\in P} [A(x),B(x)].$$
In fact, I'm planning to use this conclusion to prove a theorem about Riemann integral($f$ is Riemann-integrable iff the region under its graph is Jordan-measurable),but I meet great difficulties in proving this conclusion, since I don't have enough analytical techniques.
Question: Prove that $$[m,M]\subset\bigcup_{x\in P} [A(x),B(x)].$$
Any hint is also welcomed.
Answer: I. Show $[m,M] \supset \cup_x [A(x),B(x)]$
Take any $y\in \cup_x [A(x),B(x)]$. Then it must be in $[A(x),B(x)]$ for some $x$.
Hence, for any $y\in\cup_x [A(x),B(x)]$, there is an $x$ such that:
$$\inf_x f(x)\leq \lim_{r\rightarrow0}\inf_{z\in B_r(x)} f(z)\leq y \leq \lim_{r\rightarrow0}\sup_{z\in B_r(x)} f(z) \leq \sup_x f(x).$$
Thus $y\in[m,M]$.
So we have that  $[m,M] \supset \cup_x [A(x),B(x)].$
II. Show $[m,M] \subset \cup_x [A(x),B(x)]$
Assume that $y\in[m,M]$ and the contrary that $\forall x$ either $y<A(x)$ or $B(x)<y$. So we can partition $P$ into two subsets $X_a$ and $X_b$ where $y<A(x)$ for $x\in X_a$ and $B(x)<y$ for $x\in X_b$ with $P=X_a\cup X_b$.
We have that $m=\min\{ \inf_{X_a}f, \inf_{X_b} f \}$ and $M=\max\{ \sup_{X_a}f, \sup_{X_b} f \}$.
Assuming that neither $X_a$ nor $X_b$ is empty, we get that
$$m=\inf_{X_b}f\leq\sup_{X_b}f<y<\inf_{X_a}f \leq\sup_{X_a}f =M$$
But $P$ is connected so we can find $z\in\overline{X}_b\cap X_b$ (without loss of generality) such that $B_r(z)\cap X_a \neq \emptyset$ and $B_r(z)\cap X_b \neq \emptyset$ for all $r$. I.e. one of the partition sets contains a point on its "inner boundary" with the other partition set. This implies that $A(z)\leq \sup_{X_b} f$ and that $\inf_{X_a} f \leq B(z)$.
So we conclude that $y\in[A(z), B(z)]$ which is a contradiction.
If either $X_a$ or $X_b$ is empty, then the result changes slightly. I'll assume $X_a=\emptyset$ without loss of generality.
$$M=\sup_{X_b}f<y$$
Thus $y\notin [m,M]$, a contradiction.
The conclusion is that $[m,M] = \cup_x [A(x),B(x)]$.
Comment: Well, today I've also thought of that, and have obtained a proof using the connectedness of  rectangle. In fact, $P$ could be any connected space, and the conclusion is still correct. Form the connectness of $P$ we can conclude that $\overline{X_a}\cap\overline{X_b}\neq \emptyset.$ Choose a point $x_0$ from this intersection, then we can prove that $y\in [A_{x_0},B_{x_0}],$ which completes the proof.
Comment: Emmmm,since $m=\min\left\{\inf_{X_a} f,\inf_{X_b} f\right\},$ I think that$$y<\inf_{X_a} f \ \text{and}\  y\geqslant \inf_{X_b} f \nRightarrow y<m.$$
Comment: Ya, it's definitely contradictory, which is what we want, but not sure if it's good enough. The argument might be able to be cleaned up, but maybe wholly faulty. I'll think about it.
Comment: I think this argument can be repaired by using the connectedness of $\mathbb R^n$. Or maybe the entire argument can be discarded and just use connectedness more directly.
Comment: Yep, that's it. I'll edit my answer later, but it sounds like you are good to go now.
Comment: @jods: I find that the present proof is still incomplete. In fact, we need to ensure that $X_a\neq \emptyset\ \text{and}\  X_b\neq \emptyset,$ which is a essential  detail. If we assume that $y\in (m,M),$  we can see that this is true, so the present proof still work, but can only prove that $$\bigcup_{x\in P} [A(x),B(x)]\supset (m,M).$$
Comment: And using the compactness of $P$ we can prove that
Comment: $\left\{m,M\right\}\subset \bigcup_{x\in P} [A(x),B(x)].$ In fact, we can see $A$ is lower semicontinuous, and $B$  is upper semicontinuous. And there's a theorem saying that **If C is a compact space (for instance a closed, bounded interval [a, b]) and f : C → \mathbb{R} is upper semi-continuous, then f has a maximum on C, and if f : C → \mathbb{R} is lower semi-continuous, then f has a minimum on C.** So when $P$ is compact we have $\left\{m,M\right\}\subset \bigcup_{x\in P} [A(x),B(x)].$
Comment: @painday, That probably works too, but I am not as familiar with semi-continuity. I don't see how the result follows immediately without a little more explanation. I'll think about it. You could consider writing up and posting your solution using semicontinuity and compactness. I think having multiple solutions is good. It's generally ok to post an answer for your own question too.

If $X_a$ or $X_b$ is empty, then it does change my argument slightly, and I will fix that now.
Comment: :OK, I'll write my solution tomorrow :).
Answer: Inspired by @jdods, finally I obtain the following theorem:

Theorem: Let $(P,\mathcal{T})$ be a connected topology space, and $f:P\to \mathbb{R}$  be a bounded function, define
  $$m:=\inf_{x\in P} f(x),\ M:=\sup_{x\in P} f(x),$$
  and define functions
  $$A:P\to \mathbb{R},\ x\mapsto \sup_{\text{$U$ is a open neighborhood of $x$}} \big[\inf_{a\in U} f(a)\big],$$
  $$B:P\to \mathbb{R},\ x\mapsto \inf_{\text{$U$ is a open neighborhood of $x$}} \big[\sup_{a\in U} f(a)\big],$$
  then we have
  $$(m,M)\subset\bigcup_{x\in P} [A(x),B(x)]\subset [m,M].\ (*)$$
  And if topology space $(P,\mathcal{T})$ is also compact, then we have
  $$\bigcup_{x\in P} [A(x),B(x)]=[m,M].\ (**)$$

Proof of $(*)$: It's obvious that $\bigcup_{x\in P} [A(x),B(x)]\subset [m,M].$
Let's prove that $(m,M)\subset \bigcup_{x\in P} [A(x),B(x)].$
For arbitrary $y\in (m,M),$ if we suppose that $y\notin \displaystyle\bigcup_{x\in D}[A(x),B(x)],$
then we have $$y\in (-\infty,A(x)]\cup[B(x),+\infty),\ \forall\ x\in X.$$
Define sets $$X_a:=\left\{x\in X| y< A(x)\right\},\ X_b:=\left\{x\in X| y> B(x)\right\},$$
then $P=X_a\cup X_b.$ Let's prove that $X_a,X_b\neq \emptyset.$
In fact, if $X_a=\emptyset,$ then $P=X_{b},$ thus $y\geqslant B(x),\ \forall\ x\in P.$
But $$B(x)\geqslant f(x),\ \forall\ x\in X,$$
thus $y\geqslant f(x),\ \forall\ x\in X,$ so $y\geqslant M,$ which is a contradiction.
Now we see that $X_a\neq \emptyset,$ and similarly we can prove $X_b\neq \emptyset.$
Since $X_a\cup X_b=X,$ and $X_a, X_b\neq \emptyset,$ thus we have $\overline{X_a},\overline{X_b}\neq \emptyset,$ and $\overline{X_a}\cup \overline{X_b}=X.$ From the connectness of $P$ we infer that $\overline{X_a}\cap \overline{X_b}\neq \emptyset.$
Take $x_0\in \overline{X_a}\cap \overline{X_b},$ and assume that $U$ is an open neighborhood of $x_0,$ then we have $(U\cap \overline{X_a})\neq \emptyset,\ (U\cap \overline{X_b})\neq \emptyset.$ Take $x_1\in (U\cap \overline{X_a}),\ x_2\in (U\cap \overline{X_b}),$ then $U$ is  an open neighborhood of  both $x_1$ and $x_2.$ Thus
$$\inf_{a\in U} f(a)\leqslant A(x_2),\ B(x_1)\leqslant \sup_{a\in U} f(a).$$
Notice that $$A(x_2)\leqslant B(x_2)< y<A(x_1)\leqslant B(x_1),$$
we have
$$\inf_{a\in U} f(a)<y<\sup_{a\in U} f(a). $$
From the arbitrariness of $U$ we infer that
$$A(x_0)\leqslant y\leqslant B(x_0),$$
which is a contradiction.
So now we've proved that
$$(m,M)\subset\bigcup_{x\in P} [A(x),B(x)]\subset [m,M].\ (*)$$
To prove $(**)$,the second part of the theorem, we need to prove some useful propositions first:

Definition 1:Let $X$ be a topology space,,$x_0\in X,$ $f:X\to \mathbb{R}$ be a real-valued function. If  $\forall\ \varepsilon>0,$  $\ \exists $ an open neighborhood of $x_0$,denoted as $U,$ such that
  $$f(x)<f(x_0)+\varepsilon,\ \forall\ x\in U,$$
   then we say function $f:X\to \mathbb{R}$ is upper semi-continuous at point $x_0$. If function $f$ is  upper semi-continuous  at every point in $X$ , then we say  $f$ is upper semi-continuous function.

Similarly, If  $\forall\ \varepsilon>0,$  $\ \exists $ an open neighborhood of $x_0$,denoted as $U,$ such that
$$f(x)>f(x_0)-\varepsilon,\ \forall\ x\in U,$$
 then we say function $f:X\to \mathbb{R}$ is lower semi-continuous at point $x_0$. If function $f$ is  lower semi-continuous  at every point in $X$ , then we say  $f$ is lower semi-continuous function.
We can see that if both $f$ and $g$ are upper semi-continuous, then function $f+g,$ is also upper semi-continuous, function $-f$ is lower semi-continuous.  And if  upper semi-continuousfunction $f$ is always negative on $X$ or always positive on $X,$ then function $1\over{f}$ is lower semi-continuous.
Now we define a set as
$$T:=\left\{(-\infty,a)|\ a\in \mathbb{R}\right\}\cup \left\{\mathbb{R}\right\}\cup \left\{\emptyset\right\},$$
then we can see $T$  is a topology on $\mathbb{R},$ and the following definition is equivalent to definition 1:

Definition 2: Let $X$ be a topology space, $x_0\in X,$ $f:X\to \mathbb{R}$ be a real-valued function. If map $f:X\to (\mathbb{R},T)$ is continuous at point $x_0,$ then we say function $f:X\to \mathbb{R}$ is upper semi-continuous at point $x_0$. If map $f:X\to (\mathbb{R},T)$ is continuous , then we say function $f:X\to \mathbb{R}$ is upper semi-continuous.

The following lemma is important:
Lemma: If topological space $(X,\mathcal{T})$ is compact, and function $f:X\to \mathbb{R}$ is upper semi-continuous, then $f$ is bounded above, and $f$ has a maximum on $X.$
Proof:
  Define set
$$X_n:=\left\{x\in X|\ f(x)<n\right\},$$
here $n\in \mathbb{N},$ then  $X=\displaystyle\bigcup_{n\in \mathbb{N}} X_n,$  and according to Definition 2,  $X_{n}$ is open set in $X.$ From the compactness of $X$ we can see there exist $n_1,\cdots,n_k,$ such that
$$X=\bigcup_{i=1}^k X_{n_i}.$$ Let
$M'=\displaystyle\max\left\{n_1,\cdots,n_k\right\},$
then $X=X_{M'},$ thus $f(x)<M',\ \forall\ x\in X,$ so $f$ is bounded above.
Now let's prove that if upper semi-continuous function $f$ is bounded above, then $f$ has a maximum $X$.
In fact, suppose that $f$ has no maximum, then define $K:=\sup_{x\in X} f(x),$
we can see function $g:={1\over{K-f}}:X\to \mathbb{R}$ is upper semi-continuous, thus $g$ is bounded above. Let $M$ be a upper bound of $g$, then $$g(x)={1\over{K-f(x)}}\leqslant M,\ \forall\ x\in X.$$ Notice that $g(x)>0,\ \forall\ x\in X,$ so $M>0,$ thus
$$K-f(x)\geqslant {1\over{M}},\ \forall\ x\in X,$$
i.e.
$$f(x)\leqslant K-{1\over{M}},\ \forall\ x\in X,$$
which is a contradiction. Q.E.D
Similarly,If topological space $(X,\mathcal{T})$ is compact, and function $f:X\to \mathbb{R}$ is lower semi-continuous, then $f$ is bounded below, and $f$ has a minimum on $X.$
Now let's complete the proof of the theorem:
Proof of $(**)$: First we'll prove that function $B(x)$ is upper semi-continuous, and function $A(x)$ is lower semi-continuous.
In fact, according to the definition of $B(x),$ for any $\varepsilon>0,$ there exists  an open neighborhood of $x,$ such that
$$\sup_{a\in U} f(a)<B(x)+\varepsilon.$$
Then assume that $t\in U,$ then $U$ is also an
open neighborhood of $t,$ so
$$B(t)\leqslant \sup_{a\in U} f(a).$$
Now we see that
$$B(t)<B(x)+\varepsilon,\ \forall\ t\in U.$$
Thus function $B(x)$ is upper semi-continuous.
Similarly we can prove that function $A(x)$ is lower semi-continuous.
Now notice that
$$\sup_{x\in P} B(x)=M, \ \inf_{x\in P} A(x)=m,$$ and since $P$ is compact,
according to the lemma we have
$$m\in \bigcup_{x\in P} \left\{A(x)\right\},\ M\in \bigcup_{x\in P} \left\{B(x)\right\}.$$
Q.E.D

A property of "function amplitude."


Uncaught TypeError: undefined is not a function while creating a subview using backbone

Question: I am creating a subView which is rendered from the mainview - FindRideView.
renderRide: function (item) {
        var RideView = new RideView({model: item}); // here
    this.$el.append(RideView.render().el);
    }

However when i render the view, i get a Uncaught TypeError: undefined is not a function //here
My app structure is
 var RideView = Backbone.View.extend({});
 var FindRideView = Backbone.View.extend({
    renderRide:
    });

I checked with the RideView for any errors. But its working completely fine when not called from the FindRideView. I guess there might be some scope issue, but i am not sure about it.
Would appreciate some help.
Comment: Try naming your instance something other than `RideView` since that is the exact same as your constructor.
Comment: Your code seems fine, can you try to recreate your problem in a JSFiddle?
Comment: nialed it!! haha!
renaming it to something else did the trick :)
thanks
Answer: Try defining "RideView" outside of the function. See this for a scoping example:
http://jsfiddle.net/54DRC/3/
var mynum;
mynum = 1;
function DontSetMyNum() {
    var mynum;
    mynum = 2;
}
function SetMyNum() {
    mynum = 3;
}
$(function() {
    $("body").append("
Initial = " + mynum + "
");
    DontSetMyNum();
    $("body").append("
After DontSetMyNum call = " + mynum + "
");
    SetMyNum();
    $("body").append("
After SetMyNum call = " + mynum + "
");
});


Calculate the sum of the digits of the first 100 numbers of that sequence which are divisible by 202.

Question: In the sequence 20, 202, 2020, 20202, 202020, ... each subsequent number is obtained by adding the digit 2 or 0 to the previous number, alternately. Calculate the sum of the digits of the first 100 numbers of that sequence which are divisible by 202.
my attempt:
¿. Given sequence:
$20,202,2020,20202, \cdots$
let $n$ be the number of elements of the sequence in the first 100 numbers which ahe divisible by 202. Looking at the pattern, the first number of the sequence, divisible by 202, is 202 with digital root = 4,  the second number of the sequence, divisible by 202, is 2020202 with digital roof $=8$ the third number of the sequence, by 202, is 20202020202 with digital root $=12$ and so on.
Comment: 2020 is also divisible by 202, isn't it?
Comment: *note :* $a_n=\lfloor\frac{2\cdot10^n}{99}\rfloor$
Answer: Note that $n=\sum_{k=0}^r c_k\cdot 100^k$ is divisible by $101$ if and only if
$$n=\sum_{k=0}^r c_k\cdot 100^k\equiv \sum_{k=0}^rc_k(-1)^k\equiv 0 \pmod{101}.$$
In other words, given a number $n$ take the digits in pairs from the right and alternately add and subtract them. The number $n$ is divisible by $101$ if and only if the result is zero modulo $101$ (it reminds the divisibility rule for $11$)
Therefore in your sequence, a number is divisible by $202=2\cdot 101$ iff the number of its digits is $0\pmod 4$ or $3\pmod 4$:
$$202,2020,2020202,20202020,20202020202,202020202020\dots$$
So the sum of the digits of the first 100 numbers of that sequence which are divisible by $202$ is
$$4\cdot(1+1+2+2+3+3+\dots+50+50)$$
What is the final answer?
Answer: Divide it into two questions.

is the any obvious patterns two which of the numbers are divisible by $202$ and which are not?

Given the pattern in the answer to 1) is the any obvious way to calculate the some of digits?

Answer to 1) Clearly if there are any even number of $2$ so the number is
$N=\underbrace{202}0\underbrace{202}0\underbrace{202}0\underbrace{202}0....0\underbrace{202}$ then $N = 202\times 100010001......0001$ and is divisible by $202$.
And if there are an odd number of twos then
$N =\underbrace{202}0\underbrace{202}0\underbrace{202}0\underbrace{202}0....0\underbrace{202}02$ will have a remainder of $2$ and will not be divisible by $202$.
Answer to 2) So a number is divisible by $202$ if it has an even $2k$ number of digits.  The first $100$ such numbers are then numbers that start with $2\times 1 = 2$ digits of $2$ and end with the number that has $2\times 100 = 200$ digits of $2$.
The $k$th number will have $2k$ twos in it and the sum of the $k$th number will by $2\times (2k) = 4k$.  And so the sum of all $100$ if the numbers from $k=1$ to $k=100$ that is
$SUM = \sum_{k=1}^{100}4k$
And that is equal to $4\sum_{k=1}^{100}k$.
Now EVERY mathematician is secretly jealous and resentful of that snot-nosed little 5-year old Gauss[1] (although most won't admit it) and every mathematician knows $\sum_{k=1}^{100}k = \frac {100\times 101}2 = 5050$.
So $SUM = 4\times 5050 = 20200$.
=====
[1] who gets younger and younger with each retelling of the stupid annoying story.....[2]
[2] In case you don't know it, Gauss' tutor gave him a busy work assignment to add up all the numbers from $1$ to $100$.  "That'll keep the little brat quiet for a while" the tutor thought.  And between 5 minutes or 45 seconds (the time gets shorter with each telling too) the precocious little tyke came up with the answer $5050$.
The tutor said "How in the world..." and the kid said  "I lined up all the numbers from $1$ to $100$ going up, and added them to all the numbers $100$ to $1$ going down so each pair added to $101$ and I had $100$ of them so I divided that in half and got  $5050$".
Comment: I am afraid your solution may not be true. Please check.
Answer: If you take the first eight numbers you will get this:
$$20
\\202
\\2020
\\20202
\\202020
\\2020202
\\20202020
\\202020202$$
As you can see, for each stack of $4$, only the second and third are divisible by $202$. For the first stack, the sum is $202+2020=2222$, for the second stack $2020202+20202020=22222222$. We find a pattern: the sum of the digits of the first stack is $8$, the sum of the digits of the second stack is $16$. Since we are adding either $0$ or $2$ to the end of the numbers, this will continue the sum of the stack as $8,16,24,...$
We are going to have $25$ stacks. So, we created an arithmetic sequence where $a_1=8, d=8$, and we need to find $S_{25}$. Since $S_n=\frac{n(2a_1+(n-1)d)}{2}$, we will have the following sum:
$S_{25}=\frac{25(2\cdot8+(25-1)8)}{2}=2600$
Answer: Step 1:
To solve this question, let us try to get the first 20 numbers in the series: They are listed below
$1^{st}$ number: 20
$2^{nd}$ number: 202
$3^{rd}$ number: 2020
$4^{th}$ number: 20202
$5^{th}$ number: 202020
$6^{th}$ number: 2020202
$7^{th}$ number: 20202020
$8^{th}$ number: 202020202
$9^{th}$ number: 2020202020
$10^{th}$ number: 20202020202
$11^{th}$ number: 202020202020
$12^{th}$ number: 2020202020202
$13^{th}$ number: 20202020202020
$14^{th}$ number: 202020202020202
$15^{th}$ number: 2020202020202020
$16^{th}$ number: 20202020202020202
$17^{th}$ number: 202020202020202020
$18^{th}$ number: 2020202020202020202
$19^{th}$ number: 20202020202020202020
$20^{th}$ number: 202020202020202020202
Step 2:
By Observation, we can easily say that all odd orders (i.e. $3^{rd}$, $5^{th}$ e.t.c.) of numbers end with 0 while even orders end with 2. Our next aim is to discover the numbers that are divisible by 202. It is easy to see that the $2^{nd}$ and $3^{rd}$ orders are divisible by 202. The next in line again is $6^{th}$ and $7^{th}$ followed by $10^{th}$ and $11^{th}$, $14^{th}$ and $15^{th}$, $18^{th}$ and $19^{th}$.
Step 3:
Let us list them out
$2^{nd}$ $\Rightarrow$ 202
$3^{rd}$ $\Rightarrow$ 2020
$6^{th}$ $\Rightarrow$ 2020202
$7^{th}$ $\Rightarrow$ 20202020
$10^{th}$ $\Rightarrow$ 20202020202
$11^{th}$ $\Rightarrow$ 202020202020
$14^{th}$ $\Rightarrow$ 202020202020202
$15^{th}$ $\Rightarrow$ 2020202020202020
$18^{th}$ $\Rightarrow$ 2020202020202020202
$19^{th}$ $\Rightarrow$ 20202020202020202020
Step 4:
Let us get the sum of the digits in each these numbers (since they are divisible by 202 which is what we need). We would ignore 0 because it will not affect our result
$2^{nd}$ $\Rightarrow$ 202 adds up to 2+ 2 = 4
$3^{rd}$ $\Rightarrow$ 2020 adds up to 2+ 2 = 4
$6^{th}$ $\Rightarrow$ 2020202 adds up to 2+ 2 + 2+ 2= 8
$7^{th}$ $\Rightarrow$ 20202020 adds up to 2+ 2 + 2+ 2= 8
$10^{th}$ $\Rightarrow$ 20202020202 adds up to 2+ 2 + 2+ 2 + 2 + 2= 12
$11^{th}$ $\Rightarrow$ 202020202020 adds up to 2+ 2 + 2+ 2 + 2 + 2= 12
$14^{th}$ $\Rightarrow$ 202020202020202 adds up to 2+ 2 + 2+ 2 + 2 + 2 + 2 +
2= 16
$15^{th}$ $\Rightarrow$ 2020202020202020 adds up to 2+ 2 + 2+ 2 + 2 + 2 + 2 + 2= 16
$18^{th}$ $\Rightarrow$ 2020202020202020202 adds up to 2+ 2 + 2+ 2 + 2 + 2 + 2 + 2 + 2 + 2= 20
$19^{th}$ $\Rightarrow$ 20202020202020202020 adds up to 2+ 2 + 2+ 2 + 2 + 2 + 2 + 2 + 2 + 2= 20
Step 5:
Obviously, we agree that the $2^{nd}$ and $3^{rd}$ have the same result. This happens the same way for the rest. Let us add the orders with the same values to get a sequence.
$2^{nd}$ and $3^{rd}$ orders give: 4+4 =8
$6^{th}$ and $7^{th}$ orders give: 8+8 =16
$10^{th}$ and $11^{th}$ orders give: 12+12 =24
$14^{th}$ and $15^{th}$ orders give: 16+16 =32
$18^{th}$ and $19^{th}$ orders give: 20+20 =40
Step 6:
This results in an Arithmetic Progression with 5 terms (A.P.) $\Rightarrow$ 8, 16, 24, 32, 40,.....
The First 20 numbers gave us 5 terms of an (A.P.) corresponding to numbers that are divisible by 202.
$\therefore$ 100 numbers will give us $\frac{100}{20} \cdot 5 = 5 \times 5 = 25$
This Arithmetic Progression will have 25 terms in it. i.e. n = 25.
For any (A.P.): we let a = 1^{st} term, T_2 = Second term and d =  common difference
Also, for an Arithmetic Progression, $d = T_2 - a$ = 16 - 8 =8 ,  a = 8
For and A.P.: Sum of $n(th)$  terms is given as $S_n = \frac{n}{2}[2a+(n-1)d]$
$\therefore$ we substitute the values of n, d and a to  solve for the Sum of the 25 terms.
$\therefore S_n  = S_{25} = \frac{25}{2}[2 \cdot 8+(25-1) \cdot 8] = \frac{25}{2}[ 16+(24) \cdot 8] = \frac{25}{2}[ 16+192] = \frac{25}{2}[ 208] = \frac{25 \cdot 208}{2} =\frac{5200}{2}$ = 2600.
$\therefore$ the sum of the digits of the first 100  numbers of the sequence which are divisible by 202  is
2600
Comment: [mathjax](https://math.meta.stackexchange.com/q/5020/306553) guide.
Comment: Thank you for correcting me.


Error 403 github

Question: Criei um nova conta no GitHub e quando eu tento dar um git push -u origin master ele retorna um erro dizendo que eu não tenho permissão para acessar aquele repositório. Aparece como que se o minha antiga conta tivesse tentando acessar esse repositório. Tentei mudar usando git config user.name "Antonio Matheus" e também com git config user.email "email@example.com". Mas mesmo assim o erro persiste.
O erro aparece assim:

remote: permission to antoniomatheush/pomodoro-timer-site.git denied
  to maggrilmur. fatal: unable to access
  'https://github.com/antoniomatheush/pomodoro-timer-site.git/': The
  requested URL returned error: 403

maggrilmur é o nome de usuário da minha conta antiga no GitHub, antoniomatheush é a que eu criei recentemente.
Answer: O usuário e senha do commit não tem relação com a parte de autenticação no Github.
Provavelmente o Windows está tentando usar suas antigas credenciais. Você pode confirmar isto com o comando:
git config credential.helper

Para alterar isto, você precisa ir no Gerenciador de Credenciais do Windows. Lá, procure por uma entrada parecida com git.https://github.com. Edite ele colocando seu novo usuário Github e senha. Depois disto, tente novamente fazer o push.
Comment: Salvou minha vida, valeu.

Error 403 github


How do i set values based on other values when database opens

Question: I am trying to get the status of my jobs to change automatically when the database opens.
<code>If Me.STATUS = 6 And Me.UPDATED_TIME = Date - 1 Then
    Me.STATUS = 2
Else
End If
</code>
that is my current code however it doesn't seem to be working...
help please!
Comment: Please specify what's working, and what isn't working. This seems to be code that should be ran on a form. That's an unlikely way to update data. You usually use update queries for that.
Comment: That is probably a major issue. I am very new to access and am playing around and had the idea. that whole thing doesnt work. where would i put this code or how would i set it up
Comment: That's a very broad question. You shouldn't use vba for this at all, but an update query. Start by reading in on those
Comment: Thank you, I had ZERO idea! that is perfect!
Answer: as explained by Erik von Asmuth, vba was not the proper way to complete the task I was wanting. Below is the link to where I found the how to on an "Update Query"
https://support.office.com/en-us/article/Create-and-run-an-update-query-9dddc97c-f17d-43f4-a729-35e5ee1e0514


How to set up salt hash while installing Drupal 7?

Question: I am no expert in salt hash but while I was installing Acquia Dev, I noticed a variable <code>$drupal_hash_salt</code>, filled with a randomly generated string, in settings.php of newly installed Drupal 7 and a file called .hashlist under root drupal installation folder. Can someone help me understand the salting concepts in Drupal 7?
When I tried to import a new version of Drupal 7 site, I could not see any random string in that same variable and also no .hashlist file. I may be doing something wrong here. I tried googling around to see if I could find something useful but no luck.
So I have 3 questions

How to do salt hashing in Drupal 7 during/before installation process?
What kinds of data are being hashed (other than password)?
How can I extend this salting concept further?

Thanks a lot in advance.
Answer: I talk a bit about the new salts in my article on Improvements to Security in Drupal 7 which may help answer these questions.
Depending on when you need the salt you might be able to use drupal_get_hash_salt or you may be able to leverage the code it uses to create your hash.
Can you expand on "extend this salting concept" ?  What kind of extension do you want to do?
Salting is a standard part of hashing. You can read about salting on the php hashing pages. Changing your salt after the site is live may cause some problems in specific areas. My guess is that it depends on which modules you have installed and which features you are using. The one-time-login links are likely to stop working, but I'm not sure of other specific functionality that would stop.
Comment: Hi Greggles. First of all, let me take this opportunity to thank you (Drupal Security team leader), for taking time and replying to my query. However while going through your informative article about security I am still in dark on how to exactly use this technology to my benefit. The settings.php file talks about creating a file "salt.txt" and asks to add some contents that will then be used as salt.
Comment: And put that file outside drupal directory with chmod 666? And I have to do this before I install drupal 7? Can I still  do this once I have installed drupal 7? How do I check whether its been salted? (I am sorry I am asking so many questions but seems like there is something wrong with stackexchange editing program, as I cannot edit properly right now)
Comment: I updated that article to describe how to address use that file a bit more and expanded my answer here. It's hard to answer too much more without writing a whole book! ;)
Comment: Sadly, greggles, your article is now MIA, lost in some website transition. Is it still available anywhere? I'm finally doing one of my last and most important D7 upgrades.
Comment: Thanks for asking rfay and wongataa. I've updated the link to a new, freely accessible home for that creative-commons licensed content :)
Answer: @rfay the Wayback Machine has us covered: https://web.archive.org/web/20131018191043/http://drupalscout.com/knowledge-base/improvements-security-drupal-7


Xamarin Parse.com caching or local storage

Question: I have an app built in Xamarin (Android) that extensively uses Parse as the backend. When i say extensively i mean the app has to query Parse almost continuously as it scans for iBeacons.
It works perfectly well as is, but the problem is scalability in terms of the number of consecutive requests to Parse per second. In other words the number of requests will get ridiculous as soon as there are more than a hundred or so app users.
I need to be able to store the data from Parse locally. As far as i'm aware though, Parse doesn't support local storage via the .Net API, not do they provide caching for .Net.
Can anybody recommend what the best alternative is here? My Parse tables contain pointers etc. so i need to be able to replicate this locally or somehow cache the data.
Thanks.
Comment: I use native android, but using local datastore to sort a list by position every 5 seconds.
Answer: Parse .NET APIs do not support Local Datastore like in android, until they support it, you can either use any .NET generic data caching libraries, or just convert your parse data to JSON and save/serialize it into a local file.
something like akavache may satisfy your requirements.