Finding the Peak of a Kernel Density Estimator

Question: I implemented a Kernel Density Estimator. I have a multivariate dataset that I use with it and I would like to find the point of highest likelihood. A way I thought about is sampling n points using the KDE as my PDF. Then for every point I could use a gradient descent technique and hope to find the maximum.
Is there a better / common way how to do this?
Comment: A one-sentence summary of my answer is: That's the mode and there are workable ways of finding it directly without the arbitrariness of choosing a kernel type or width (or a grid on which to compute density). But independently of that, I envisage a column of values and a corresponding column of density estimates; why isn't this a question of finding the row with the maximum density? There are usually built-in functions for that. (Note that if your problem is bivariate or multivariate density estimation, do please make that explicit.)
Comment: Without further ado: There is a recent publication called [Finding the Mode of a Kernel Density Estimate](https://arxiv.org/abs/1912.07673). (Disclaimer: I haven't read it yet, but I will.)
Comment: My dataset is multidimensional, but I can still order the points by euclidean distance or some other metric and apply half-sample mode or?
Comment: I don't know implementations of half-sample mode except for univariate densities. I can't see that the idea generalises beyond one dimension.
Comment: Then I'm not sure if your answer solves my problem, I'm sorry. I didn't mention it's multidimensional as I expected there's a general solution, independently of the number of dimensions. But anyway I think your answer is valuable contribution.
Comment: @Make42 That looks like a great find.  If, after reading it, you could post a short summary, that would make a fine answer to this question.
Comment: @whuber: Thank you. I will, once I read the paper.
Comment: @whuber: I went through the paper - quite frankly, I don't get it - at least not the details. I am not sure if it is me or the paper. I could reiterate the basic ideas though - would that be helpful and worthy of an answer? I could also reiterate the abstract but I don't see the point in that. If you were to read the paper by any chance, I would be interested in a more approachable explanation. I got lost regarding the polynomial system in section 2.
Comment: @Make42 The idea is as follows: first there are two regimes, low vs high dimensions. In the low dimension, we use the property that the mode must be within some distance r of one of the input points. Then they do an exhaustive search around each of the input points upto this distance r on a fine mesh. For this search, they expand each kernel as some taylor poly upto some required degree that gives enough precision.
Comment: Then they can reformulate the mode finding problem as solving a system of polynomial inequalities for each point in the fine mesh (the system only has 2 inequalities: 1) is value at x larger than some b 2) x is near the mesh point. then binary search on b). Altogether, given a fine enough mesh and large enough degree, you can prove that the best point you find will be close to the true mode
Comment: Now in the high dimensional regime, they simply apply a random projection (see https://en.wikipedia.org/wiki/Johnson%E2%80%93Lindenstrauss_lemma) to a smaller dimension and repeat the algorithm from above. There is a slight caveat of getting a solution in the *original* space after finding it in the projected space but it turns out a simple trick takes care of it
Comment: While it does give some provable guarantees, I am fairly sure that this algorithm is mostly of a theoretical interest since this polynomial system solving cannot be easily implemented. The runtimes are also exponential so performing many steps of the heuristic mean shift algorithm could be much faster
Comment: This doesnt rule out other approaches that get some good theroetical guarantees but are also practical. I can answer further questions about this paper if necessary
Comment: @SandeepSilwal: Let's see if I got this right: Step 1: They choose probing points, by spanning a mesh of the search space, but only using those mesh nodes as probing point that are close to an original data point. Step 2: Instead of calculating the real density, they approximate the "sum of Gaussians" as a "sum of polynomials" (which in itself is a polynomial) using Taylor expansions. Step 3: For each probing point they calculate the approximated density and then compare those with each other. Did I get this right?
Comment: Question1: Could they use different probing point or is the mesh-character important for the following steps? Q2: The reason why they are "fast" is because they use Taylor expansion for calculating the "sum of Gaussians" at the probing points, instead of the "sum of Gaussians" directly. Is that right? Q3: Around which points are the Taylor expansions happening? The input points?
Comment: @Make42 Yes your steps are correct. Q1: They are using a fine mesh around the given input points because they have a structural theorem that says roughly 'the mode must be within some distance r (which can be upper bounded) of one of the input points.' Then the mesh is chosen fine enough so that the function can only vary very little between mesh points. Q2: I'm not sure 'fast' is the right word here. Rather, you can prove things about polynomials (they use a previous result about an algo that solves polynomial inequalities provably. It's likely that no such algo exists for general functions).
Comment: Q3: Basically every function evaluation at each of the mesh points is evaluated for the polynomial approximation which you pick to a sufficiently high degree to guarantee that the value of the polynomial vs the real function only differs by very small (smaller than epsilon*1/n <= epsilon*max value).
Comment: To be more precise, whats happening is that you are asking the question "does there exists a point x near a fixed mesh point p that has value larger than c." Then you iterative over all p and c. Then for a fixed p and c, this question can be translated as a system of two polynomial inequalities which reduces to a previous algorithm. Overall I would say this is more of a stepping stone and hopefully it would be possible to get other results that have provable guarantees but also are more practical.
Comment: @SandeepSilwal: Q3 is meaning this: A series expansion, like the Taylor expansion, needs to be "expanded around a point $a$" as they say: https://mathworld.wolfram.com/TaylorSeries.html - I meant to ask around which point(s) they expand when evaluating the polynomial(s).
Comment: If you are evaluating $f(x) = \exp(-||x-p||^2)$ where $p$ is one of your input points then you expand it at $p$.
Answer: EDIT: This addresses the original question and is retained because it is relevant to that and also to the title of the question, which refers to the peak density. It isn't pertinent to the revised question text, which refers explicitly to the multivariate case.
As the peak of the (estimated) density corresponds to the (main) mode, an alternative is to estimate that mode directly.
A "half-sample mode" can be estimated using recursive
selection of the half-sample with the shortest length.  Although the idea has longer roots, note particularly the detailed and thorough discussion of Bickel and Frühwirth (2006).
First some more general comments:
The mode is often disparaged or neglected by comparison with
its siblings the mean and median, but it can be of distinct interest
or even use, especially whenever distributions are unimodal but
asymmetric. (Modes also have a long history, as readers of Thucydides
will recall.)
If a variable is categorical or counted, the mode can usually
be read off a frequency table, subject to the occurrence of ties.
The same approach can be applied to any variable, subject to
the resolution of measurement.
However, the main question is how to get at an estimate of the mode whenever
a variable is measured with a resolution such that counting is
not a reliable method, if especially all or almost all measurements
are distinct. Many people will have been brought up to look
at a histogram and read off an approximate value, and may have
the impression that not much more can or should be done. Looking at
a graph is naturally always a good idea to put any estimate
of mode in context. A more modern way of doing it is to get
a kernel estimate of the density and modes have been estimated
in that way. Either of these approaches suffers from some arbitrariness,
for example over bin origin and width or kernel type and width.
This shouldn't usually matter, but sometimes a direct method
would be useful.
Less obvious than looking for a peak in density, but still worth
a try, is to look for a shoulder on a quantile plot.
Kernel estimation is an excellent method, especially when bimodality
or multimodality is a possibility. The suggestion, however, is
that it may be regarded as an independent method of assessing modality.
An idea of estimating the mode as the midpoint of the shortest
interval that contains a fixed number of observations goes back at
least to Dalenius (1965). See also Robertson and Cryer (1974),
Bickel (2002) and Bickel and Frühwirth (2006) on other estimators of the mode.
The order statistics of a sample of $n$ values of $x$ are defined by
$x_{(1)} \le x_{(2)} \le \cdots \le x_{(n-1)} \le x_{(n)}$.
The half-sample mode can be defined using two rules.
Rule 1  If $n = 1$, the half-sample mode is $x_{(1)}$.  If $n = 2$, the
half-sample mode is $(x_{(1)} + x_{(2)}) / 2$.  If $n = 3$, the half-sample
mode is $(x_{(1)} + x_{(2)}) / 2$ if $x_{(1)}$ and $x_{(2)}$ are closer than
$x_{(2)}$ and $x_{(3)}$, $(x_{(2)} + x_{(3)}) / 2$ if the opposite is true, and $x_{(2)}$ otherwise.
Rule 2 If $n \ge 4$, we apply recursive selection until left with $3$
or fewer values. First let $h_1 = \lfloor n / 2 \rfloor$. The shortest half of
the data from rank $k$ to rank $k + h_1$ is identified to minimise
$x_{(k + h_1)} - x_{(k)}$
over $k = 1, \cdots, n - h_1$. Then the shortest half of those $h_1 + 1$
values is identified using $h_2 = \lfloor h_1 / 2 \rfloor$, and so on.
To finish, use Rule 1.
Bickel, D.R. 2002.  Robust estimators of the mode and skewness of
continuous data.  Computational Statistics & Data Analysis 39: 153-163.
Bickel, D.R. and R. Frühwirth. 2006.  On a fast, robust estimator of
the mode: comparisons to other estimators with applications.  Computational Statistics & Data Analysis 50: 3500-3530.
Dalenius, T. 1965.  The mode - A neglected statistical parameter.
Journal, Royal Statistical Society A 128: 110-117.
Robertson, T. and J.D. Cryer. 1974.  An iterative procedure for
estimating the mode.  Journal, American Statistical Association
69: 1012-1016.
Note: a Stata implementation is named hsmode (SSC) for which see here. The notes here are based on the help for that program, which includes further discussion and references. Stata users can install using ssc install hsmode. For other implementations see this webpage
Comment: I'd forgotten when I wrote this that I had already written this answer to a different question: http://stats.stackexchange.com/questions/176112/how-to-find-the-mode-of-a-probability-density-function/176144#176144
Comment: I preliminary accept your answer until I tested it. But it seems to be solid. A question I have anyway, this technique (half-sample mode) kind of makes my KDE obsolete, as it's only working on the dataset or? Except I add another gradient decent on top to get a more precise estimate.
Comment: Nothing here makes kernel density estimation obsolete, or even redundant. You always need a check on what the distribution looks like.
Answer: A Kernel Density Estimator is defined as
$$f(x;h) = \frac{1}{nh}\sum_{i=1}^{n}{K(\frac{x-x_i}{h})}$$
where $K$ is defined as
$$\forall x:K(x) > 0, K(-x)=K(x)$$
$$\int_{-\infty}^{\infty}K(x)dx = 1$$
$$\mathbf{E}[K] = 0$$
Now the problem you posed is to find the maximum of the function $f$. The generality of the $K$ function makes the maximum hard to find analytically. Like you mentioned above I think, gradient descent is most likely the way to go. Luckily the expression for the gradient is rather simplistic.
$$\frac{\partial f(x;h)}{\partial x} = \frac{1}{nh^2}\sum_{i=1}^{n}{\frac{dK}{dx}}$$
But, the optimization problem is not convex. And therefore gradient descent will not converge to the same point from different starting points. You have a couple options here. One, is what you stated. Sample a set of points and run gradient descent until convergence. And then select the maximum. But this seems computationally expensive, especially in a multidimensional case.
Another approach that is not as computationally expensive and is an approximation to the algorithm you stated above, is to select a point that you believe is close enough to the maximum and then compute gradient descent from there.
From the definition of K above, we can say that the maximum of K (if $K$ is symmetrical around 0) will be at 0. Therefore in function $f$, $x=x_i$. So intuitively a "good enough" starting point should be a point that minimizes the distances from all the data-set points. And this simply will be the mean or expected value of all your samples.
So to reiterate my approach for a computationally inexpensive approximation to the maximum. You first find the expected value of your data-set. Set that as your starting point in your gradient descent algorithm. And you run the optimization until converges.
Comment: "So intuitively a "good enough" starting point should be a point that minimizes the distances from all the data-set points." That is not the case, except for simple distributions which have only one mode or too large bandwidth parameter.


How to add custom header in Azure API Management before making a call to the backend

Question: I have an Rest Api that is being exposed on Azure. The Azure Api once called calls a WCF Service in the backend.
Firstly I need to transform the JSON Request to XML. Also, To call the SOAP Service I need to add a Custom Header like this:-
 <s:Header>
      <AuthHeader xmlns="http://abc.security.service">
         <UserID>UserID</UserID>
         <Token>Token</Token>
      </AuthHeader>
   </s:Header>

How do I add an "Inbound Policy" that would transform the request to XML and inject the custom header ?
Any ideas or suggestions would be greatly appreciated !!
Answer: For this requirement, please refer to the policy in my APIM.
<policies>
    <inbound>
        <base />
        <json-to-xml apply="always" />
        <set-body>@{
            string inBody = context.Request.Body.As<string>();
            string requestBody = inBody.Replace("<Document>","").Replace("</Document>","");
            string header = "<s:Header><AuthHeader xmlns=\"http://abc.security.service\"><UserID>UserID</UserID><Token>Token</Token></AuthHeader></s:Header>";
            return header + requestBody;
        }</set-body>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

Please pay attention to the escape character in header, we need to use \" instead of ".


Há como construir uma aplicação útil baseada totalmente no paradigma funcional?

Question: O paradigma funcional, em teoria, é bonito de se ver. Purismo, imutabilidade e determinismo. Isso pode facilitar o desenvolvimento, diminuir a incidência de bugs e ajudar na manutenibilidade. A partir disso, há como construir uma aplicação útil baseada totalmente na programação funcional?
Ao meu ver, qualquer comunicação externa ou side effect como:

imprimir no console;
consumir a data/hora do sistema;
salvar/recuperar dados de um banco de dados

fere o purismo do paradigma funcional.
Sendo assim, tem como respeitar inteiramente esse paradigma para montar um software "útil"? Por útil quero dizer aplicações que se comuniquem com sistemas externos, como bancos de dados, APIs, e que receba entrada do usuário.
Se eu quiser construir algo, eu deveria ter parte do meu código funcional e a parte impura separada em outro paradigma que me permita entrada de dados externos? Em geral, como as linguagens funcionais (F#, Erlang, Elixir, Scala) lidam isso? Ou nem lidam?
Comment: LISP permite você sair um pouco do mundo funcional em Common Lisp, então a saída padrão para linguagens deste paradigma é abrir alguns pontos imperativos por questões pragmáticas. Não lembro exatamente como o outro dialeto majoritário (Scheme) lida com isso, mas eu creio que seja abrindo pontos específicos para ser uma programação imperativa também. Outro ponto para se avaliar é: a solução pode ter uma parte funcional pura que é alimentada por uma camada não funcional, como se o programador deixasse a parte funcional apenas para fazer a computação em si, não para lidar com todos os detalhes...
Answer:
Há como construir uma aplicação útil baseada totalmente na programação funcional?

Compiladores são úteis? É um domínio onde esse paradigma funciona muito bem.
Big Data, Machine Learning são úteis? Programação funcional se dá muito bem com isso. Talvez não em todas nuances dessas tecnologias, mas em várias delas vai muito bem.

qualquer comunicação externa fere os pilares do paradigma funcional. Como funciona a construção de uma aplicação com programação funcional? Não existe como respeitar inteiramente esse paradigma para montar algo real/útil?

Pureza de paradigma é difícil de alcançar mesmo. Se quer assim, e nenhuma linguagem que eu conheço é 100% funcional (alguns adaptam o conceito para dizer que sua linguagem é), aí só poderia fazer manipulações de dados existentes no próprio código, nada externo.
Nem imperativo costuma ser 100% puro, ainda que dê.

Se eu quiser construir algo, eu deveria ter parte do meu código funcional e a parte impura separada em outro paradigma que me permita interação externa?

Basicamente é isso.

Em geral, como as linguagens funcionais (F#, Erlang/Elixir, Scala) lidam isso? Ou nem lidam?

Essas, em geral, não lidam, elas são funcionais até a página 3 :)
Tem linguagens que usam Monads para tratar de comunicação externa encapsulando o que é impuro do resto do código, assim, de certa forma, podemos continuar considerando como programação funcional já que as regras colocadas no Monad criam um certo determinismo e não causam efeitos colaterais, mantendo a transparência referencial, ou seja, o Monad é puro mesmo que internamente ele faça coisas impuras, ele não se contamina (pelo menos conceitualmente).
Coloquei no GitHub para referência futura.


Como passar o valor de uma variável para um input hidden?

Question: Como posso fazer para passar o value de uma variável Javascript para um input hidden ?
Answer: Seria bom você colocar algum código mas basicamente com jquery seria assim:

$("#botao").click(function(){
var minhaVariavel="valor";
  alert("Antes de atribuir o valor:"+$("input[name='campoInvisivel']").val());
$("input[name='campoInvisivel']").val(minhaVariavel);
alert("Depois de atribuir o valor:"+$("#campoInvisivel").val());
});

<input type="hidden" name="campoInvisivel" id="campoInvisivel">
<input type="button" value="Colocar Valor com Jquery" id="botao">

Aqui o exemplo somente com JavaScript, lembrando que os alert são apenas para demonstração, a linha na qual passa o valor para o input é essa document.getElementById("campoInvisiveljs").value=minhaVariavel;. Segue abaixo o código completo

// Aqui é só com js
function passarValor(){
var minhaVariavel="valor";
alert("Antes de passar o valor:"+ document.getElementById("campoInvisiveljs").value);
document.getElementById("campoInvisiveljs").value=minhaVariavel;
alert("Depois de passar o valor:"+document.getElementById("campoInvisiveljs").value);
}
   <input type="hidden" name="campoInvisiveljs" id="campoInvisiveljs">
   <input type="button" value="Colocar Valor com Java Script" id="botao" onClick="passarValor();">
Comment: Não existe nenhuma forma mais simples com javascript?
Comment: Você quer somente com js, sem jquery?
Comment: o que voce nao achou simples?
Comment: Exato, quero somente com javascript.
Comment: Pronto, editei e deixei das duas formas para servir para outras pessoas posteriormente...
Answer: Com javascript basta atribuir o valor ao atributo value:
var variavel = ["a", "b", "c"];
document.getElementById("input_hidden_id").value = variavel.join("");

Exemplo:

    var variavel = ["a", "b", "c"];
    document.getElementById("input_hidden_id").value = variavel.join("");

    function verValor() {
      document.write(document.getElementById("input_hidden_id").value);
    }
<input id="input_hidden_id" type="hidden" value="123" />
<button onclick="verValor()">Ver Valor</button>
Comment: Como posso passar uma array?
Comment: Pode usar a função `join()` que junta os valores do array. Editei a resposta @Gonçalo
Answer: Podes fazer isso assim:

var dados = ['eu', 'tu', 'ele'];
var input = document.getElementById('escondido');
input.value = JSON.stringify(dados);
<input type="hidden" id="escondido" />

Desse modo o input vai receber como valor um JSON que pode facilmente ser re-convertido em array no servidor ou quando se ler o valor dele.


How do I scrape TLS certificates using go-colly?

Question: I am using Colly to scrape a website and I am trying to also get the TLS certificate that the site is presenting during the TLS handshake. I looked through the documentation and the response object but did not find what I was looking for.
According to the docs, I can customize some http options by changing the default HTTP roundtripper. I tried setting custom GetCertificate and GetClientCertificate functions, assuming that these functions would be used during the TLS handshake, but the print statements are never called.
    // Instantiate default collector
    c := colly.NewCollector(
        // Visit only domains: hackerspaces.org, wiki.hackerspaces.org
        colly.AllowedDomains("pkg.go.dev"),
    )

    c.WithTransport(&http.Transport{
        TLSClientConfig: &tls.Config{
            GetCertificate: func(ch *tls.ClientHelloInfo) (*tls.Certificate, error) {
                fmt.Println("~~~GETCERT CALLED~~")
                return nil, nil
            },
            GetClientCertificate: func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) {
                fmt.Println("~~~GETCLIENTCERT CALLED~~")
                return nil, nil
            },
        },
    })

Please help me scrape TLS certificates using Colly.
Answer: This is a snippet to get leaf certificate from raw http.Response in case you give up getting certificate using Colly.
tls := ""
if res.TLS != nil && len(res.TLS.PeerCertificates) > 0 {
    cert := res.TLS.PeerCertificates[0]
    tls = base64.StdEncoding.EncodeToString(cert.Raw)
}


Desativar determinadas opções do context menu padrão

Question: Eu gostaria de saber como eu posso desabilitar as opções do menu de contexto da melhor forma possível, se tiver alguma forma nativa e que não seja difícil de desfazer, seria interessante.
Um exemplo para o resultado esperado é a tag de vídeo do site xvideos.com, eles também têm a opção "Salvar vídeo como ..." desabilitada, e o menu de contexto é o padrão, eu gostaria do mesmo resultado.

Edit:

Não quero criar uma menu de contexto personalizado em javascript, apenas desativar opções do menu padrão, mesma que a forma seja javascript, mas não criar um novo.
Comment: No caso eu não quero criar uma menu de contexto personalizado, apenas desativar opções do menu padrão.
Comment: Então você ainda pode utilizar como base a [resposta aceita](https://pt.stackoverflow.com/a/112472/3774) que esta na pergunta duplicada, basta você não usar o `menu`, veja o [exemplo](https://jsfiddle.net/L03ejcwq/).
Comment: Mas eu quero deixar o menu de contexto funcionando normal, apenas desativar opções dele, desativar ele totalmente poderia usar a resposta marcada como duplicada, mas não ao respeito do menu de contexto padrão.
Comment: Ok, entendi seu problema, não sei se isso é possível, vou indicar sua pegunta para ser reaberta, vale a pena você modificar esse trecho da sua pergunta `desabilitar as opções` para `desabilitar determinadas opções` ou algo parecido, também vale a pena você colocar que opções são essas que você quer desabilitar.  =D
Comment: Vou editar Icaro, vlw, e o exemplo que passei é de conteudo aberto, mas para quem se interessar na questão, vale a pena acessar qualquer video do xvideos, deletar uma div qe fica por cima dos videos e ver que na tag video, é o menu padrão mesmo.
Comment: Se você só quiser desabilitar o download da tag do html5 `` talvez essa [resposta do SOen](https://stackoverflow.com/a/41136470/2456894) te ajude.
Comment: Pelo que dei uma olhada isso ai é aplicado no player da tag video, isso ja ta aplicado no meu projeto, ele tira o botão de download do player html5
Answer: A princípio não é possível habilitar ou desabilitar essas opções do context menu.
Como aparece no exemplo citado pode estar relacionado à forma como o conteúdo está sendo entregue ao browser e que ele não consegue fazer o download do conteúdo e não uma questão de html ou javascript.
Isso poderia ser pelo conteúdo ser do tipo stream e ou estar sendo entregue em chunks (apenas uma suposição).
O que você pode fazer é: Marcar na controlsList da sua <video> a propriedade nodownload e "desabilitar" o contextmenu do elemento em questão.

<!DOCTYPE html>

  <video id="videoPlayer" width="400" controls
                                      controlsList="nodownload"
                                      oncontextmenu="return false;">
      <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
      <source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
</video>

Comment: Pelo que vi realmente é em bloco, com ao decorrer do vídeo é baixado os blocos com o nome de hls-720p.ts. e a requisição retorna tipo video/mp2t. Vou marcar sua resposta como solução, mas para aprendizado, você teria algum link ou orientação de como pesquisar para ter esse tipo de vídeo? pois pelo que vi o src do vídeo não muda, então é feito apenas uma requisição e acredito que o proprio navegador faça as restantes.. (Estou chutando..)
Comment: @HenriAzevedo Você deve pesquisar por smooth streaming ou adaptative bitrate.


Código entra em loop infinito

Question: Por que este código esta em loop infinito?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main()
{
int i;
float salario[10],  valorDataBase, salarioReajustado[10];

printf("Informe o percentual  de reajuste da data-base: \n");
scanf("%f",  &valorDataBase);

    for (i=0 ; i<10 ;  i=i++)
    {
        printf("Informe o seu salario atual: \n");
        scanf("%f", &salario[i]);
    }
    //Impressão da lista de  dados do vetor salario reajustado
    for (i=0 ; i<10 ;  i=i++)
    {
        salarioReajustado[i] = salario[i] + salario[i]*valorDataBase/100;
        printf("Seu salario reajustado sera %f \n",salarioReajustado[i]);
    }

getch();
return(0);
}

Comment: `i=i++` deve ser apenas `i++`
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: E eu pergunto, por que está incrementando a variável i e atribuindo a ela mesma? Isto é comportamento indefinido. Se só incrementar funciona, afinal é o correto. Deve ter copiado de forma equivocada de algum lugar. De qualquer forma o ideal é nunca copiar nada, é entender como aquilo funciona para usar de forma adequada. Simplificando:
#include <stdio.h>

int main() {
    float salario[10], valorDataBase;
    printf("Informe o percentual  de reajuste da data-base: \n");
    scanf("%f", &valorDataBase);
    for (int i = 0; i < 10; i++) {
        printf("Informe o seu salario atual:\n");
        scanf("%f", &salario[i]);
    }
    for (int i = 0; i < 10; i++) printf("Seu salario reajustado sera %f\n", salario[i] + salario[i] * valorDataBase / 100);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Dica final, em casos reais valores monetários não podem ser do tipo float.
Comment: Só para complementar, `i = i++` primeiro atribui e depois incrementa, por conta disso a variável `i` sempre é `0`, se fizesse dessa forma `i = ++i` funcionaria, porque primeiro incrementaria e depois atribuiria.

Código entra em loop infinito


Existence of system of parameters via prime avoidance

Question: This is a question about the hint in exercise 11.3.I part (b) of Vakil's FOAG notes, which is to prove the existence of a system of parameters for a Noetherian local ring. The statement of the full exercise is:

Suppose $(A,\mathfrak m)$ is a Noetherian local ring.
(a) Use Krull's Height Theorem to prove that if there are $g_1,\dots ,g_l$ such that $V(g_1,\dots ,g_l) = \{ \mathfrak m \}$, then $\dim A \leq l$.
(b) Let $d = \dim A$. Show that there exist $g_1,\dots ,g_d\in A$ such that $V(g_1,\dots ,g_d)
 = \{ \mathfrak m \}$. Hint: use induction on $d$. Find an equation $g_d$ knocking the dimension down by 1, i.e. $\dim A/(g_d) = d - 1$. Suppose $\mathfrak p_1, \dots ,\mathfrak p_n$ correspond to the irreducible components of ${\rm Spec} A$ of dimension $d$, and $\mathfrak q_i \supset \mathfrak p_i$ are prime ideals corresponding to irreducible closed subsets of codimension 1 and dimension $d-1$. Use prime avoidance to find $h_i \in \mathfrak q_i\setminus \cup_{j=1}^n \mathfrak p_j$. Let $g_d = \Pi_{i=1}^n h_i$.

Proceeding with the inductive step as in the bolded hint, we can pick out the $\mathfrak q_i$ of both codimension 1 and dimension $d-1$ because we can just take them to be the second prime ideal in every chain of length $d$ starting with the minimal prime $\mathfrak p_i$. Because $\mathfrak q_i$ has height 1, it cannot be contained in any of the $\mathfrak p_j$, hence the prime avoidance lemma applies and we can find an element $h_i$ as stated.
The point I don't understand is this: why do we need to take the product of the $h_i$ at the end? It seems the purpose of doing that is to ensure that $g_d$ is contained in every $\mathfrak q_i$. But isn't it already true that setting $g_d = h_1$ gives a quotient $A/(g_d)$ which is a Noetherian local ring of dimension $d-1$, since we're avoiding all the minimal primes? What am I missing?
Comment: Geometrically minimal ideals correspond to irreducible components of $\mathrm{Spec} A$, now the idea is to decrease the dimension is to consider the codimension one subvariety defined by $g_d$, but to be sure that you decrease the dimension you have to intersect all the irreducible components. Now if you only take $h_i$ you are certain to intersect the $i$th component but not the other ones, by taking the product you make sure to intersect everyone.
Comment: I don't understand what you mean by "to decrease the dimension you have to intersect all the irreducible components". Why doesn't Alex's argument work as written to show that the dimension is $d - 1$? Since it seems to me that if $A/(g_d)$ had dimension $d$ rather than $d - 1$, then it must contain one of the $\mathfrak{p}_i$ (which it doesn't, since we made sure that $h_1 \not\in \mathfrak{p}_i$ for all $i$).
Answer: If you were to take $g_d = h_1$, then indeed $\text{Spec }A/(g_d)$ has an irreducible component (corresponding to $q_1$) of dimension $d - 1$. But this does not ensure that $A/(g_d)$ is pure of dimension $d - 1$. We could now have irreducible components of $A/(g_d)$ of dimension smaller than $d-1$, not corresponding to any of the $\mathfrak{q}_i$.


Using Python for Android with theano import, gives IOError: [Errno 21]

Question: I have a Python-Kivy app that I want to make available to Android. The app uses Theano and Numpy. I get the following adb logcat when running app on an Android device:
<code> Traceback (most recent call last):

I/python  (24492):    File "main.py", line 19, in <module>

I/python  (24492):      from theano import function

I/python  (24492):    File "/data/data/org.example.AppName/files/lib/python2.7/site-packages/theano/__init__.py", line 42, in <module>

I/python  (24492):      from theano.configdefaults import config

I/python  (24492):    File "/data/data/org.example.AppName/files/lib/python2.7/site-packages/theano/configdefaults.py", line 1486, in <module>

I/python  (24492):      "platform": platform.platform(),

I/python  (24492):    File "/home/user-name/.local/share/python-for-android/build/other_builds/python2/armeabi/python2/python-install/lib/python2.7/platform.py", line 1575, in platform

I/python  (24492):    File "/home/user-name/.local/share/python-for-android/build/other_builds/python2/armeabi/python2/python-install/lib/python2.7/platform.py", line 163, in libc_ver

I/python  (24492):  IOError: [Errno 21] Is a directory: '/data/data/org.example.AppName/files'

I/python  (24492): Python for android ended.
</code>
I don't know how to proceed, or if it's possible to import Theano in Android. The Kivy app works on Linux and Windows.
Thanks in advance.
Comment: The actual reason for the error is that platform.py makes an incorrect assumption about the location of the Python executable, and gets confused because it's a directory. In reality, there is no executable because Python is being run via a short C program. I'm not sure if there's something you're supposed to do to make the platform module work in this case, but it might be useful to follow up. However, in this case if the existing question answer is correct about Theano not supporting Android, that may not be useful here.
Answer: Theano doesn't support android. You could use TensorFlow or create a webservice and make http request from your app to ask the service to do the job for you.


Hook to render all active Facet

Question: Is there a possible hook or something else that can be written to display all the current active facet link i.e the selected facet. i want to display to the user in breadcrumb format  all the facet they have selected and give them the option to remove it
thanks
Answer: There is a bock for this.
You can create/configure the block from Configuration->Search and Metadata->Current Search block (admin/config/search/current_search)
Create a new Search Block and choose a type: Active Items. In pattern enter from tokens below: [facetapi_active:active-value]
Then go to your blocks page and activate your new block.
See the screenshot how my settings look like.
Comment: do you have any ideas on how to add clear all

Hook to render all active Facet


INCOME TAX ANALYSIS: How to run a loop involving floats(decimals as intervals)

Question: I am trying to compute the tax analysis (PAYE) using if loop ('cos that's what I know), the first and last loop works fine but returns 0 for 2nd, 3rd and 4th loop.
I tried rounding up the input variable and it works but I get wrong decimals which is not accepted.
import numpy

#TAXABLE = 200333.33
#TAXABLE = 282645.83
#TAXABLE = 65203.83
#TAXABLE = 133364.58
#TAXABLE = 20495.83
#TAXABLE = 147083.33
#TAXABLE = 10328.83
#TAXABLE = 223908.33
#TAXABLE = 3504.75
#TAXABLE = 890.33
TAXABLE = 119270.83
TAX_INCOME = TAXABLE
#TAX_INCOME = round(TAXABLE)
#TAX_INCOME
TAX=0
#PAYE = 25000
LIMIT1 = 25000
LIMIT2 = 25000
LIMIT3 = 41666.67
LIMIT4 = 41666.67
LIMIT5 = 133333.34

#PERCENTAGE
RATE1=0.07
RATE2=0.11
RATE3=0.15
RATE4=0.19
RATE5=0.21
RATE6=0.24

#CALCULATION
if TAX_INCOME <= 25000:
    TAX1=0
    TAX = TAX_INCOME*RATE1 + TAX1
    if TAX < (0.01*TAXABLE):
        TAX = (0.01*TAXABLE)
if TAX_INCOME in numpy.arange(25001,50001):
    TAX1 = LIMIT1*RATE1
    TAX2 = (TAX_INCOME-25000)*RATE2
    TAX = TAX1 + TAX2
if TAX_INCOME in numpy.arange(50001,91667.67):
    TAX1 = LIMIT1*RATE1
    TAX2 = LIMIT2*RATE2
    TAX3 = (TAX_INCOME-50000)*RATE3
    TAX = TAX1+TAX2+TAX3
if TAX_INCOME in numpy.arange(91667.67, 133334.33):
    TAX1 = LIMIT1*RATE1
    TAX2 = LIMIT2*RATE2
    TAX3 = LIMIT3*RATE3
    TAX4 = (TAX_INCOME-91666.67)*RATE4
    TAX = TAX1+TAX2+TAX3+TAX4
if TAX_INCOME in numpy.arange(133334.34, 266667.68):
    TAX1 = LIMIT1*RATE1
    TAX2 = LIMIT2*RATE2
    TAX3 = LIMIT3*RATE3
    TAX4 = LIMIT4*RATE4
    TAX5 = (TAX_INCOME-133333.34)*RATE5
    TAX = TAX1+TAX2+TAX3+TAX4+TAX5
if TAX_INCOME>=266667.68:
    TAX1 = LIMIT1*RATE1
    TAX2 = LIMIT2*RATE2
    TAX3 = LIMIT3*RATE3
    TAX4 = LIMIT4*RATE4
    TAX5 = LIMIT5*RATE5
    TAX6 = (TAX_INCOME-266666.68)*RATE6
    TAX = TAX1+TAX2+TAX3+TAX4+TAX5+TAX6

#result = format(TAX)
result = "{0:.2f}".format(TAX)
result

I expect:

65203.83 to return 6780.57;
133364.58 to return 18673.23;
147083.33 to return 21554.17

but my code keeps returning 0.00.
Answer: I believe the problem is in the conditions referring to numpy.arange:
if TAX_INCOME in numpy.arange(91667.67, 133334.33):

requires that TAX_INCOME be among a set of values defined as 91667.67 + 1, 91667.67 + 2, ..., 133334.67. I assume your intention would be better expressed as:
if 91667.67 < TAX_INCOME  <= 133334.33:

If you change all of the conditions in the way above you will get the expected results.
Comment: thank you @sophros, the code now works as should. I appreciate.
Comment: Please sir, can u take a look at the first loop, im trying to return 10% of TAXABLE if the TAX computed is less than 10% of TAXABLE, else it shud return the initial computed TAX...BUT my code is not checking, its just computing the TAX.. CAN YOU ASSIST?????.
Comment: @alhaji - as a token of appreciation could you please mark the answer as correct with the tick mark on the left of the answer and / or upvote it?
Comment: @alhaji: Regarding your second question... are you sure 0.01 is 10%?
Answer: numpy.arange will return an array of valued spaced by 1 (unless you specify a different step).
change your if statements like this:
if TAX_INCOME in numpy.arange(91667.67, 133334.33):
to
if TAX_INCOME in >= 91667.67 and TAX_INCOME < 133334.33):


Orthogonal projection onto a subspace.

Question: Let $H = L^2(0,1)$ and $E$ is spanned by the set $\{f_1(t)=\sin(2\pi t), f_2(t) = \sin(4\pi t), g_0(t) = \cos(0), g_4(t) = \cos(8 \pi t)\}$. Then i need to find a vector which is closest to the function $f(t) = 3t \in H$. I know that this is equivalent to a condition
$$
                     (f-g)\perp E
$$
where $g \in E$. So using this equivalent condition and the fact that functions of $E$ can be presented as a linear combination of {$f_1(t)=\sin(2\pi t), f_2(t) = \sin(4\pi t), g_0(t) = \cos(0), g_4(t) = \cos(8 \pi t)\}$, but as a result i receive really complex integrals which are hard to compute. So any help/suggestions are apperciated.
Comment: You should use the Fourier series, sine and cosine series. Btw, the imaginary part is cero in your case.
Comment: "Then i need to find a vector which is closest to the $f(t) = 3t\in H$" - Well, I would choose $f$ itself. You can't get closer than that. ;-)
Answer: You want to find constants $\alpha,\beta,\gamma,\delta$ such that
$$
      (f-\alpha f_1-\beta f_2-\gamma g_0-\delta g_4)\perp E
$$
Because $f_1,f_2,g_0,g_4$ are mutually orthogonal, then the above is equivalent to
$$
          \alpha=\frac{\langle f,f_1\rangle}{\langle f_1,f_1\rangle},\;\beta=\frac{\langle f,f_2\rangle}{\langle f_2,f_2\rangle},\;\gamma=\frac{\langle f,g_0\rangle}{\langle g_0,g_0\rangle},\;\delta = \frac{\langle f,g_4\rangle}{\langle g_4,g_4\rangle}
$$

Orthogonal projection onto a subspace.


Is all run four adds to the tally of number of 4s of a batsman in cricket?

Question: When a batsman runs four runs, does it add to the tally of 4s scored by that batsman?
Answer: No.
The tally of "fours" is specifically for scoring of a Boundary Four, not just any play that happens to score four runs.


SQL Cumulative Count with BigQuery for active

Question: I would like to know how to the rows date falls into once truncated into week. Current data is

Ad Name
Launch Date
Last Seen

Ad 1
9 Dec, 2021
16 Dec, 2021

Ad 2
1 Dec, 2021
9 Dec, 2021

Ad 3
1 Dec, 2021
31 Dec, 2021

Desired output would be, imaginging that December has 4 weeks. The dates provided are examples only, they would be automatically generated by the SQL function date_trunc

Week
Active Ads

Dec Date 1-7
2

Dec Date 7-14
3

Dec Date 14-21
2

Dec Date 21-30
1
Answer: Consider below approach
<code>select
  date_trunc(seen_day, week) week_start,
  last_day(seen_day, week) week_end,
  count(distinct ad_name) Active_Ads
from your_table,
unnest(generate_date_array(
  parse_date('%d %B, %Y', launch_date),
  parse_date('%d %B, %Y', last_seen)
)) seen_day
group by 1, 2
</code>
if applied to sample data in your question - output is


Cannot GET /peerjs/peerjs/id

Question: In console it is outputting: peerjs.min.js:64 GET http://localhost:3030/peerjs/peerjs/id?ts=16144206488930.6577072628446186 404 (Not Found)
After expanding the error in the networks tab it showed: Cannot GET /peerjs/id
I tried changing the port number, even adding quotes at some places. I am trying to make a zoom clone. I am sure it's a tiny mistake which is causing such headache. So help would be appreciated.
Client Side
    const socket = io('/');

    const videoGrid = document.getElementById('video-grid');

    const myVideo = document.createElement('video');
    myVideo.muted = true;

    var peer = new Peer(undefined, {
        path: '/peerjs',
        host: '/',
        port: '3030'
    });

    let myVideoStream
    navigator.mediaDevices.getUserMedia({
        video: true,
        audio: true
    }).then(stream => {
        myVideoStream = stream;
        addVideoStream(myVideo, stream);
    })

    peer.on('open', id => {
        socket.emit('join-room', ROOM_ID, id);
    })

    socket.on('user-connected', (userId) => {
        connecToNewUser(userId);
    })

    const connecToNewUser = (userId) => {
        console.log(userId);
    }

    const addVideoStream = (video, stream) => {
        video.srcObject = stream;
        video.addEventListener('loadedmetadata', () => {
            video.play();
        })
        videoGrid.append(video)
    }

Server Side
const express = require('express')
const app = express();
const server = require('http').Server(app);

const io = require('socket.io')(server);

const { v4: uuidv4 } = require('uuid');
const { ExpressPeerServer } = require('peer');
const peerServer = ExpressPeerServer(server, {
    debug: true
});

app.set('view engine', 'ejs');

app.use(express.static('public'));

app.get('/', (req, res) => {
    // res.status(200).send("Hello World")
    res.redirect(`/${uuidv4()}`);
    // res.send(`/${uuidv4()}`);
})

app.get('/:room', (req, res) => {
    res.render('room', { roomId: req.params.room });
})

io.on('connection', socket => {
    socket.on('join-room', (roomId, userId) => {
        socket.join(roomId);
        socket.to(roomId).broadcast.emit('user-connected', userId);
    })
})

server.listen(3030);

Comment: I am having the same issue. Did you find a fix ? I am using vue.js 3
Comment: @NewBie1234 no I didn't find any fix, had to put the project on hold
Comment: anything new surfaced ?
Comment: The console says `/peerjs/peerjs/id` but the error says `/peerjs/id`...which one is true?  And once we straighten out which URL is the right one...then which route do you want to have handle that request?
Comment: If anyone is else is facing the issue, as mentioned in the answer "app.use(/peerjs, peerServer)" should to added and also with respect to the above question on the client side peer-object "path" is defined but while starting peer-server "path" is not defined
Answer: Just add app.use('/peerjs', peerServer) on your server-side then you will be fine.
Comment: @Piyush add this line "app.use('/peerjs', peerServer)" that is the only missing point.
Answer: had same issue found the solution by adding
const peerServer = ExpressPeerServer(server, {
   debug: true,
   key:"add-some-key"      <--- this fixed it add some key
});

app.use('/peerjs', peerServer)

then access via
http://localhost:9000/peerjs/add-some-key/id

should give a key

Cannot GET /peerjs/peerjs/id


Pandas: Update values of a column

Question: I have a large dataframe with multiple columns (sample shown below). I want to update the values of one particular (population column) column by dividing the values of it by 1000.
City     Population
Paris    23456
Lisbon   123466
Madrid   1254
Pekin    86648

I have tried
df['Population'].apply(lambda x: int(str(x))/1000)
and
df['Population'].apply(lambda x: int(x)/1000)

Both give me the error

ValueError: invalid literal for int() with base 10: '...'
Comment: Try this: `pd.to_numeric(df['Population'], errors='coerce').div(1000)`
Answer: If your DataFrame really does look as presented, then the second example should work just fine (with the int not even being necessary):
In [16]: df
Out[16]:
     City  Population
0   Paris       23456
1  Lisbon      123466
2  Madrid        1254
3   Pekin       86648

In [17]: df['Population'].apply(lambda x: x/1000)
Out[17]:
0     23.456
1    123.466
2      1.254
3     86.648
Name: Population, dtype: float64

In [18]: df['Population']/1000
Out[18]:
0     23.456
1    123.466
2      1.254
3     86.648

However, from the error, it seems like you have the unparsable string '...' somewhere in your Series, and that the data needs to be cleaned further.
Comment: Yes, as you mentioned I do have some unparsable string  '...'

I did add
    df.fillna(np.NaN)

Looks like that has not helped

Pandas: Update values of a column


How to Combine and Sell multiple iOS Apps as one package

Question: We have more then 10 separate apps on app store. But now we want to sell all these apps as one package, so user will have paid once only for all 10 apps. Is it possible on App store?
Comment: No, I'm afraid this is currently not possible.
Comment: so, can you please give me any alternate if you have.
Answer: Not ideal but:
Alternative could be for the user to download one of the apps (for free). This app contains a store which lists the other apps in the group and allows easy download (also free). Store also offers a pack activation purchase which enables the core features of all the apps. This generates a record for the user on your server and / or a number of hashed identifiers. The user can tap a number of buttons to open the other apps using the hashed identifiers (custom URL scheme) or use a restore button in the other apps which checks your server before checking with Apple.
Answer: I suggest that you allow the apps to be installed for free, and then use in-app purchasing to acquire a license to run any of the 10 applications. This approach does not require implementing a store of your own.
Comment: Yes, we can do like that but if we have 500 devices then we will have to make transaction in all the devices. we wants to remove this multiple payment transaction.


Not able to load BHO when IE is opened as non admin in EPM mode

Question: I have created 64 bit BHO which I am trying to load in windows 8 IE10.
I am trying to open IE in user account with non admin privileges.
BHO gets loaded when I open IE as Administrator(by right click on it and click Run as admin)
But same BHO is not getting loaded by IE when I open it in non admin mode.
Are there any registry changes I need to make so as to get it loaded when IE is opened as non admin.
Answer: For some reason, running IE as admin seems to lift any restrictions enforced by EPM.
EPM requires that your BHO is compiled for x64 and x86, and that your BHO registers itself as AppContainer compliant.
If you're using an RGS file to define your BHO's class, you should add:
<code>'Implemented Categories' = s ''
    {
        {59fb2056-d625-48d0-a944-1a85b5ab2640} = s ''
            {
            }
    }
</code>
See this link for more details.
Also your BHO's DLLs should be in an AppContainer readable folder (I know by experience that subfolders of "Program Files" and "System32" are AppContainer readable).


What kind of cut-offs are used for publication bias tests in meta-analysis?

Question: I have performed meta-analysis and included four different tests for publication bias in the analysis - classic fail-safe N, Orwin's fail-safe N, Duval and Tweedie's trim and fill as well as funnel plots. The tests did not seem to indicate publication bias in my material - according to classic fail-safe N 23 papers would be needed to bring the result to p > 0.05, according to Orwin's fail-safe N 8 papers would be needed to reduce the OR into a trivial one, trim and fill test did not show adjustments and funnel plot was symmetrical.
However, one of my reviewers wants me to include cut-offs for publication bias tests in the Methods. I have tried to look for any cut-offs that would be commonly used with these tests but in many cases even the interpretation of results is not very exact. How should I proceed with this problem, what should I answer to the reviewer?
Thanks!
Answer: The use of any fail-safe N method is depreciated. Please see Becker (2005) and check out the Conclusions section. Here, she states:

"Given the other approaches that now exist for dealing with publication bias, the fail-safe N should be abandoned in favour of other, more informative analyses [...]".

You also might want to read her statement in Summary of the Examples:

"The incredible range of values shown here reveals one of the greatest weaknesses of the failsafe N computations - it is difficult to interpret the values without a statistical criterion."

The "trim and fill method" is a good starting point. However, you also might want to give Egger's regression method a try which, for instance, is described in Sterne/Egger (2005) (please note that Egger et al. (1997) suggest a weighted least squares regression, while Sterne and Egger (2005: 101) recommend a simple OLS regression). See also this CV question on Egger's linear regression method intercept in meta analysis.
For a general overview of methods to detect publication bias see Sutton et al. (2000) or these slides by Birgit Schrödle.
References
Egger, M., G. Davey Smith, M. Schneider, C. Minder (1997), Bias in meta-analysis detected by a simple, graphical test British Medical Journal 315: 629-634.
Sterne, J.A.C., M. Egger (2005), Regression Methods to Detect Publication and Other Bias in
Meta-Analysis. Pp. 99-110 in: H.R. Rothstein, A.J. Sutton, M. Borenstein (eds.), Publication Bias in Meta-Analysis. Prevention, Assessment and Adjustments, The Atrium, Southern Gate, Chichester: Wiley.
Sutton, A.J., F. Song, S.M. Gilbody, K.R. Abrams (2000), Modelling publication bias in meta-analysis: a review. Statistical Methods in Medical Research 9: 421-445
Comment: Thank you for the prompt and very useful comment! I will proceed with the Egger's regression method.


Exibir imagem até o gif ser carregado

Question: Estou carregando um gif quando o utilizador passa o rato por cima de uma determinada
. Faço isso usando jQuerry com o seguinte código:
$('#vidthumb_' + idDoDiv).attr('src', caminhoParaOGif);

o problema é que o gif demora por volta de 1 segundo a carregar, e eu queria mostrar alguma coisa (imagem de loading ou texto) até o gif ser carregado e pronto para ser reproduzido, como devo alterar o meu código?
Comment: Deixei como resposta uma solução para você.
Answer: Você pode adicionar um spinner feito em CSS após o elemento , que será removido após o gif ser carregado pelo onload.
Só é preciso colocar a imagem dentro de uma div (essa div não irá influenciar no layout, serve apenas como referência).
Veja exemplo (como a transição é muito rápida, deixei comentada a linha que esconde o spinner para que se possa vê-lo no exemplo):

caminhoParaOGif = "https://tctechcrunch2011.files.wordpress.com/2015/08/safe_image.gif";

$("#vidthumb_").on("mouseover", function(){
   $(this).after('');
   $('#vidthumb_')
   .attr('src', caminhoParaOGif)
   .on("load", function(){
//      $(this).next().remove(); // descomente esta linha
   });
});
*{
   position: relative;
}

.loader {
    border: 16px solid #f3f3f3; /* cinza */
    border-top: 16px solid #3498db; /* azul */
    border-radius: 50%;
    width: 30px;
    height: 30px;
    animation: spin 2s linear infinite;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -31px 0 0 -31px; /* metade da soma do width + 2x a borda*/
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

Comment: Ótimo método, mas vale lembrar que @keyframes não funciona em alguns browsers antigos :D
Comment: Funciona no IE 10+... creio que seja bem satisfatório. :D
Comment: Sim, depende da necessidade e para quem for desenvolver, eu mesmo tenho um projeto em empresa que tive que readaptar o css para o ie7 pois o pessoal só usa ele. Seria ótimo se começassem a acompanhar as atualizações, rs.
Comment: como posso editar/brincar com snippet?
Comment: @ihavenokia Vc pode alterar apenas as dimensões e as cores, alterando o border, o width/height e as cores das bordas.
Comment: @ihavenokia Se quiser colocar outro estilo de spinner, aí vc pode procurar na net algum e substituir, pois a lógica é a mesma.
Answer: Como você está atribuindo a imagem via script, a mesma leva um tempo para ser carregada no documento. Uma dica é colocar um gif/imagem que você quer que fique até a sua imagem carregar diretamente no elemento, assim quando o utilizador passar o mouse sobre o elemento, a imagem será apresentada até a nova imagem ser atribuída ao src.
Exemplo:

$('#img').mouseenter(function(){
  $(this).attr('src','http://www.topimagens.com.br/imagens/imagens-mais-novas.jpg');
});

Comment: mas neste caso acontece exatamente o problema que eu tenho, se **imagens-mais-novas.jpg** for um gif e demorar a carregar vai dar a sensaçao que é uma mera imagem e o utilizador poderá tirar o rato em cima da div pois ela fica algum tempo sem 'se mexer'.

Exibir imagem até o gif ser carregado


How to include both a class and data attributes in a form select in Rails 7?

Question: In my Rails 7 app, I am using Stimulus and need to add data attributes to a form select to link it to a JavaScript controller. I am also trying to format the field (not the options) with a class.
Here is the form select element:
<%= f.select(:repeat, Batch.repeats, {class: "class_name"}, { data: { batch_repeat_target: "input", action: "change->batch-repeat#toggle" }}) %>

The above code results in the data attributes being applied to the select field, but leaving the class out.
I also tried to flip the class and the data attributes, as follows:
<%= f.select(:repeat, Batch.repeats, { data: { batch_repeat_target: "input", action: "change->batch-repeat#toggle" }}, { class: "class_name" }) %>

The result was the opposite of the first approach: this time, the field was styled per the class, but the data attributes were not associated with the select element.
Per this question, I became aware that:

select helper takes two options hashes, one for select, and the
second for html options. So all you need is to give default empty
options as first param after list of items and then add your class to
html_options.

From there, I thought that I needed to include both the class and the data attributes in the first option hash, and leave the second one empty, along the following lines:
<%= f.select(:repeat, Batch.repeats, { { class: "class_name" }, { data: { batch_repeat_target: "input", action: "change->batch-repeat#toggle" }}}, {}) %>

However, the above revised code resulted in an ActionView::SyntaxErrorInTemplate in BatchesController#new error.
In yet another attempt, I tried to shuffle things around, leaving the first option hash empty and including both the class and the data attributes in the second one, as follows:
<%= f.select(:repeat, Batch.repeats, {}, { { class: "class_name" }, { data: { batch_repeat_target: "input", action: "change->batch-repeat#toggle" }}}) %>

That revision also resulted in an ActionView::SyntaxErrorInTemplate in BatchesController#new error.
The question referenced above is more than 11 years old and: is there a different convention now, particularly in Rails 7, with regards to form select elements? How can I both include a class and data attributes here?
Answer: A hash looks like this: { key1: value1, key2: value2 }
So, take your attempted code: { { class: "class_name" } } - the inner hash there is { class: "class_name" } so let's assign that to a variable: value1 = { class: "class_name" } and then let's use that variable in your attempted code: { value1 }
See how that's not a hash, there's no key for the value.  A hash must always have keys and values.  This is why you're getting the syntax errors in your second two examples.
So let me go through your other two attempts:
<%= f.select(:repeat, Batch.repeats, {class: "class_name"}, { data: { batch_repeat_target: "input", action: "change->batch-repeat#toggle" }}) %>

So here, :repeat is the first argument, Batch.repeats is the second, the third argument (which is supposed to be the select options) is the hash with a single key/value pair: { class: "class_name" }, and the fourth argument (which is supposed to be the html options) is the hash with a single key/value pair: { data: { the: data, hash: here }
Your second attempt:
<%= f.select(:repeat, Batch.repeats, { data: { batch_repeat_target: "input", action: "change->batch-repeat#toggle" }}, { class: "class_name" }) %>

First two arguments the same, the third argument (the select options) is now the hash with the :data key/value, and the fourth argument (the html options) is now the hash with the single :class key/value.
What you want to do is provide an empty hash for the third argument (the select options), and then a hash with TWO key/value pairs for the fourth argument (the html options):
{ class: "class_name", data: { the: data, hash: here } }

(Note, I intentionally didn't feed you the full answer, because I feel that you're the sort of person who will benefit from discovering it on your own, but say so if I've misjudged, happy to edit this answer if you need it)
Comment: Thank you very much for your thorough explanation: very instructional and helpful. Problem solved, indeed.


Graphical interpretation of $f(z)=\sqrt{9-z^2}$ at purely imaginary numbers.

Question: Consider the function $f(z)=\sqrt{9-z^2}$. When $z\in\mathbb{R}$, the graph of the function is:

When $z$ is purely imaginary, such as $z=5i$, how can we interpret the function graphically? I assume that it is possible to take such a domain of $f$ since $(9-z^2)\geq0$ when $z$ is purely imaginary.
Please let me know if my question or assumption is wrong.
Comment: Wolfram alpha does this for you http://www.wolframalpha.com/input/?i=sqrt(9-(it)%5E2)
Comment: In order you have a true problem on imaginary numbers you can not try just with $z^2$.
Comment: @Piquito I don't think all imaginary numbers can be the domain.
Comment: I mean your problem as it has been posted is almost evident, too easy.
Comment: @Piquito Yes, now I feel so too. But sometimes even easy things are complicated by the head. Thanks for help!
Comment: @Kappa.- You are right, what you say is true.
Answer: Hint: if $z=it$ with $t \in \mathbb R$, then $f(it)=\sqrt{9+t^2}$.


Google Analytics vs ddos

Question: What i'm wondering is, what kind of behaviour does google analytics show when a ddos attack occurs? Any theories?
Answer: My theory would be that an effective DDoS platform/script would not include anything as heavyweight as a JavaScript engine, and that therefore the DDoS activity would not show up in Google Analytics at all.
The point of a DDoS attack is to overwhelm the server with a flood of requests.  Any CPU cycles that are spent evaluating JavaScript in the response that the server sends back are cycles that could better be used churning out more requests to the server.  I would fully expect a properly executed DDoS attack to not waste time parsing the response from the server, or even reading it off of the underlying socket, let alone interpreting and executing and JavaScript that may be embedded in the markup or fetching scripts and other resources from domains other than the target server.
Of course, this does not preclude the possibility of an exceptionally naive DDoS attack implemented using web frameworks and libraries that do evaluate embedded JavaScript.  Such an attack would not (or rather, should not if you've implemented your server code correctly) be very effective, but it would likely generate a spike in Google Analytics traffic.
Answer: It depends on the way that the DDOS is implemented. If it's simply an executable distributed to multiple machines, making simple HTTP queries using native TCP sockets, then Google Analytics wouldn't notice anything at all: because the JavaScript that gets returned would never be executed.
However, other sorts of DDOS attacks could leverage actual browsers distributed across many machines. For instance, if you could hack the Yahoo home page and insert an  into it, you could easily DDOS "takemedown.com". In this particular scenario, GA would certainly detect the impressions, and because (depending on the scenario) there might be an HTTP referrer tag, you could possibly run a report in GA that could pull out the suspicious impressions.
But there are other similar scenarios that wouldn't leave any particular footprints. For instance, if you could hack Lady Gaga's twitter account, you could send out a link to her 16MM followers, and a significant number would immediately click on it: and since most of those clicking on it would probably be doing so from within a separate app, there wouldn't be any referrer tag, and no particular way of identifying the requests.
In other words, it all depends, but it's probably not a terribly useful avenue to investigate. In many (most?) scenarios, GA wouldn't even recognize the impression; and in many others, wouldn't have any reasonable way of picking out the good impressions from the bad.
Answer: It will show up 100%  some significant  peaks in google analytics , simply because there are huge number of requests from multiple sources having huge bounce rate !
Answer: When a HTTP DDoS attack occurs the attacker is either using several (thousands) of computers to do so. Sometimes, it's also done with servers. When they make the request, they don't render the javascript or anything - they simply in most cases just make a GET request to the webpage.
So no, it shouldn't really have an impact on GoogleAnalytics
Answer: Well, I'm also searching this kind of information, but I have some considerations about the answer:
You will probably not see the attack itself with Google analytics, but you should see the results, I mean, a DDoS is a "distributed deny of service", so, if the service is effectively denied, then you should see a flat line on the graph on Google analytics.
Answer: It depends how the bot works, but here's what happened to my website:

Google Analytics real time report for the monk
As well as the increase in traffic you will likely see your bounce rate go sky high and average time on page significantly drop - which I'm sure can have a negative impact on SERPS.
For me it coincided with a Google update so first I put it down to that, but I started getting a lot of traffic to the root page, terms, and privacy, with many prefixed with /?m=0 which is in itself odd (and I'd love for someone to shed light).
The attack caused a great deal of timeouts and was painful to fix:
In short, I hooked up CloudFlare, then created Security -> WAF rules to challenge countries where I was receiving most of the bot traffic. I also switched on the basic bot attack mode (there's a more effective super bot attack mode with the paid subscriptions).
The other interesting point of note was why was my site subject to a DDOS attack. I wish I knew, but at a similar time to when the attack started I was approached by someone who enquired about buying the website. Possibly a tactic to get me to sell it/sell it cheap.

Google Analytics vs ddos


download pdf from ajax post

Question: I want to download a pdf file via a jquery post. I tried this:
$('#downloadPdf').click(function() {
    var id = $('#fileId').val();

    $.ajax({
        type: "POST",
        url: "includes/download_pdf.php",
        data: 'file_id=' + id,
        complete: function(data) {
            $('#pdf_results').html(data.responseText);
        }
    });
});

Code PHP:
<?php
    $file_name = $_POST['file_id'];
    // We'll be outputting a PDF header('Content-type: application/pdf');
    // It will be called downloaded.pdf header('Content-Disposition: attachment; filename="'.$file_name.'.pdf"');
    // The PDF source is in original.pdf readfile('/var/www/vhosts/domain.nl/private/'.$file_name.'.pdf');
?>

When I use this code I get all strange signs in #pdf_results. I want to save the PDF to my computer but this doesnt work.
Somebody knows how to fix this?
Thanks in advance!
Comment: you are trying to output the raw pdf as html. That won't work. You cannot start a download this way. Do you want the user to see a download dialog or should the pdf be display in that html element?
Comment: possible duplicate of [POST to server, receive PDF, deliver to user w/ jQuery](http://stackoverflow.com/questions/2186562/post-to-server-receive-pdf-deliver-to-user-w-jquery)
Comment: @Fender I want to see a download dialog.
Comment: without leaving the page, right?
Comment: you can't achieve this because ajax can't handle this nicely asynchronously. PDF is not character data. It's binary data. you'll have to use other trick like a .click(); event on the  of the pdf and manage it server side if you need something different.
Answer: You don't need to use AJAX for this. Try to use something like this:
$(function(){
    $('#downloadPdf').click(function(){
        var id = $('#fileId').val();
        window.open(location.protocol + '//' + location.hostname + '/includes/download_pdf.php?file_id=' + id);
        return false;
    });
});

Cheers!
Comment: This is not a POST request.
Answer: There is no need for ajax here.
Try using Rory McCrossan's solution:
POST to server, receive PDF, deliver to user w/ jQuery
Either use the plugin or simply link to the file and make sure your server sends the correct headers (else you can read the file with php and output it from there: http://www.saschakimmel.com/2009/05/php-prompt-the-user-to-download-a-specific-file/)
Answer: Have an invisible  on the page, and create a <form> with attributes method="POST" action="includes/download_pdf.php" target="name_of_the_iframe", add a <input type="hidden" name="file_id" value="the_value"/> into it, and submit it.
All of the above can be done all in JavaScript without the need to put that kind of markup into the page, to keep things clean. And none of this is ajax.
Answer: You need to achieve this :
I didn't really trace your program but you need the content disposition line in your php to make it work.
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
**header('Content-Disposition: attachment; filename="downloaded.pdf"');**

// The PDF source is in original.pdf
readfile('original.pdf');
?>

check the manual here
Also you can move the file over onto an iframe but that's a security risk, hence another topic.
Comment: Good answer, the key is `attachment`, and to download it with javascript: `window.location = "includes/download_pdf.php"`;

download pdf from ajax post


How to apply patch file to views module in Drupal 7

Question: I have problem with my views module. In some occasions it displays this deterrent warning:
Notice: Undefined property: views_handler_field_field::$original_value in views_handler_field->render_text() (line 1118 of C:\wamp\www\novine\sites\all\modules\views\handlers\views_handler_field.inc).
I think I found the patch that could work and save me from this buggy thing. My problem is how to apply downloaded patch to views module. I placed patch file in views folder, cached site, and  nothing happened. That was obviously naive try.
Can someone help me and tell all applying patch procedure? Thanks in advance!
Answer: If it is a standard Drupal patch, you use a program named git (part of ambience in most Gnu/Linux configurations) to apply it.  The correct procedure is to first clone the newest released version of the project, apply the patch, then install the patched version in the views folder.  If the patch file is named views-bugfix.patch you download it, and then:
git clone --recursive --branch 7.x-3.x http://git.drupal.org/project/views.git
git apply -v views-bugfix.patch

In some cases, the patch is not for the released branch, but some other branch (this will be mentioned along with the patch).  In that case you need to clone this branch instead.
Source for this info.
If you're stuck in a Microsoft environment and don't have git here is something that may help you: Patching in Windows (haven't tested this myself - I don't do windows.)
Comment: Thank you, very much. I am going to investigate this in detail.


asp.net with load balancer

Question: I have created an ASP.NET-based relying party application and this application is deployed on farm-server where load balancing is enabled and sticky session is also used.
When request come from single server in that time its working fine but during the post back if request server is changed in that time it throws an exception "Key not valid for use in specified state".
I have tried to set same machine key on both server but still facing same problem.
I have found on net the alternative solution is set enableViewStateMac="false".
Can i use this, and what is demerit of this?
Comment: How is your session state stored? See Scott Hanselman's post http://www.hanselman.com/blog/LoadBalancingAndASPNET.aspx for different options.
Answer: To answer your question, according to MSDN:

This attribute should never be set to false in a production Web site.

(Of course, the default is also false ...) Which suggests to me that you want to be very careful doing this.
Can you include a link to the resource you found online that suggested you switch this off?
Next, according to an MSDN blog:

The problem is that if a POST back is performed and goes to a different server, you will get a nice little error message saying "Corrupt View State".
To fix this, you can either set enableViewStateMac to false in the  element or specify a common value for the validationKey attribute in the  element across all servers (in the farm).

Which suggests to me that, unless the error message has changed (quite possible), this isn't what you're running into.
Take a look at this accepted answer - https://stackoverflow.com/questions/686873/allowing-session-in-a-web-farm-is-stateserver-good-enough/687162#687162 - over on Stack Overflow to make sure you're setup correctly.
MSDN also has an article ASP.NET Session State Overview that discusses setting up session state.
At this point, I think it's a configuration issue. Changing machine.config should have restarted the app pools, so that's probably not the issue.

asp.net with load balancer


What is the equivalent of sess_count in Drupal 7

Question: As Converting 6.x modules to 7.x explained:

All session functions starting with sess_*, as well as session_save_session(), are now renamed to drupal_session_* or _drupal_session_*

I have to use sess_count() in my D7 module and naturally I used drupal_session_count() but I ended up having Call to undefined function drupal_session_count() fatal error. I also tried _drupal_session_count() with no luck. User session handling functions page for Drupal 7 didn't mention about this function neither.
Which function should I use in order to count how many users have sessions?
Answer: drupal_session_count() was removed from Drupal 7. I'm not sure what an equivalent would be other than writing your own function.
Looks like the user block has it's own query. And admin menu had to replace it too.
Answer: The drupal_session_count() was removed in drupal 7, but I suppose you could do a simple db_query like this:
 $session_count = db_query("SELECT COUNT(*) FROM {sessions}")->fetchColumn();

You could also look at the drupal_session_count() function and use something similar:
function drupal_session_count($timestamp = 0, $anonymous = TRUE) {
   $query = db_select('sessions');
   $query->addExpression('COUNT(sid)', 'count');
   $query->condition('timestamp', $timestamp, '>=');
   $query->condition('uid', 0, $anonymous ? '=' : '>');
   return $query->execute()->fetchField();
}


Why would one Meteor client collection behave different from what is shown in MongoDB?

Question: I've been happily inserting collection docs via the client console and browsing those docs in my app and my command-line MongoDB client, with no problems... until today, when I modified one of my collections with some new fields via the MongoDB shell and now I get very strange behavior.
Here are some results in command-line MongoDB:
meteor:PRIMARY> db.pieceSizes.find()
{ "_id" : "LzZxiwj2i32E9EGnm", "name" : "3C", "length" : 39, "width" : 25.5, "countedSF" : 7 }
{ "_id" : "AePXzKFgB7M8Ewnf2", "name" : "4C", "length" : 51, "width" : 25.5, "countedSF" : 9 }

However, when I look on the client, I basically see blank docs; when I run this in the JavaScript console:
PieceSizes.find()

... and then I expand the LocalCollection, I only see the _id, eg:
Object {_id: "LzZxiwj2i32E9EGnm"}

I get the same results for findOne.  Why would the client not see all the data, starting after I modified things in the shell?
I'm looking in the right DB because I can edit other collections and see data changes correctly on both ends.
I'd love to have a full explanation, but I'll settle for simply getting my app with working data again.
UPDATE: I saw that there's a Meteor update so I ran it to update to 0.7.0.1, and now it gets even stranger.  If I do a findOne for that doc, I get the following object:
Object {0: undefined, 1: undefined, 2: undefined, 3: undefined, 4: undefined, 5: undefined, 6: undefined, 7: undefined, 8: undefined, 9: undefined, 10: undefined, 11: undefined, 12: undefined, 13: undefined, 14: undefined, 15: undefined, 16: undefined, 17: undefined, 18: undefined, 19: undefined, 20: undefined, 21: undefined, 22: undefined, 23: undefined, 24: undefined, 25: undefined, 26: undefined, 27: undefined, 28: undefined, 29: undefined, 30: undefined, 31: undefined, 32: undefined, 33: undefined, 34: undefined, 35: undefined, 36: undefined, 37: undefined, 38: undefined, _id: "LzZxiwj2i32E9EGnm"}

That's right, it has key _id with the expected value like earlier but now also has keys 0-38 with undefined values.  But the MongoDB client still shows all the data I want (and no numbered keys).
So I figured I'd try to remove and insert my data again all on the client side, but when I perform an insert:
PieceSizes.insert({name:"1C", length:88, width:18, countedSF:10})
"YkgoAJehkyZmDbe7G"

... I end up with that output that looks like an ID ("YkgoAJehkyZmDbe7G") but no doc with that ID is defined (ie. findOne will not pull it up and a find will show a cursor with nothing like this ID in its results).  However, I can see a new doc on both browser console and command-line shell with nothing but an ID:
{ "_id" : ObjectId("52b7d0d81f4f910000000001") }

Note that it totally dropped all my other information.  Besides that, it has an ID that doesn't match the regular Meteor convention (ie. it created the typical Mongo ObjectId).  I suppose I can work with the ObjectId, but I cannot work if the client will not save any of my data nor read any of the extra data from what's already in the DB.
I guess the next step to try and export/import/reinstall data and tools.  Any workarounds welcome!
Comment: I didn't get it, is there a solution to solve this issue? I mean what should we do so browser mongo become sync with  server mongo?
Answer: There are a couple of things
When Meteor inserts a document it will use a string type _id such as LzZxiwj2i32E9EGnm. When its inserted from mongo its typically an ObjectID object such as ObjectId("52b7d0d81f4f910000000001").
You can do this in meteor if you want by setting the idGeneration option of your collection to MONGO for example:
 PieceSize = new Meteor.Collection('pieceSizes', { idGeneration : 'MONGO' });

The reason this is done as a string in Meteor is so that you can easily use strings in URLs and map them to a specific ID. Its a little bit trickier using ObjectIDs since you would have to convert them back and forth to strings.
The reason of what looks like to be why you only get the _id field is you have a fields option set but to nothing during a publish. You can test this is the case by adding back auto publish
 `meteor add autopublish`

There are a couple of things that can cause the behavior you have:
Not publishing correctly
If it works after this it means that your publish rule doesn't set the fields correctly or you aren't returning documents correctly on a transform it could be either.
You need something like this
 Meteor.publish("pieces", function() {
     return PiecesSize.find({}, fields: { name: true, length: true, countedSF: true });
 });

So that those particular fields are published. After this you can disable auto publish.
If you don't set fields correctly you only get _id fields.
Not returning on a transform
If it is a transform such as this (or even using a Collection instead)
Docs.find({}. {transform: function(doc) {
    doc.value2
    return doc
});

don't forget to use return at the end of the transform if you don't you also get fields of just _id as results.
If you think its none of these it could be database corruption or something. You could use meteor reset and get a fresh start on your database.
Comment: Thank you for the complete explanations!  However, I found one part of my problem is the length property: using that in the client will jack up the the way inserts work.  I'll explain more in another answer.
Comment: I didn't get it, is there a solution to solve this issue? I mean what should we do so browser mongo become sync with  server mongo?
Answer: I found it: using a 'length' property in your object will wreak havoc with the communication to/from the DB.
Looks like there are known issues with a 'length' field:
https://github.com/meteor/meteor/issues/594
Here are the symptoms.
Inserts via client code, eg. the browser's JavaScript console
Command: PieceSizes.insert({name:"1C", length:88, width:18, countedSF:10})
Return value (expected): a key (eg. "YkgoAJehkyZmDbe7G"), but one which isn't stored anywhere with the object and can't be used.
Stored info as seen in Mongo shell (unexpected): an object with a single field of _id, eg. { "_id" : ObjectId("52b7d0d81f4f910000000001") }
Stored info as seen in browser client (unexpected): an object with a single field of _id, eg. { "_id" : ObjectId("52b7d0d81f4f910000000001") }
Inserts via a Mongo shell on the server
Command: db.pieceSizes.insert({name:"1C", length:88, width:18, countedSF:10})
Return value (expected): none
Stored info as seen in Mongo shell (expected): an object with a generated _id, eg. { "_id" : ObjectId("52b85c2d42c8a8dc81bf0331"), "name" : "1C", "length" : 88, "width" : 18, "countedSF" : 10 }
Stored info as seen in browser client (unexpected): an object with one _id key and 88 keys named "0" through "87"; all have an undefined value.  (Note that there is a case where the _id is an ObjectId, possibly caused by a meteor upgrade in my case.)
Comment: I didn't get it, is there a solution to solve this issue? I mean what should we do so browser mongo become sync with  server mongo?


Rejection sampling - total probability of acceptance

Question: I am given the following pdf $$f(x)=3 x^{2}, \quad 0 \leq x \leq 1$$ which i need to simulate by using rejection sampling.
I have used the following code below in R.
PDF_function <- function(x){3*x^2}

c <- PDF_function(1)

curve(PDF_function, 0, 1)
abline(a = c, b = 0, col='red')

X = runif(4500, 0, 1)
U = runif(4500, 0, 1)

pi_x <- function(x) {
  new_x = 3*x^2
  return(new_x)
}

count = 1
accept = c()

while(count <= 4500 & length(accept) < 1000){
  test_u = U[count]
  test_x = pi_x(X[count])/(c*dunif(X[count],0,1))
  if (test_u <= test_x){
    accept = rbind(accept, X[count])
    count = count + 1
  }
  count = count + 1
}

hist(accept)

mean(accept)
var(accept)

integrate(PDF_function, 0, 1)

1/(1*3)

length(accept)/count

I am asked to compare the total probability of acceptance and compare it with the theoretical one. If I understand this correctly then by computing length(accept)/count I get the estimated probability of acceptance but what is the theoretical one? I think the theoretical one is the area of the pdf function over the total area (under the envelope). If I integrate my function from 0 to 1 I get 1 (obviously) and the total area is 1 * (f(1)=3) = 3. So the theoretical is 1/3 ~= 0.333. Is this correct?
Answer: Yes, the theoretical value is $1/3$, which is the area under the curve over the amplified proposal distribution area, which is uniform in your case. You're double-counting the count, so if you remove the additional count increment inside the conditional statement you'll obtain empirical acceptance ratio close to $1/3$.


Azure pricing in case web server VM and database VM are in different region

Question: My WebServer VM is in different region and Database VM is in different region. For example, let's say WebServer VM is in Singapore, and Database VM is in US-West.
Now if I get a POST request from a user, which hits WebServer in Singapore region that inserts data into the database which is in US-West region, will this request be charged for outbound data transfer from webserver VM?
Thanks In Advance
Answer: Yes, all data outbound traffic is charged.
You also must take into consideration the latency caused by doing such a transaction, and the possible security issue in exposing your database on the Internet.
Answer: Yes, the deployment as you described it would incur outbound data transfer charges.  You would see some cost from the web server (making the call to the database), and some cost from the database server (results going back to the web server).
Here is the pricing page for Azure that explains data transfer rates.  Notice that the rate varies by Zone.  In your example, it would be between Zone 1 and Zone 2.
http://azure.microsoft.com/en-us/pricing/details/data-transfers/


Authorization pop up while running spring boot application on tomcat 8

Question: Required Authorization for executing application, which I am not sure what I need to put
Popped up message: The server localhost is asking for username and password.The server reports that it is from spring.
Warning: Your username and password will be sent using basic authentication on a connection that is not secure
Answer: You should add security.basic.enabled=false in application.properties file and put it under src/main/resources path.


A Mysterious Consequence of Discrete Optional Sampling Theorem

Question: I'm trying to understand the proof of optional stopping theorem for continuous Martingales. They begin by recalling the equivalent fact for a Martingales that take values on a discrete set:

Recall the optional sampling theorem for stopping times $\alpha, \beta: \Omega \rightarrow {t_j}_{j \geq 1}$ ̨with values in a discrete set:
  $$(X(t_j),F_{t_j})_{j \geq 1} \text{ submartingale, } \alpha \leq \beta \leq C \implies X(\alpha) \leq E[X(\beta)|F_{\alpha}]$$

They proceed to use the statement in the proof of the continuous case:

Using the discrete version of optional sampling theorem with $\alpha = \sigma_j \wedge k$ and $\beta = \tau_j \wedge k$ reveals $X(\sigma_j \wedge k), X(\tau_j \wedge k) \in L^1(P)$ and $X(\sigma_j \wedge k) \leq E[X(\tau_j \wedge k)|F_{\sigma_j \wedge k}]$.

I see where the inequality comes from, but what about the assertion that $X(\sigma_j \wedge k), X(\tau_j \wedge k) \in L^1(P)$?
Comment: What is the definition of $\sigma_j, \tau_j$? I assume they are a special choice of stopping times. In particular, what values do the stopping times $\sigma_j$ and $\tau_j$ take?
Comment: My bad: $\sigma_j$ and $\tau_j$ are stopping times. Each can only take countably many values. This is why the "discrete" theorem can be invoked.
Comment: I am looking at A.18 in this book: https://books.google.com/books?id=Ph7oBQAAQBAJ&lpg=PA125&vq=be%20an%20open%20bounded%20Set.%20Then&pg=PA373#v=onepage&q&f=false
Answer: Here is a direct way to see integrability using the definition of $\tau_j$. The definition of $\tau_j$ given in your book (included here for completeness) is
$$\tau_j(\omega) = \begin{cases} \tau(\omega) \qquad \text{ if } \tau(\omega) = \infty, \\n2^{-j} \qquad \text{ if }(n-1)2^{-j} \leq \tau(\omega) < n2^{-j}
\end{cases}$$
where $\tau$ is some stopping time (the case of $\sigma_j$ will be similar so I just deal with $\tau_j$ here).
In particular, $\tau_j \wedge k \in \{ 2^{-j}n : n \leq 2^j k\}$. Hence $$|X(\tau_j \wedge k)| \leq \sum_{n=1}^{2^jk} |X(2^{-j}n)| \in L^1(P)$$
since, by assumption, $X(2^{-j}n) \in L^1(P)$ for each $n$. So $X(\tau_j \wedge k) \in L^1(P)$.
Comment: $X$ is a submartingale.
Comment: Part of the definition of a submartingale is that $X(t) \in L^1(P)$ for any $t \geq 0$.
Comment: Where's the assumption that $X(\frac{n}{2^j}) \in L^1(P)$?
Comment: Can you elaborate?


Squid never caching files using dnf

Question: I'm attempting to set up a local repository cache for dnf. The idea is for one machine on the network to download a package, then any other machine on the network attempting to acquire the package will receive it from the cache. I'm using squid for this, and currently have dnf requesting packages through the squid server, but squid is recording a miss every time. I'm unsure what is causing this, so I'll copy in the typical access.log message and relevant section of squid.conf.
1450150756.680    131 10.64.9.57 TCP_MISS/200 183815 GET
http://mirror.crucial.com.au/fedora/linux/updates/23/x86_64/l/libquadmath-5.3.1-2.fc23.x86_64.rpm -
FIRSTUP_PARENT/[parent-proxy-url] application/x-redhat-package-manager
[Host: mirror.crucial.com.au
User-Agent: dnf/1.1.4
Accept: */*
Proxy-Connection: Keep-Alive]
[HTTP/1.1 200 OK
Expires: Sun, 13 Dec 2015 22:57:47 GMT
Server: nginx/1.8.0
Date: Tue, 15 Dec 2015 03:39:07 GMT
Content-Type: application/x-redhat-package-manager
Content-Length: 183182
Last-Modified: Thu, 10 Dec 2015 20:53:32 GMT
ETag: "5669e64c-2cb8e"
Age: 0
Connection: keep-alive
Proxy-Connection: keep-alive
Via: 1.1 NZ8KS49CH
X-Cache-Lookup: HIT from NZ8KS49CH (M86 Security Proxy Cache)
X-Cache: HIT from NZ8KS49CH (M86 Security Proxy Cache)
X-WebMarshal-RequestID: C3F30882-D914-481F-8E60-2AD367A4A046]

And here's the conf:
cache_peer [parent-proxy-url] parent 8081 0 no-query no-digest proxy-only default login=[user]:[pass]

acl all src 0.0.0.0/0 ::/0
never_direct allow all
maximum_object_size 4096 MB
# Uncomment and adjust the following to add a disk cache directory.
cache_dir ufs /var/spool/squid 10000 16 256

# Leave coredumps in the first cache dir
#coredump_dir /var/spool/squid

cache_replacement_policy heap LFUDA

acl filetype urlpath_regex \.rpm
cache allow filetype
send_hit allow filetype
cache deny all

#
# Add any of your own refresh_pattern entries above these.
#
refresh_pattern -i .rpm$ 129600 100% 129600 refresh-ims override-expire
refresh_pattern -i .iso$ 129600 100% 129600 refresh-ims override-expire
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern .               0       20%     4320

I also noted that when I had it set up so my web browser was directed through squid, some things were cached. Once I set up the dnf only, nothing caches ever.
Comment: Exactly which version of squid are you using?
Comment: squid-3.5.9-7.fc23.x86_64
Answer: Figured it out. The cache_peer line included "proxy-only", which stops squid form caching anything from that peer. Removing the "proxy-only" term fixed the issue completely. I think I picked it up from some tutorial online which must have been attempting something different to me.

Squid never caching files using dnf


Pywintypes error when running an adodbapi package python query

Question: I am having difficulty installing adodbapi and running a script which uses SQL to connect and run a DAX query using adodbapi. I have run into this error on multiple machines.
Answer: The issue is due to an MSOLAP update. I have copied an old MSOLAP.dll file (version 15) and overwritten the newer one (version 16).
https://github.com/mhammond/pywin32/issues/1820


Lines on projective hypersurfaces of large degree

Question: My question refers to Exercise 11.3.J (c) from Ravi Vakil's The Rising Sea: Foundations of Algebraic Geometry:
"Throughout, we work over an algebraically closed field. […]
If $d\geq n$, show that for "most hypersurfaces" $X$ of degree $d$ in $\mathbb P^n$ (for all hypersurfaces whose corresponding point in the parameter space $\mathbb P^{{{n+d}\choose d}-1}$ — cf. Remark 4.5.3 and Exercise 8.2.K — lies in some nonempty Zariski-open subset), "most points $p\in X$" (all points in a nonempty dense Zariski-open subset of $X$) have no lines in $X$ passing through them. (Hint: first show that there is a single $p$ in a single $X$ contained in no line. Chevalley's Theorem 7.4.2 may help.)"

In (a) from the same exercise a method is explained to check if through a given point on $X$ with special (nice) coordinates there is a line contained in $X$: Essentially, one has to check $d$ many conditions.
Part (b) is on the case $d\leq n-1$, where through each point of $X$ there does exist a line contained in $X$.
Both (a) and (b) are clear to me. Also, (c) does at least seem plausible to me, as there are simply too many conditions for such lines to exist in general. I could imagine that for (c) one has to work with some "incidence scheme(s)". But how can (c) be solved rigorously?
What puzzles me furthermore is Vakil's hint "first show that there is a single $p$ in a single $X$ contained in no line": I think it is easy to prove this hint, but it is so much weaker than the full claim, therefore I do not understand how it could be helpful.
Finally, Vakil gives another hint, namely that Chevalley's Theorem may help. Unfortunately, I do not see to what map Chevalley's Theorem should be applied here.
Answer: Let $p$ be the point $(1:0:\dots:0) \in \mathbb{P}^n$ and let $(x_0:x_1:\dots:x_n)$ be the homogeneous coordinates. The equation $f(x)$ of a hypersurface $X$ passing through $p$ can be written as
$$
f = x_0^{n-1}f_1(x_1,\dots,x_n) + x_0^{n-2}f_2(x_1,\dots,x_n) + \dots + f_n(x_1,\dots,x_n),
$$
where $f_i$ is a homogeneous polynoimal of degree $i$.
Lines through $p$ that lie on $X$ correspond to the solutions of the system of equations
$$
f_1(x_1,\dots,x_n) = f_2(x_1,\dots,x_n) = \dots = f_n(x_1,\dots,x_n) = 0.
$$
Now if $f_i$ are chosen generically, this system has no solutions. Indeed, for example you can take
$$
f_1 = x_1,
\quad
f_2 = x_2^2,
\quad \dots, \quad
f_n = x_n^n.
$$


Accepting binary data in asp net controller

Question: I am struggling with binding of binary data sent in the body of http request.
I have the following controller in Asp Net core (NetCore 2.1):
    [HttpPost]
    [Consumes("image/png", System.Net.Mime.MediaTypeNames.Application.Pdf, System.Net.Mime.MediaTypeNames.Image.Tiff)]
    [Route("test")]
    public IActionResult Test(IFormFile file)
    {
        return Ok(file.Length);
    }

The aim is to receive the stream of byte and bind it to a parameter named 'file'. The problem is that the IFormFile variable is null. In fact by placing a breakpoint inside the controller, the Route works perfectly but it raises a null pointer exception as soon as I try to access 'file' variable.
My doubts are concerned with the way it works. If I access to Request object I am able to read the stream of data without problems. But I don't think it is the right way to do this.
Example:
    [HttpPost]
    [Consumes("image/png", "image/bmp", System.Net.Mime.MediaTypeNames.Application.Pdf, System.Net.Mime.MediaTypeNames.Image.Tiff)]
    [Route("test")]
    public IActionResult Test(IFormFile binary)
    {
        var x = new System.Drawing.Bitmap(Request.Body);
        x.Save(".\\file.bmp");
        return Ok("Image height: " + x.Height.ToString());
    }

How can I bind the data sent as binary inside my controllers?
The following is an example of request sent by postman:
postman screenshot
raw request
P.S. I am bonded to receive data as binary although I know that it would be better to receive it inside a multipart-form
Comment: If you want to bind binary to IFormFile binary,you can try to use [custom model binding](https://learn.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding?view=aspnetcore-2.1).
Comment: @YiyiYou thanks for the suggestion but I have definitely found what I was looking for
Answer: Just found the solution right there: https://weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers?Page=2
What I was looking for was a way to bind the raw Request.Body Stream to a parameter of the controller and it was so easy.
I have just created a custom formatter as below:
public class RawRequestBodyFormatter : InputFormatter
{
  public RawRequestBodyFormatter()
  {
    SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/bmp"));
  }

///
/// Allow image/bmp and no content type to
/// be processed
///
/// <param name="context"></param>
/// <returns></returns>
public override Boolean CanRead(InputFormatterContext context)
{
    if (context == null) throw new ArgumentNullException(nameof(context));

    var contentType = context.HttpContext.Request.ContentType;
    if (string.IsNullOrEmpty(contentType) || contentType == "image/bmp")
        return true;

    return false;
}

///
/// Handle bmp images
///
/// <param name="context"></param>
/// <returns></returns>
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
    var request = context.HttpContext.Request;
    var contentType = context.HttpContext.Request.ContentType;

    if (string.IsNullOrEmpty(contentType) || contentType == "image/bmp")
    {
        return await InputFormatterResult.SuccessAsync(request.Body);
    }

    return await InputFormatterResult.FailureAsync();
}

And then added the respective option to my app
services.AddMvc(options =>
            options.InputFormatters.Insert(0, new
RawRequestBodyFormatter())

Now the following Controller is fully working!
[HttpPost]
[Consumes("image/png", "image/bmp", System.Net.Mime.MediaTypeNames.Application.Pdf, System.Net.Mime.MediaTypeNames.Image.Tiff)]
[Route("test")]
//[JwtAuthenticationAttribute]
public IActionResult Test([FromBody]Stream file)
{
     var x = new System.Drawing.Bitmap(file);
     x.Save(".\\file.bmp");
     return Ok("Image height: " + x.Height.ToString());
}