Calculating Bias in R

Question: Write a simulation experiment to estimate the bias of the estimator λˆ= 1/ X¯ by sampling using x=rexp(n,rate=5) and recording the values of 1/mean(x). You should find that the bias is λ/n−1. Here we've used λ = 5 but the result will hold for any λ. Here is my solution ( I dont get λ/n−1). Am I doing something wrong here?
<code>set.seed(1)
lambda <- 5
x <- rexp(n= 1e5, rate = lambda )
samp.mean <- mean(x)
lam.est <- 1/samp.mean
lam.est ##4.986549

bias <- abs(lambda - lam.est)
bias ##0.01345146
</code>
Comment: Please add the [tag:self-study] tag & read its
[wiki](https://stats.stackexchange.com/tags/self-study/info). Then tell us what you understand thus far, what
you've tried & where you're stuck. We'll provide hints to
help you get unstuck. Please make these changes as just
posting your homework & hoping someone will do it for you
is grounds for closing.
Comment: +1. There is a fascinating and deep statistical question lurking here: although the bias indeed is $\lambda/(n-1),$ as $n$ grows large it becomes increasingly likely that the bias *as estimated in the dataset* will differ appreciably from its expectation by an amount that grows more slowly than $1/n.$ Consequently, *computer simulation can be misleading.* I recommend studying a *running estimate* of the bias, suitably scaled, as in `lambda <- 5;
x <- rexp(1e4, rate=lambda);
m <- seq_along(x) / cumsum(x) - lambda;
plot(m * (seq_along(x)-1), type="l");
abline(h=lambda)`
Answer: Your issue stems from the fact that you only ran one simulation. Recall that the formal definition of the bias of an estimator is :
$$ Bias(\hat{\theta}) = E(\hat{\theta})-\theta $$
In a simulation you approximate the expected value of your estimator by its sample mean.
Here is some R code to get what you want :
<code>> set.seed(1)
> lambda <- 5
> n <- 50
> X <- matrix(rexp(n*1e5, rate = lambda),n)
> samp.mean <- apply(X,2,mean)
> lam.est <- 1/samp.mean
>
> bias <- abs(lambda - mean(lam.est))
> bias
[1] 0.1001163
> # Approximately equal to lambda/(n-1) and will be if n -> infty
</code>
Comment: The correct way indeed includes a look at multiple estimates (and the coding is, I believe, something that the author should have tried figuring out themselves). But the correct way would be to also estimate the variance of the estimate. Just the difference is not enough.
Comment: I am not sure whether you meant to give a complete answer or just a hint, but comparing just the difference between the mean of estimates from several tests and $\lambda$ is one step towards a final answer but not enough.
Comment: Indeed this is not a full answer and I only provide the author an estimate of what the bias of the MLE of an exponential is. I provided some code to show the author what is the correct way to estimate this bias as he or she seems to be a new contributor.
Answer: You computed the outcome of only a single test.
Could you instead write a program that repeats this test a lot of times. Then look at how the distribution of the estimates is. Is the distribution of the estimates centered around $\lambda$ or is there a bias?

Calculating Bias in R


Set terminology and symbols in optimization

Question: Coming from engineering background, I'm getting a little lost in terminology and symbols, but I still want to be mathematically precise.
In engineering optimization, I often have say two design variables, where a variable is a set of possible alternative values that dictate the value of a design (a mapping from design space to objective space);
\begin{equation}
\begin{aligned}
X_1 &= {1, 3, 4} \
X_2 &= {1, red, black}\
\end{aligned}
\end{equation}
This would define a design space $\Theta = \{X_1,X_2\}$. And $\Theta \rightarrow \Omega$, where $\Omega$ is the objective space. i.e. $\left|\Omega\right| = \Re$ in single objective optimization.
How do I express the "`size"' of this design space? I believe it's true to say that the cardinality (and magnitude? same term?) of the design space is $\left|\Theta\right| = 2$. But I am also concerned with the total number of design vectors in this finite space, say $\theta$. In this case, there are  $\left|X_1\right| \times \left|X_2\right| = 9$ possible design vectors, or combinations of 2-tuples.
In general, for $m$ variables, the number of vectors is $\theta$;
\begin{equation}
\begin{aligned}
\theta = \prod_{i=1}^{m} \left|X_i\right|
\end{aligned}
\end{equation}
Is there a cleaner or more recognizable way to represent $\theta$? is the above description and choice of symbols common? I've looked at several texts on optimization, but haven't found any that really express it in this way.
Answer: If you want to present the "size" with terminology rather than in symbolic form, you can refer to the design space as the Cartesian product of the design variables.  In your example there are two design variables, each with three value alternatives, and in the absence of any constraints that prevent arbitrarily pairing those values, the Cartesian product gives the design space with a total of $3 \times 3 = 9$ possibilities.
Comment: Exactly what I was looking for, thanks!


Is there any point to regular phrase lengths?

Question: I have gotten several comments on my scores saying that they would be better if I had regular or at least even numbered phrase lengths. But what is the point of say sticking to 8 bar phrases for a composition? There are plenty of phrases which are an odd number of measures long. You don't have to look any further than Beethoven's 5th symphony to find a phrase like that.

This is the opening phrase of Beethoven's 5th. As you can see, it is 5 measures long. It also sounds like a question and answer in octaves, with the answer still being incomplete until the second phrase enters and the motif is developed. So you could say this phrase is a period within a sentence that is itself part of a theme. I have tried sticking to 8 bar phrases and I find that because the last 2 measures of an 8 bar phrase are expected to be cadential, I find that my creativity as a composer goes down and I rely more on modulation than on rhythm or anything else that is important other than the notes themselves when I use regular phrase lengths. Is it really worth it if sticking to 8 bar phrases means my creativity lowers?
And even if it didn't have to do with my creativity, is there really a point to sticking to even numbered or regular phrase lengths when you could easily get the essence of an even numbered length phrase in an odd numbered length phrase by simply shortening the cadential part of the phrase?
Comment: Beethoven 5 is a poor example: here it's stating a motif, which will be used extensively. It's hardly a tune in itself, just a statement, and the '5 bars' are there to underline the last note, not really to make it 5 bars long, as actually, with fermata, it's nearer 6. Which pretty well makes it even...
Comment: If the comments come from experienced person whose skills as composer you admire then it might make sense to assume, that this is at least a good advice on how to improve that particular piece. No rule is categorical but in a school situation if you do go outside of some guidelines it'd better be for a good reason
Comment: I agree with Tim that Beethoven's 5th is a poor example, but for a different reason. It's mainly in the relaxed segments that the phrasing is uneven. Most of the time it sticks to 4-bar phrasing.
Comment: I've realized something about feedback on creative works: When someone mentions some random thing they think you should do differently, all that means is that they didn't love what you wrote and they are trying to come up with some reason *why* they didn't love it. The real reason is they just didn't love it. The reason they say is just some random rationalization. If they loved it, they wouldn't have said anything random about what you should do differently. All you can take away from feedback like this is, they just didn't love it.
Comment: So, getting feedback saying that I should use regular or even numbered phrase lengths has nothing to do with the phrasing itself and that kind of feedback I should just ignore and not try to change my music to fit the feedback?
Comment: I've heard of pieces that stubbornly stick to 7-bar phrases (e.g. a Haydn work I can't remember anything else about) or 5-bar phrases (e.g. Brahms's Rhapsody in E Flat Major, Op. 119, No. 4). At least those were earnest about sticking to their unorthodox phrase lengths. Ragged phrase lengths, especially if those lengths change every phrase, often give me the impression that the composer does not know what s/he is doing.
Comment: But it isn't like I can know from just posts alone whether or not the person who commented "the piece would be better if you did x thing" is experienced or not.
Answer: Yes, that Beethoven phrase you included is technically 5 bars, but the binary nature of it is so very clear. There are two, two-bar segments. Given the fermatas, the 5th bar seems clear enough an explicitly written emphasis to hold the last note a long time. I view it as 2+2+1 not 2+3. The regularity and symmetry then come from the 2+2 aspect and - in my view - the extra +1 doesn't change that.
Having said that, it sounds like someone is telling you to make everything divisible by 2, and my guess is they are telling you that is classical style.
Well, sort of 'yes'. Certainly lots and lots of classical music is in regular, even numbered phrases. But, could form genres have any relevance? (Hint: yes, the particular form matters.)
A classical minuet very commonly is phrased with even numbers of bars. But, a sonata can exhibit lots of different phrase lengths.
You may be interested to read this chapter from a classical era theorist named Riepel. In it various phrase lengths are discussed and given the names: zweyer, dreyer, and vierer, which respectively are 2, 3, and 4 bars in length. Riepel is super-sensitive to the idea that minuet phrases should be even, but says other phrase lengths are appropriate in a sonata.
Comment: Regular phrases are a feature that the minuet shares with most dance forms.  I would view the opening of the Fifth rather as an augmented statement of the one-bar motive.  It is out of time (note the fermatas), with the extra measure conveying that the last note should be longer than the fourth.  This seems much more about rhetoric than rhythmic proportion or balance.
Answer: No, there's no automatic virtue in using regular phrase lengths.
Maybe the structure of your music works well, maybe it doesn't.  We'd have to see some of it.
Answer: You can find music with predictable phrase lengths and music with quite the opposite. For example, the Chopin scherzos are very much in four-bar phrases, while in many works by Brahms the phrasing is very subtle. In both cases there are celebrated and "successful" works.
There is a tendency toward regularity of phrase length. This can be a larger-scale form of rhythm: instead of (or in addition to) feeling a regular pulse of beats at a relatively short time scale, we feel a regular pulse of phrases at a relatively long time scale. This regularity might become monotonous without variation. On the other hand, if every phrase is a different length, then a listener sensitive to this kind of rhythm might feel the music is disorderly or confusing. Those are the two extremes. In between, you have the vast majority of music which tends toward regularity but with some freedom.
Consider a forte in a passage mostly piano, or a highly chromatic chord in an otherwise harmonically sterile passage. So with phrasing: if you allow a tendency toward regular phrase lengths, then diverging with occasional phrases of different lengths becomes an expressive device that is unavailable if phrase length cannot be predicted.
All these comments consider the general case rather than specific cases. As for your specific piece, if it works it works.
Answer: Much depends on the point of the music. Dance music needs regularity as dancers use patterns that span several measures. Likewise, as noted in an other answer, the rather common four-measure phrase acts more like a unit rather than separate measures. The structure over many measures tends to be divided into groups of four-measure phrases.
Answer: Possibly the same reasoning behind our preference for counting 4 in a bar? It literally 'evens things up', and has a more satisfying feel to it. 5/4 time is used in a few t.v. themes - Mission Impossible is one - as it gives a feeling of suspense. If that's what you want for your music, that sort of concept works well. For music that you'd rather have the listener calm and enjoying the tranquility, that just won't work as well as 4 or 6.
Stretch it all out into stanzas and phrases, the same principal often applies.
Answer: Regular phrase structures are regular for a reason. You are going to have to resort to unusual chord progressions if you use odd phrases, most chord progression work off 4 steps forward,  3 steps back or one step forward. Thismeans you are often working off 4 steps making 8 bars an easy and effective way to start and end on the tonic.
Although odd phrases and unusual chord progressions are not impossible I have to wonder why you would want to do that. They add nothing to the musicality of your piece and complicate your compisition for no good reason.
Comment: But sticking to regular phrase lengths really limits what I can do. For example, if I were to do 8 bar phrasing, and modulate from C to Cm, this is what would be expected: Bar 8: G7 -> C Bar 9: Cm Without this limitation of regular phrasing, I can easily end a phrase on the parallel minor without using the dominant there and instead just directly go from 1 tonic chord to the next. And I actually find it easier to compose when I don't limit myself to regular phrasing.


Calcular distância entre 2 pontos no Google maps

Question: Não tenho muita experiência com javascript e não tenho ideia de como pegar o resultado desse script e passar para um campo <input text>.
Esse script calcula a distância e o tempo entre dois pontos. Então queria pegar o tempo e a distância e então salvá-lo em um banco de dados.

<title>Calcular distancia entre cidades (mapas e rotas)</title>

       Endereço de origem
       <input type="text" id="txtOrigem" class="field" style="width: 400px" />
       Endereço de destino
       <input type="text" style="width: 400px" class="field" id="txtDestino" />
       <input type="button" value="Calcular distância"  onclick="CalculaDistancia()" class="btnNew" />

    <input type="text" value="<? Variavel distancia?>"
    <input type="text" value="<? Variavel tempo?>"

Comment: Só dando uma olhada por cima, eu vi que há um elemento `` não-fechado que não contém linhas e colunas dentro dele. Isso está certo? Além disso, o seu HTML não está completo, uma vez que não tem o `` e nem o ``.
Comment: Mais Ta funcionando sim. Na verdade ele não vai ter nem tabela
Answer: Acho que consegui resolver.
Primeiro eu corrigi os problemas com a HTML mal formada: Está faltando o  e o  no final, que acrescentei. Você tem um elemento
 sobrando que é inútil, e eu o removi. Você está quebrando linha dentro do atributo src do  e isso é ruim,  e eu não quebrei linha ali. Além disso, eu acrescentei o <!DOCTYPE html> e o <meta charset="utf-8">. Por fim, dei um jeito em alguns escapes que estavam faltando (â para â e ã para ã).
Depois, eu acrescentei os campos onde o resultado será colocado. Também separei-os dos campos onde a pesquisa é realizada. Fiz os campos do resultado serem somente-leitura para garantir que o resultado deles de fato venha do Google (no entanto, não confie nisso se você for disponibilizar para o público em geral). Coloquei todos eles dentro de um <form> com um botão submit para poder enviar ao servidor posteriormente:

EDIT: Em 11/06/2018, mais de três anos depois da data em que esta pergunta e esta resposta foram postadas, o Google mudou o formato da API. Até então, era possível utilizar a API gratuitamente sem necessitar de uma API Key. Com a mudança, torna-se necessário o uso de uma API Key, que só pode ser ativada com um cartão de crédito. Veja mais neste link, nesta página e aqui. Nos códigos que se segue, substitua o API_KEY_AQUI pelo valor do seu API Key. E para usar o seu API Key, você deverá ativá-lo.

    <form action="http://www.example.com/url" method="post">

Pesquisa:

      Endereço de origem
      <input name="pesquisaOrigem" type="text" id="txtOrigem" class="field" style="width: 400px" value="São Paulo" />
      Endereço de destino
      <input name="pesquisaDestino" type="text" id="txtDestino" class="field" style="width: 400px" value="Rio de Janeiro" />
      <input type="button" value="Calcular distância" onclick="CalculaDistancia()" class="btnNew" />

Resposta:

      Endereço de origem
      <input name="resultadoOrigem" readonly="readonly" type="text" id="txtOrigemResultado" class="field" style="width: 400px" value="" />
      Endereço de destino
      <input name="resultadoDestino" readonly="readonly" type="text" id="txtDestinoResultado" class="field" style="width: 400px" value="" />

      Distância
      <input name="distancia" readonly="readonly" type="text" id="txtDistancia" value="" />
      Tempo
      <input name="tempo" readonly="readonly" type="text" id="txtTempo" value="" />
      <input type="submit" value="Enviar para o servidor" />
    </form>

Arrumei o javascript para preencher estes campos no callback. Já aproveitei para retirar o "aguarde" quando a resposta chegar e também traduzi o tempo para o português.
      // Tratar o retorno do DistanceMatrixService
      function callback(response, status) {
        // Verificar o status.
        if (status != google.maps.DistanceMatrixStatus.OK) { // Se o status não for "OK".
            $("#litResultado").html(status);
        } else { // Se o status for "OK".
            $("#litResultado").html(" "); // Remove o "aguarde".

            // Popula os campos.
            $("#txtOrigemResultado").val(response.originAddresses);
            $("#txtDestinoResultado").val(response.destinationAddresses);
            $("#txtDistancia").val(response.rows[0].elements[0].distance.text);
            var tempo = response.rows[0].elements[0].duration.text;
            tempo = tempo.replace("day", "dia").replace("hour", "hora").replace("min", "minuto");
            $("#txtTempo").val(tempo);

            //Atualizar o mapa.
            $("#map").attr("src", "https://maps.google.com/maps?saddr=" + response.originAddresses + "&daddr=" + response.destinationAddresses + "&output=embed&key=API_KEY_AQUI");
        }
      }

Eis o HTML completo:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Calcular distância entre cidades (mapas e rotas)</title>

    <form action="http://www.example.com/url" method="post">

Pesquisa:

      Endereço de origem
      <input name="pesquisaOrigem" type="text" id="txtOrigem" class="field" style="width: 400px" value="São Paulo" />
      Endereço de destino
      <input name="pesquisaDestino" type="text" id="txtDestino" class="field" style="width: 400px" value="Rio de Janeiro" />
      <input type="button" value="Calcular distância" onclick="CalculaDistancia()" class="btnNew" />

Resposta:

      Endereço de origem
      <input name="resultadoOrigem" readonly="readonly" type="text" id="txtOrigemResultado" class="field" style="width: 400px" value="" />
      Endereço de destino
      <input name="resultadoDestino" readonly="readonly" type="text" id="txtDestinoResultado" class="field" style="width: 400px" value="" />

      Distância
      <input name="distancia" readonly="readonly" type="text" id="txtDistancia" value="" />
      Tempo
      <input name="tempo" readonly="readonly" type="text" id="txtTempo" value="" />
      <input type="submit" value="Enviar para o servidor" />
    </form>

Para usar, você deve proceder assim:

Você escolhe os locais desejados e os preenche nos campos de pesquisa.
Clique no botão "Calcular distância".
O Google trará o resultado.
O javascript preencherá os campos do formulário com os resultados.
Você clica no botão "Enviar para o servidor" e os dados do formulário serão enviados ao servidor.

No servidor, você vai receber uma requisição POST contendo os seguintes campos de formulário: pesquisaOrigem, pesquisaDestino, resultadoOrigem, resultadoDestino, distancia e tempo. O significado de cada um deles é óbvio. A URL responsável por receber este serviço deverá ser configurada no seu servidor e o campo action do seu <form> no HTML deve coincidir com ela.
Se preferir, você pode fazer com que a resposta OK do Google já submeta o resultado via AJAX para o seu servidor automaticamente. Ou então você pode querer colocar alguma lógica de validação mais complexa no seu botão "Enviar para o servidor". Neste caso, se você tiver alguma dúvida de como fazer isso, já fica para o escopo de uma outra pergunta, mas nada te impede de adaptar este processo como lhe convier.
Já no servidor, você executará um prepared statement com uma instrução SQL mais ou menos assim:
INSERT INTO Distancias (pesquisaOrigem, pesquisaDestino, resultadoOrigem, resultadoDestino, distancia, tempo) VALUES (?, ?, ?, ?, ?, ?)

Ou simplesmente assim:
INSERT INTO Distancias (origem, destino, distancia, tempo) VALUES (?, ?, ?, ?)

E então é só preencher os parâmetros do seu prepared statement com os dados recebidos do formulário. No entanto, antes de fazê-lo, talvez você queira pré-processá-los para converter todos os tempos em minutos, converter todas as distâncias em valores numéricos (eliminando o sufixo " km"), e talvez dando alguma arrumada na origem e no destino caso queira eliminar informações que você julgue desnecessárias como número de rua, CEP, diferenças entre maiúsculas/minúsculas, ou o que você quiser.
Comment: muito bom o que vi aqui, tive a resposta que procurava!
Comment: eu estou usando seu código em um sistema, mas estou com um problema, está retornando um erro após alguns testes que fiz, esperei 10 min e o erro continua: OVER_QUERY_LIMIT


Getting collection document protected by uid via where does not work

Question: In my application, once the user is logged in via Firebase auth, I want to fetch additional data from my firestore database.
I do not want users to be able to look at other user's documents, therefore I created a rule for this:
match /users/{userId} {
  function isAuthenticated() {
    return request.auth != null;
  }

  function userIsSelf() {
    return request.auth.uid == userId;
  }

  allow read: if
  isAuthenticated()
  && userIsSelf();
}

In my head, what I wrote should in theory allow the current logged in user to see data only about himself, and this worked fine in the "rules playground".
However, when I try this code in in the app, I get an error: FirebaseError: Missing or insufficient permissions.
I think this has something to do with the way firestore fetches the data?
The way I query this is by fetching the collection users with a where that only returns users that has uid same as logged in user:
const querySnapshot = await firebase.firestore().collection("users").where("uid", "==", uid).get().catch(err => {
    console.error('could not fetch user', err)
})

if (!querySnapshot || querySnapshot.empty) {
    dispatch('logout')
    throw new Error('Cannot find logged in user\'s data in database')
}

const userData = querySnapshot.docs[0].data()
commit('setUser', userData)

I created my firestore rules to look like this:
rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {

    function isAuthenticated() {
      return request.auth != null;
    }
    function isAdmin(uid) {
      return get(/databases/$(database)/documents/users/$(uid)).data.role == 'admin'
    }

    // Allow admin to do everything
    match /{document=**} {
        allow read, write: if isAdmin(request.auth.uid)
    }

    // Only allow users to read/write to themselfs
    match /users/{userId} {

      function userIsSelf() {
        return request.auth.uid == userId;
      }
      function roleIsUserOrSameAsDocument() {
        return request.resource.data.role == 'user' || request.resource.data.role == resource.data.role;
      }

        allow read: if
        isAuthenticated()
        && userIsSelf();

      allow write: if
        isAuthenticated()
        && userIsSelf()
        && roleIsUserOrSameAsDocument();
    }
  }
}

Answer: Your query doesn't match your rules.  Your query is attempting to get all documents where the uid field matches the provided uid:
firebase.firestore()
    .collection("users")
    .where("uid", "==", uid)

But your rules are saying that users may only access the individual document with the ID that matches their UID.  The rule is going to reject this query every time, because it's not looking at the document ID at all, just a field.
Your rules allow this query instead:
firebase.firestore()
    .collection("users")
    .doc(uid)

If you actually do want to allow the user to access any document where their UID matches the uid field in the document, you will need to adjust them like this:
match /users/{userId} {
  function isAuthenticated() {
    return request.auth != null;
  }

  function checkDocUid() {
    return request.resource.data.uid == request.auth.uid;
  }

  allow read: if isAuthenticated() && checkDocUid();
}

Note that request.auth.uid is the currenetly auth'd user's uid and request.resource.data.uid is the value of the uid field in the document.
Always remember that your query must match the rules exactly, and that security rules are not filters.
Comment: Thank you! This makes so much sense. I was unaware of the `.doc()` prototype. This is exactly what I wanted. This way I also don't need to do `.docs[0].data()`. Awesome!


Multiple-choice: sum of primes below $1000$

Question: I sat an exam 2 months ago and the question paper contains the problem:

Given that there are $168$ primes below $1000$. Then the sum of all primes
  below 1000 is
(a) $11555$ (b) $76127$ (c) $57298$ (d) $81722$

My attempt to solve it: We know that below $1000$ there are $167$ odd primes and 1 even prime (2), so the sum has to be odd, leaving only the first two numbers. Then I tried to use the formula "Every prime can be written in of the form $6n-1$,$6n+1$ except $2$ and $3$.", but I got stuck at that.
Comment: Just by "multiple-choice psychology" I expect both obviously wrong answers (c) and (d) to be somehow close to (and ideally on both sides of) the correct answer. This is the case only if (b) is the correct answer.
Comment: Only (b) is really plausible on size. I'd expect the average size to be in the 400-500 area, but definitely less than 500. Then you have eliminated (c) and (d) on parity anyway.
Comment: I have to say, that this test question is horrible. It's gimicky and relies on a lot of mental jumps, the opposite of what a test question should do.
Comment: @SlimsGhost: I know what a mathematical proof looks like, but nobody was asking for a proof. I'm just making fun of multiple-choice tests.
Comment: According to [OEIS A034387](https://oeis.org/A034387) (both "Comments" and "Formula") one can approximate the answer by $1000^2/(2\log 1000)$ which gives $72382.4$. This suggests that (a) could be wrong. That same reference has a "Link" with _Table of n, a(n) for n = 1..10000_.
Comment: Could you specify what kind of calculator/computer you are allowed to rely on for an answer?
Comment: one more way :  if 1 to 169 were the 169 first prime, the sum will already be 14365, and this is setting lower bounds standards very, very low
Comment: @HopefullyHelpful I disagree. I think this is a very good test question. This question requires the student really to think and use their creativity.
Comment: @Curd, that is not a proof, that is an educated guess or value judgment, based on "psychology".  I agree with your guess, but my agreement does not make it a proof.  But still an interesting answer/comment :)
Comment: @Curd sorry, my mistake with the comment. I was just trying to have fun too, promise :)  Still love the question and answers and comments on this one.
Comment: A key multiple-choice insight is that we don't need to accurately estimate the sum, since (C),(D) are infeasible and (A) implies an impossibly low average of 68.8, as several answers pointed out. So we never need to compute or accurately estimate (B). It's interesting, but not necessary to answering the MC question.
Answer: The sum of the first 168 positive integers is $\frac{168^2+168}{2}=14196$, which is greater than answer (a). The sum of the first 168 primes must be even greater than that.
Comment: I agree Oscar's answer is similar, and it helped inspire this one. But I think it's instructive to show just how obviously too low (a) is, and how trivially simple the bound that excludes it can be. That said I didn't quite expect this answer to be so popular, I guess people like simplicity...
Comment: Beauty lies in simplicity.
Comment: Oscar Lanzi has a similar answer (which is earlier); yours is a bit more simple (but your bound is only half as good, though already good enough to exclude (a)).
Answer: you just have to decide between $11555$ and $76127$.
Notice that the first implies the average prime under $1000$ is $11555/168<69$. Which is clearly false.
Comment: To clarify, note that there are only `19` primes under `69` and the remaining `149` primes are larger. Hence there is no way to arrive at this average.
Comment: @FlorianF Well… no, not really. 11,555 is obviously wrong, but it is definitely below 84,000.
Comment: Or the other way round, the average of the primes <1000 should be below 500, since the density decreases.  So the sum should be below 168*500 = 84000.  That leaves only 76127.
Comment: I just independently used the same method. Florian's estimate for (B) is a ballpark overestimate. Accuracy doesn't matter because (A) is infeasible because it implies an impossibly low mean. So we already know the answer can only be (B), whatever (B) is. We weren't asked to estimate (B) more accurately, in which case we'd integrate some [Prime-counting function](https://en.wikipedia.org/wiki/Prime-counting_function) e.g. per the OEIS sequence @JeppeStigNielsen cites.
Comment: One doesn't even need to count the number of primes under $69$. We're told that there are $168$ primes below $1000$, so the average of the primes below $1000$ is certainly greater than the average of the first $168$ positive integers, which is $169/2$. Of course, this is essentially the content of Meni Rosenfeld's answer...
Answer: We have to decide among $\text{(A)}$ and $\text{(B)}$. Note that the $26$th prime is $101$. This implies that if $p_{n}$ denotes the $n$ th prime, then $$\sum_{n=1}^{168}p_{n} = \sum_{n=1}^{25}p_{n}+\sum_{n=26}^{168} p_{n} > \sum_{n=26}^{168} 101 =101 \times 143=14443 >\text{(A)}=11555$$
The answer is thus $\text{(B)}$, $76127$. The answer can be confirmed through direct calculation or can be verfied here.
Comment: It is somewhat commonly known piece of a trivia - there are 25 primes below 100 and the primes below 25 sum to 100.
Comment: Why did you choose the 26th prime here? Or is it just arbitrary?
Comment: @MarioDS It is as Jon Claus said; many people memorized it, so I was able to answer it quickly.
Answer: There are $168$ primes with the first one equal to $2$ the rest $\ge 2k-1$ for $k=2,3,4,...,168$.   So their sum is at least $168^2+1=28 225$.
Comment: (a) would mean that the average prime is $<70$, which is horrendously implausible, for me good enough to pick (b) instead. - But this answer is the formal reason why it's implausible
Answer: I just wanted to carry forward your observation about "Every prime can be written in of the form $(6n-1),(6n+1)$ except $2$ & $3$".
We can quickly get a minimum sum out of this. Assume that the $166$ primes not $2$ or $3$ are the smallest such numbers obeying the above; then $83$ are $6k{-}1$, $83$ are $6k{+}1$ and the minimum bound total is $83$ terms of $12k$, which is $12\cdot 84 \cdot 83 /2 = 504\cdot 83  = 41832$ - and we can decoratively add the $2$ and $3$ to get $41837$. This is more than big enough to eliminate option (a) as required.
Comment: The only problem here is that I feel cheated at the too-obvious wrongness of option (a)  -  it could've been say 41555 instead of 11555 :-)
Comment: Using that all primes > 7 are 30k ± 1, 7, 11, 13, the lower bound is 51,677.
Comment: Interestingly, 41837 isn't _that_ far away from 76127.
Answer: Your analysis that the answer must be $(a)$ or $(b)$ is convincing.  Considering that $(a)$ and $(b)$ are much different, just about any simplistic method to approximate the sum of all primes should tell which is the right answer.
For example, the sum of all numbers less than $1000$ is about $500,000$. So, $\cfrac{168}{1000} \times 500,000$ or $84,000$ should be in the right ballpark.  $76127$ is the right answer, by this reasoning.
Comment: I edited out the meta-commentary (as we call it... well, at least as I call it) because we try to stay away from that stuff on SE. Anyway, I think you've got nothing to worry about. This method is legit, because the four answer choices are separated by enough to easily distinguish between them.
Comment: Yup you got me to upvote.  A comparison test, see another answer, easily limits the size of the "ballpark" thus settling the question.
Answer: Primes except for $2$ are all odd, and you have $168$ distinct primes, so their sum must be at least $2 + \sum_{k=2}^{168} (2k-1) = 2 + (168^2-1) > 160^2 = 25600 > 11555$. So option (a) is out and only (b) remains.
Comment: Of course, the question is so weak that taking the first $168$ positive integers suffices, but it's even easier to get a bound using odd positive integers!
Answer: The methods provided previously are very correct. However, I would like to share my approach as I believe this is even simpler. It's less calculative, and more logical.
Sum is odd ⇒ answer is either (a) or (b)
Taking the number in (a) 11555 we divide it by 168 [to get the average]
11555/168≈69
69<168/2
An average of 168 distinct numbers can be less than 168/2(=84) iff at-least some of them are negative.
Which is clearly not possible since we are dealing with whole numbers.
⇒ only possible answer remain (b).


Can I edit the oracle instances property?

Question: When creating a table in Oracle, the Parallel and Degree properties can be specified.
When creating a table and selecting * from all_all_tables, there is an INSTANCES item. Can this item be edited by the user using DDL statements such as CREATE TABLE? If there is, please ask for an example phrase.
Answer: Below is an example of setting and altering the INSTANCES property of a table:
SQL> create table test1(a number) parallel (instances 2);

Table created.

SQL> select instances from user_tables where table_name = 'TEST1';

INSTANCES
----------------------------------------
         2

SQL> alter table test1 parallel (instances 1);

Table altered.

SQL> select instances from user_tables where table_name = 'TEST1';

INSTANCES
----------------------------------------
         1

The table property is defined in the 19c reference as "Number of instances across which the table is to be scanned, or DEFAULT".
I think INSTANCES has been deprecated and replaced by setting PARALLEL_FORCE_LOCAL at either the session or system level. The INSTANCES syntax is documented in the version 7 SQL Reference but is not documented in the version 8i SQL Reference.


Showing a certain map is a homeomorphism

Question: I'm studying point-set topology for the first time, and I'm finding some difficulty in solving problems which ask to verify certain statements in particular examples. I'm ok with the theory, but sometimes I can't quite see how to approach exercises like the following.
I'm asked to show that the map $\Bbb{P^1R} \to S^1$, $[x_0,x_1] \mapsto (\frac{x_0^2-x_1^2}{x_0^2+x_1^2},\frac{2x_0x_1}{x_0^2+x_1^2})$ is a homeomorphism.
I've thought of using the fact that $\Bbb{P^1R}$ is homeomorphic to $S^1$ with antipodal points identified.
This essentially just allows me to say that in the above map $x_0^2+x_1^2=1$, but I can't see how that helps to show that it's a homeomorphism. Is there some geometric picture I'm not seing? Or am I just supposed to do a ton of calculations?
More generally, are there any particular things I'm supposed to be thinking when dealing with particular examples in topology, rather than general statements? Thank you in advance, any advice is very much appreciated.
Answer: You should be able to do this in a straightforward manner by applying the following theorem:

Theorem: If $f : X \to Y$ is a continuous bijection from a compact space $X$ to a Hausdorff space $Y$, then $f$ is a homeomorphism.

So, just verify that the formula you wrote defines a continuous bijection from $P^1 \mathbb R$ to $S^1$, and verify compactness of $P^1 \mathbb R$ and Hausdorffness of $S^1$.
Let me add that if you are asked to prove a specific function is a homeomorphism, I doubt you could achieve that by using some abstract knowledge of the existence of some other homeomorphism.
Comment: Aaah I see now, thank you!!!


How can I match color palettes across different seaborn plots?

Question: I want to make a pie chart and a barplot (displot) that use the same colour label across both plots, but I don't know how to do that.
temp_df = pd.DataFrame([['d7d1b050-0e48-4c00-8061-c78817155b72',
  '42773088-e38f-4578-bc2a-69d1797a90eb',
  11,
  'groupA'],
 ['962c397d-a8f8-4f1c-a589-ecf74a7da62d',
  'b5baafb0-f6d4-4b4e-bc76-1287614b985d',
  10,
  'groupA'],
 ['a90fde40-9b9f-466e-bd5e-a40325b5fc9d',
  'b3fba007-aef5-4a5f-a53b-94eb0705d953',
  11,
  'groupB'],
 ['22ebb056-603c-4f66-8240-8c54e8043509',
  'b780fa66-addd-48c0-8db4-d755ebd351b8',
  10,
  'groupC'],
 ['52ffd64c-a5c1-4cd5-89c8-c1dcb8bd24b2',
  '37482cb7-c354-4b4b-92b6-2aaa62811e5b',
  10,
  'groupA'],
 ['55524169-f159-4c31-b939-bb00e1cba804',
  '34a9ff63-ea75-473d-ab89-9a92c3f4a8d9',
  10,
  'groupB'],
 ['2027d9d0-1e29-4d1f-969a-995a47f12052',
  '875488ea-85a2-47cb-b1ea-62003bbce80a',
  10,
  'groupA'],
 ['10d9c9fb-b5dd-4581-b148-a6198abecec1',
  '3f4b0604-513a-424b-98a3-e788ab3daa97',
  11,
  'groupD'],
 ['1c1e183b-6459-41bd-99aa-5f89b375006a',
  '53dd2ffd-c9b0-49c3-9275-190716c78799',
  10,
  'groupB'],
 ['31030ded-64a7-4854-8042-585605141e71',
  'f0514527-2d7b-4cad-a36f-f21e3425093c',
  10,
  'groupD'],
 ['cdfd5a0c-dd8c-4546-ba31-c2f021fb4859',
  '1ed007fe-d4f7-41bc-8f3c-b163c57f8a1f',
  11,
  'groupE'],
 ['66bd16a5-b514-4d8a-ad7a-afb8921f7dd2',
  'a2e9f137-bba5-46ec-8b13-7b17821de735',
  10,
  'groupB'],
 ['3cdb21d9-be3c-4723-bf28-0a7769d492b4',
  '9a6f1516-54a0-4dda-83d7-e05311e87ff5',
  10,
  'groupE'],
 ['d25f4cb2-3bf7-4898-a8a3-91d9e1b58576',
  '716a7732-6bcd-478d-87f9-c13cd83eaf66',
  11,
  'groupA'],
 ['e95134fd-7ce2-4e88-808c-e5abf13a4892',
  'c021c21b-7bab-4e1f-9ff0-4dfc584263b8',
  11,
  'groupE'],
 ['e13da005-1033-466f-b984-48fdfa0988f2',
  '5bcc0651-0775-4fa5-b521-ac90e0a33b1c',
  10,
  'groupB'],
 ['b60ee53d-e4fc-4e37-aa1c-df67f66e304e',
  '592adca4-6fa6-48c3-be97-2357250d736d',
  10,
  'groupD'],
 ['c1d47246-838f-418a-a92d-7b5150122775',
  'ff5d180c-cca9-474a-974e-e18c35cab912',
  10,
  'groupA'],
 ['fc129686-f7cd-407a-aca3-68f86c52af41',
  'a18dfc3a-2ce6-43f7-a21f-4c7371cff2b6',
  11,
  'groupE'],
 ['191af645-cb9e-408a-af2e-b6826f7177b9',
  'd430610b-b7da-42cb-aa93-c7f94774093c',
  10,
  'groupA']])

temp_df.columns = ['clickId', 'sessionId', 'month','group']

temp_df.groupby(['group']).agg({'sessionId':'count'}).plot.pie(y='sessionId');

sns.displot(data=temp_df[['sessionId', 'month', 'group']].drop_duplicates(), x='date', hue='group',  stat='count', multiple="stack")

Those two plots will use different color palettes, and what I would like is for each level within group to have the same colour for both the displot and the pie chart.
Any idea how I would do that?
Comment: This code doesn't run
Comment: As your code is currently written the last line `sns.displot` throws `ValueError: Could not interpret value \`date\` for parameter \`x\``
Answer: You could use the same colors (plt.cm.tab10) in both cases.  You might want to set alpha to 1. Note that you need discrete=True for the histogram.
To make sure that the same order is used everywhere, temp_df['group'] = pd.Categorical(temp_df['group']) can be used. Or temp_df['group'] = pd.Categorical(temp_df['group'], ['groupA', 'groupB', 'groupC', 'groupD', 'groupE']) if the exact ordering is important. By default, the order of appearance in the dataframe (or in the subset) is used.
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import seaborn as sns
import pandas as pd
import numpy as np

temp_df = pd.DataFrame([
    ['d7d1b050-0e48-4c00-8061-c78817155b72', '42773088-e38f-4578-bc2a-69d1797a90eb', 11, 'groupA'],
    ['962c397d-a8f8-4f1c-a589-ecf74a7da62d', 'b5baafb0-f6d4-4b4e-bc76-1287614b985d', 10, 'groupA'],
    ['a90fde40-9b9f-466e-bd5e-a40325b5fc9d', 'b3fba007-aef5-4a5f-a53b-94eb0705d953', 11, 'groupB'],
    ['22ebb056-603c-4f66-8240-8c54e8043509', 'b780fa66-addd-48c0-8db4-d755ebd351b8', 10, 'groupC'],
    ['52ffd64c-a5c1-4cd5-89c8-c1dcb8bd24b2', '37482cb7-c354-4b4b-92b6-2aaa62811e5b', 10, 'groupA'],
    ['55524169-f159-4c31-b939-bb00e1cba804', '34a9ff63-ea75-473d-ab89-9a92c3f4a8d9', 10, 'groupB'],
    ['2027d9d0-1e29-4d1f-969a-995a47f12052', '875488ea-85a2-47cb-b1ea-62003bbce80a', 10, 'groupA'],
    ['10d9c9fb-b5dd-4581-b148-a6198abecec1', '3f4b0604-513a-424b-98a3-e788ab3daa97', 11, 'groupD'],
    ['1c1e183b-6459-41bd-99aa-5f89b375006a', '53dd2ffd-c9b0-49c3-9275-190716c78799', 10, 'groupB'],
    ['31030ded-64a7-4854-8042-585605141e71', 'f0514527-2d7b-4cad-a36f-f21e3425093c', 10, 'groupD'],
    ['cdfd5a0c-dd8c-4546-ba31-c2f021fb4859', '1ed007fe-d4f7-41bc-8f3c-b163c57f8a1f', 11, 'groupE'],
    ['66bd16a5-b514-4d8a-ad7a-afb8921f7dd2', 'a2e9f137-bba5-46ec-8b13-7b17821de735', 10, 'groupB'],
    ['3cdb21d9-be3c-4723-bf28-0a7769d492b4', '9a6f1516-54a0-4dda-83d7-e05311e87ff5', 10, 'groupE'],
    ['d25f4cb2-3bf7-4898-a8a3-91d9e1b58576', '716a7732-6bcd-478d-87f9-c13cd83eaf66', 11, 'groupA'],
    ['e95134fd-7ce2-4e88-808c-e5abf13a4892', 'c021c21b-7bab-4e1f-9ff0-4dfc584263b8', 11, 'groupE'],
    ['e13da005-1033-466f-b984-48fdfa0988f2', '5bcc0651-0775-4fa5-b521-ac90e0a33b1c', 10, 'groupB'],
    ['b60ee53d-e4fc-4e37-aa1c-df67f66e304e', '592adca4-6fa6-48c3-be97-2357250d736d', 10, 'groupD'],
    ['c1d47246-838f-418a-a92d-7b5150122775', 'ff5d180c-cca9-474a-974e-e18c35cab912', 10, 'groupA'],
    ['fc129686-f7cd-407a-aca3-68f86c52af41', 'a18dfc3a-2ce6-43f7-a21f-4c7371cff2b6', 11, 'groupE'],
    ['191af645-cb9e-408a-af2e-b6826f7177b9', 'd430610b-b7da-42cb-aa93-c7f94774093c', 10, 'groupA']],
    columns=['clickId', 'sessionId', 'month', 'group'])

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14, 6))

temp_df['group'] = pd.Categorical(temp_df['group'], ['groupA', 'groupB', 'groupC', 'groupD', 'groupE'])
temp_df.columns = ['clickId', 'sessionId', 'month', 'group']
temp_df.groupby(['group']).agg({'sessionId': 'count'}).plot.pie(y='sessionId', ax=ax1)

sns.histplot(data=temp_df[['sessionId', 'month', 'group']].drop_duplicates(),
             x='month', hue='group', palette='tab10', alpha=1,
             stat='count', discrete=True, multiple="stack", shrink=0.8, ax=ax2)
ax2.xaxis.set_major_locator(MultipleLocator(1))
sns.despine(ax=ax2)
plt.tight_layout()
plt.show()

Comment: I can reproduce the results you've shown here, but when I'm working with my own non-anonymized data, the colours between the two plots don't match up.  Any idea why that might be happening? I'm going to keep digging into it, but you've got more experience than I do.
Comment: You could do `temp_df['group'] = pd.Categorical(temp_df['group'])` to fix an ordering on the groups.  What exactly is the difference you see?  Are there more groups in one vs the other?  Are the colors fully different, or just in a different order?  Are there more than 10 colors? (After 10 colors, the pie chart will start repeating colors).
Comment: The colors are not indexing the same between the two plots.  I've gone so far as to turn the plotting part of the code into a function and just changing which data is being passed- and the only difference is the number of rows.... which makes no sense to me.

But the Categorical grouping made it work!


Banjolele: retune GDAE -> GCEA

Question: I've bought a tenor banjo-uke (GDAE) as a present for person, who is playing on ukulele.
Problem is that I've found there is a different tunning (ukulele is GCEA) and he would have to learn from begining on different tuning...
Is it possible to retune banjo uke from GDAE to GCEA? I'm layman, so I know nothing about it. Is it as simple as seems to be (just replace strings) or not so simple?
And if yes, which kind of strings should I use?
Answer: Banjo ukuleles are typically tuned the same as regular ukuleles: GCEA.  The current tuning you have on your banjo uke is alternative.  A tenor scale ukulele is 17 inches (43 cm) measured from the nut to the saddle, so if your banjo ukulele has the same scale length, you should be able to put standard tenor scale ukulele strings on it and tune it to GCEA.  String sets are available for both high-G (standard reentrant tuning) and low-G.
Answer: You are making this more complicated than it really is,..In that, it being that "Tenor" banjolele tuning is DGBE,.as opposed to GCEA for the suprano & concert ukes,. does NOT mean that one needs to "start over" when taking up the Tenor Banjolele, in that the "REALATIONSHIP" of the strings in the 2 different tunings is the "SAME". so that all of the fingering is the "same", The difference being, that when you finger any "particular" chord, on one instrument, then a "different" chord comes out of the other instrument,..
What I mean is that, "IF" the player wants a "C" chord, on the tenor banjolele then they just need to use the same fingering as for a "G" chord on the uke,..& so on.
Another way of thinking about it is to just go ahead & tune the tenor "Banjolele" to DGBE , which is standard, but use a guitar chord chart.
But you really don't need a guitar chart, all you need to  do is wrap your head around the idea, that to get a particular chord on the banjolele you need to play the chord that is 7 intervals higher on the musical scale.
Lets say for instance that you want to play a song on the tenor banjolele that you play on the uke, in the key of "G",..No problem, in that "IF" you just went ahead & played the song, on the tenor, using the uke fingering, in the key of "G" then it would sound just fine, the only difference being that it is being played in the key of "C" on the tenor, so "IF"you want it to come out in the key of "G" on the Banjolele, then you need to use the same fingering on the Tenor Banjolele as in the key of "D" on the uke,..
In short, you are using the same chord patterns on both instruments, but on one instrument the "same" pattern will produce a different chord than the other instrument will produce. Following is a list of some "possible' chords,..Now assuming a person can play each of these chords on a uke, then to play that same chord on a Tenor then play the uke pattern just to the right of it, ..that is If you want an "F" on the tenor, then play the "C" uke pattern,..Or if you want a "E" on the tenor, then play the "B" uke pattern
F-C-G-D-A-E-B
Or, "IF" you want the tuning to be the same on both instruments, then REMOVE the "D" string from the tenor & move the "G" string to where the "D" string was, then move the "B" string to where the "G" string was & tune it up to "C" ,..then move the "E"  to where the "B" string was,..& now you will need a new string to give you a high "A" note,..A Mandolin "A" might work,.. But a music store should have a chart that will give you some idea as to the pitch, at a particular length, for a particular string,..
But, I have experimented with changing the tuning as described, & I have found that I sort of enjoy the extra effort involved in, playing each instrument in it's intended tuning,..
So, in short, all of the shapes of chords played are the same on both instruments, but you just call them by different names, on the different instruments,..It's no big deal to learn,..
Comment: Standard *baritone* ukulele tuning is DGBE, but *tenor* ukuleles are normally tuned at GCEA, the same as soprano and concert ukes.
Comment: Also, the OP said that his or her uke has a GDAE tuning, which are not the same intervals as standard GCEA.

Banjolele: retune GDAE -> GCEA


Apple Remote Notifications - Handle Token change

Question: I need to use Notifications via APNS in my iPhone App.
But as I read specification, I see the Token can be changed on APNS side and I have to update token on Provider side to receive notifications right.
But what will happen when Provider creates Notification and will pass it to APNS and in this time the token will be already changed?
Will I receive a Notification with old token? Will provider be notified that token expired?
Should I solve it so, that after registering I will update my Provider with info "YOU CAN SEND NOTIFICATIONS" and make a NSTimer job to update this state while app is running?
According to this:
http://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/IPhoneOSClientImp/IPhoneOSClientImp.html#//apple_ref/doc/uid/TP40008194-CH103-SW2
Thanks
Answer: If your app registers for notifications at launch, and implements the methods specified in the documentation, it will be sure to get the correct token.
If your app keeps track of what the token used to be, it can send an update to the provider as needed (or just every time it gets a token whether it has changed or not).
If the token has changed, and the provider tries to push using the old token, the provider will be notified by the push notification server that the token is not valid.
Comment: when you read documentation i posted, you can note `An application should register every time it launches and give its provider the current token.` and `Moreover, never cache a device token and give that to your provider; always get the token from the system whenever you need it`. And question persists. What will happen when Provider sends Notification while offline and You go online and on register token will be changed ?
Comment: And when token changes and Provider sends Notification to APNS while client offline or with old token while it is already new ?
Comment: I'm pretty sure the token will only change when the client registers for a notification, not while it's offline. Also, they don't change that often. They can even persist across OS upgrades, so I don't think it's that big a an issue in real life.
Comment: Your app should obviously tell the provider if the token has changed, but if the token hasn't changed, there's no need for the network traffic to the provider. I wouldn't call that caching. As for token changes, I'm pretty certain that they only happen when a device requests a token from an APNS, not while it's offline. A token might have an expiration date if it's not used for a while, but if your users use your app on a regular basis, this will never be an issue, since your app will know if the token has been updated.
Comment: I think you don't understand my question POV. Client app registers and receives changed token, Provider will generate and send Notification to APNS before Client app will notify Provider about new token. How can I solve this situation?
Comment: You're right, I might have misunderstood your question. You're talking about the (very short) time overlap, where the token has actually changed, but the provider has not been notified yet, and it needs to send a push notification to the app?
Comment: I updated my answer to cover the situation where the token has changed, but the provider doesn't know yet.
Comment: thanks, that answers my question, and this discussion is also very inspirative :)


Domain of Orthogonality of Legendre Polynomials?

Question: In my Numerical Analysis Course, under the topic Theory of Orthogonal Polynomials We are following the book Numerical Analysis by Kendall E Atkinson.
The problem is the author keeps saying "The Legendre Polynomials are orthogonal in $(-1,1)$"
According to me a polynomial is defined everywhere and is Orthogonal With respect to a Inner-product which might have some integral and limit.
It makes no sense for me to talk about orthogonality in a Domain.
The course is combined for Physics and Mathematics students and I am a Mathematics Major.
Each Physics major believes the polynomial are orthogonal only in the domain.
for example Legendre polynomials are orthogonal in $(-1,1)$ only and you cant use them outside the $(-1,1)$ to study them or to find the coefficients using recursive relation outside $(-1,1)$ using Gaussian Elimination.
I want to know if there is meaning of Polynomials being orthogonal in a domain. If Yes, what does it mean?
Comment: How are you going to form the inner product without a domain? You could use a dot product, sure, but in the case of pair wise integration you need a domain in order to get a number out
Comment: The domain (-1,1) is defined for the Integral of the inner product not for the polynomial I suppose.
Answer:
"The Legendre Polynomials are orthogonal in (-1,1)"

The Legendre Polynomials are orthogonal with respect to the inner product $\langle f,g\rangle=\int_\mathbb R w(x)f(x) g(x)\, dx$ for a certain weight function $w(x).$
Answer: The orthogonality of Legendre polynomials is typically defined with respect to the inner product
$$
\langle p,q\rangle = \int_{-1}^1 p(x)q(x)\,dx
$$
Thus, they are said to be orthogonal on $(-1,1)$.
Of course, through a linear change of variables you could define them to be orthogonal on any bounded interval $(a,b)$.
Comment: The Polynomial $1$ and $1/2(3x^2 -1)$ are Orthogonal w.r.t. that Inner product that's it. what do you mean by orthogonal on $(-1,1)$
Comment: It simply means they are orthogonal with respect to the inner product given above, i.e., the integral defined on $(-1,1)$. If the integral was over $(a,b)$, then you would say they are orthogonal on $(a,b)$.
Comment: So do you mean that they stay orthogonal on $\mathbb{R}$ but we say they are orthogonal over (a,b) because it is the limit of the integral of the inner product. Is it a Standard Notation or Definition?
Comment: They are polynomials, so they are defined on $\mathbb{R}$, but they are not orthogonal on $\mathbb{R}$. Orthogonality is defined entirely with respect to the inner product which is defined on $(-1,1)$. I hope that makes it clear.
Comment: Sorry but it does not make it clear at all. Can you prove that Legendre Polynomials are not orthogonal over $\mathbb{R}$
Comment: The integral of $p_0(x)p_1(x) = x$ is divergent on $(0,\infty)$, and hence by definition it is divergent on $(-\infty,\infty)$. Thus these polynomials are not orthogonal on $\mathbb{R}$.
Comment: I suppose we are not allowed to change the Inner product otherwise they won't be legendre polynomial anymore!
Answer: What it means is that they are orthogonal with respect to the "uniform" probability distribution on $(-1,1)$, i.e. the measure $m$ defined by
$$
m(A) = \begin{cases}
1 & \text{if } A = (-1,1), \\
0 & \text{if } A \text{ is disjoint from } (-1,1), \\
\cdots & \text{(see below for other sets.)}
\end{cases}
$$
The measure assigned by $m$ to intervals that are subsets of $(-1,1)$ is proportional to the length of the interval (and from the above you can see what the constant of proportionality is).
Answer: they are orthogonal with respect to the inner product in the interval [-1,1],
Comment: In my opinion this does not answer to the question in the OP.


How do I set a local user a user rights assignment on an active directory GPO?

Question: We have a process where I work, where any changes to active directory GPOs are performed on test servers, backed up and then the backups applied to the live AD.
I'm in the process of amending a GPO where I want to specifically add in a user rights assignment for a user account that'll exist locally on the member servers that the GPO will apply to.
I've tried adding the word BUILTIN to the front of that user, I've tried using migtables, I've tried creating the user on the domain (but that ends up as trying to apply the user rights to the domain user of that name if he exists..).
Not sure what to do, Googling comes up with a lot of results that don't tend to lead anywhere for this scenario (local, user, group, policy all very common terms together).
Any suggested way of doing this?
Comment: You would do this by just typing the name in to the first popup of the add to user right assignment. Bulitin only work for the accounts and groups shipped with windows.
Answer: Perhaps, you can try the following:

Create a separate group for the user locally.
Create GPO and configure Restricted Groups in GPO to apply only to the local group created in step 1.

Description of Group Policy Restricted Groups
This is mentioned in the article if you follow the link:
Restricted Groups is a client configuration means and cannot be used with Domain Groups. Restricted Groups is designed specifically to work with Local Groups.
Answer: If you will be using the same local account name on each of the member servers, you can enter it like this in the GPO:
<code>.\localUsername
</code>
The .\ notation simply refers to the local computer when the setting in the GPO is applied. It is similar to entering domainName\accountName.
If you will be using a different account name on each of the member servers, then the solution will not be elegant. This approach would require you to either create a unique GPO for each member server's user rights assignments, or enter everything in one ugly (and less secure) GPO like this:
<code>server1\localUsername1, server2\localUsername2, server*N*\localUsername*N*
</code>
The best thing that you can do to begin with is to create domain service accounts instead of local accounts.
Hope this helps.
Comment: Domain controller came up with a message of "The following Accounts could not be validated when I tried to add .\localUserName to the user rights assignments, ended up using the solution below. Thanks for the help.


Syntax needed to exit a Worksheet_Change for multiple ranges subroutine if more than one target

Question: Option Explicit

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    Dim rngF As Range, rngC As Range
    Dim aCell As Range, bCell As Range
    Dim wkSheet1 As Worksheet

    'recursive error prevention
    On Error GoTo Whoa
    Application.EnableEvents = False

    If Target.Cells.CountLarge > 1 Then GoTo Letscontinue

    '___set range
    Set wkSheet1 = ThisWorkbook.Worksheets("backend")

    Set rngF = wkSheet1.Range("C5:C500,H5:H500,M5:M500,R5:R500,W5:W500,AB5:AB500" & _
              ",AG5:AG500,AL5:AL500,AQ5:AQ500,AV5:AV500,BA5:BA500,BF5:BF500," & _
              "BK5:BK500,BP5:BP500,BU5:BU500,BZ5:BZ500,CE5:CE500,CO5:CO500," & _
              "CT5:CT500,CY5:CY500,DD5:DD500,DI5:DI500,DN5:DN500," & _
              "DS5:DS500,DX5:DX500,EC5:EC500")
    Set rngC = wkSheet1.Range("D5:D500,I5:I500,N5:N500,S5:S500,X5:X500,AC5:AC500," & _
               "AH5:AH500,AM5:AM500,AR5:AR500,AW5:AW500,BB5:BB500,BG5:BG500," & _
               "BL5:BL500,BQ5:BQ500,BV5:BV500,CA5:CA500,CF5:CF500,CP5:CP500," & _
               "CU5:CU500,CZ5:CZ500,DE5:DE500,DJ5:DJ500,DO5:DO500," & _
               "DT5:DT500,DY5:DY500,ED5:ED500")

    'fORECAST

    If Not Application.Intersect(Target, rngF) Is Nothing Then
        '~~> Loop through all cells in the range
        For Each aCell In rngF
            If aCell.Value <> "" Then
                If aCell.Value <> "N/A,TBC,TBA,TBD" Then
                    If aCell.Value < Date Then
                        aCell.ClearContents
                        MsgBox "The Forecast date you have specified " & _
                        "may not occur in the past. Please try again"
                    Else
                    End If
                End If
            End If
        Next
    End If

    'complete

    If Target.Cells.Count > 1 Then Exit Sub

    If Not Application.Intersect(Target, rngC) Is Nothing Then
        '~~> Loop through all cells in the range
        For Each bCell In rngC
            If bCell.Value <> "" Then
                If bCell.Value > Date Then
                    bCell.ClearContents
                    MsgBox "The Forecast date you have specified " & _
                    "may not occur in the past. Please try again"
                Else
                End If
            End If
        Next
    End If

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

The question: I used If Target.Cells.Count > 1 Then Exit Sub to try get the sub to exit as soon as more than 1 cell had been affected. IE: After a single target cell in any of the specific ranges is affected, stop executing the clear cell contents on any others. Im sure my syntax is wrong or the logic needs a tweak. I've omitted part of the code that isn't affected.
Comment: Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). BTW, it's "Thanks in advance", not "Thanks in advanced".
Answer: If Target.Cells.Count > 1 Then Exit Sub is good enough :) However this line can give you error in Excel 2007+
Target.Cells.Count returns an Integer and it will give you an error in Excel 2007+ if the number of cells affected as they can be of Long Type
For Excel 2007+ use the below
If Target.Cells.CountLarge > 1 Then Exit Sub

Note: You need to add the line before you switch off events. Else instead of Exit Sub, you will have to say
If Target.Cells.CountLarge > 1 Then GoTo LetsContinue

Where LetsContinue is where you do the clean up as shown Here
Example 1
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.CountLarge > 1 Then Exit Sub

    On Error GoTo Whoa

    Application.EnableEvents = False

    '~~> Your code

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

Example 2
Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo Whoa

    Application.EnableEvents = False

    If Target.Cells.CountLarge > 1 Then GoTo Letscontinue

    '~~> Your code

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

Followup From Comments
Ah I think you misunderstood how the _Change Event Fires :) This event will fire if any cell is changed. Target.Cells.CountLarge checks for the number of cells that are changed right now. For example if you copy and paste values in say Cell A1:A5 then it means 5 cells are being changed at the moment.
What you want to do is run a piece of code when the user input a date in the userform. If that is correct then this code is what you need. I am using Sub Update() You may have to put it in the CommandButton Code (if you are using that)
Also you do not need to type the entire range. See how I am creating the range using a loop.
Note: The below code is Untested.
Option Explicit

Sub Update()
    Dim rngF As Range, rngC As Range
    Dim aCell As Range, bCell As Range
    Dim ws As Worksheet
    Dim i As Long

    Set ws = ThisWorkbook.Sheets("backend")

    With ws
        '~~> This creates your range
        For i = 3 To 133 Step 5
            If rngF Is Nothing Then
                Set rngF = .Range(ReturnName(i) & "5:" & ReturnName(i) & 500)
            Else
                Set rngF = Union(rngF, .Range(ReturnName(i) & "5:" & ReturnName(i) & 500))
            End If

            If rngC Is Nothing Then
                Set rngC = .Range(ReturnName(i + 1) & "5:" & ReturnName(i + 1) & 500)
            Else
                Set rngC = Union(rngC, .Range(ReturnName(i + 1) & "5:" & ReturnName(i + 1) & 500))
            End If
        Next i
    End With

    'Debug.Print rngF.Address
    'Debug.Print rngC.Address

    '~~> Forecast
    '~~> Loop through all cells in the range
    For Each aCell In rngF
        If aCell.Value <> "" Then
            If aCell.Value <> "N/A,TBC,TBA,TBD" Then
                '<~~ Is this the date from userform. If yes then
                '<~~ use a variable and input it below instead of `Date`
                If aCell.Value < Date Then
                    aCell.ClearContents
                    MsgBox "The Forecast date you have specified " & _
                    "may not occur in the past. Please try again"
                    Exit For '<~~ This will exit the For Loop. To exit the sub use `Exit Sub`
                End If
            End If
        End If
    Next

    '~~> Complete
    '~~> Loop through all cells in the range
    For Each bCell In rngC
        If bCell.Value <> "" Then
            '<~~ Is this the date from userform. If yes then
            '<~~ use a variable and input it below instead of `Date`
            If bCell.Value > Date Then
                bCell.ClearContents
                MsgBox "The Forecast date you have specified " & _
                "may not occur in the past. Please try again"
                Exit For '<~~ This will exit the For Loop. To exit the sub use `Exit Sub`
            Else
            End If
        End If
    Next
End Sub

Function ReturnName(ByVal num As Integer) As String
    ReturnName = Split(Cells(, num).Address, "$")(1)
End Function

Comment: Siddharth!! Thanks so so so much for you answer! It feels really great to get YOUR answer as it was one of your original answers that I built the code off of. The irony that you answered this is crazy. So for the original, and this update THANKS!! :)
Comment: Thank you for the kind comments :) Yes I know it was based on the code that I wrote. No one actually uses `'~~>` or `Whoa` other than me :D
Comment: Sorry Siddharth,  I tried both examples but the macro still identified and cleared more than the single specific cell i needed to check. Basically I entered in a date yesterday, that gets cleared today when the sub runs...
Comment: @Dylan don't hesitate to accept the answer if it works: it will tell other users with your same problem that this is the solution.
Comment: Thanks Matteo NNZ, it hasnt resolved just yet. I was just excited to get SIddharth's response as his was the code I originally got inspired from
Comment: with the example 2 built in, @SiddharthRout
Comment: @Dylan: I indented your code. I see an EndIf missing. besides that I don't see any problem with the code. Can you explain what were you truing to do and what were you expecting and what results did you actually get?
Comment: @SiddharthRout, essentially I use a userform to input dates into this hidden 'backend' sheet. the inputs go into the specified ranges.As you can see, this sub prevents you from choosing a past date for forecast. If I set a forecast date today, as today's date: ie I input 28/05/2015 now. Then, if I come into the file tommorrow and change any other value, it causes the sub to run and then deletes the 28/05/2015 date i specified yesterday. So i was hoping i could get the sub to run on 1 specific cell, then stop checking the rest, as they may be in the past but that data must be preserved.
Comment: Ah I think you misunderstood how the _Change Event Fires :) This event will fire if any cell is changed. `Target.Cells.CountLarge` checks for the number of cells that are changed right now. For example if you copy and paste values in say Cell A1:A5 then it means 5 cells are being changed at the moment
Comment: @SiddharthRout oh I see! so its the incorrect event for what I am trying to do?? Could you suggest a different Event for this? is there a different type of _change event?
Comment: Yes that would work perfectly! If I can only input into 1 cell at a time, I only need the Sub to run for that 1 cell. then the sub can exit. :)
Comment: @Dylan: I have updated the post. See the section `Followup From Comments` You may have to refresh the page


Prove that $X= \{ (x,y): y = mx + c \}$ is homeomorphic to $\mathbb R$.

Question:
Let $m$ and $c$ be non-zero real numbers and $X$ the subspace of $\mathbb R^2$ given by $X =\{ (x,y): y = mx + c \}$. Prove that $X$ is homeomorphic to $\mathbb R$.

I am struggling to figure out how to define a homeomorphic function between these two sets, can anyone please help?
Comment: Consider the map $f:\mathbb{R} \to X$ defined by $f(x) = (x, mx+c)$.
Answer: Hint: It might be easier to prove a more general fact. Let $f\colon X\to Y$ be any continuous function (between arbitary topological spaces). Show that $x\mapsto (x,f(x))$ defines a homeomorphic embedding of $X$ into $X\times Y$.
Comment: Is $\pi_1: X\times Y\to X$ the inverse map then?
Comment: @snulty: Its restriction the the graph of $f$ is.
Comment: That's great, nice answer! (+1)
Answer: Define the bijection $f : \mathbb R \to X$ by $fx = (x, mx + c)$. Let $(p_n)$ be a convergent sequence in $\mathbb R$ with $p_n \to p$. Then, the sequence $(fp_n) = (p_n, mp_n + c)$ also converges to $(p, mp + c)$. The inverse bijection $f^{-1} : X \to \mathbb R$ is defined by $f(x, mx + c) = x$. So, consider a convergent sequence $(q_n, mq_n + c)$ in $X$ with $(q_n, mq_n + c) \to (q, mq + c) \in X$. It follows that since $(q_n, mq_n + c) \to (q, mq + c)$, the sequence $f^{-1}(q_n,mq_n + c) = (q_n)$ also converges and $q_n \to q$. Hence, $f^{-1}$ preserves sequential convergence, and $f$ so defined is a homeomorphism.
Answer: Here's a relatively straightforward way to see it.
First note that $\iota :\Bbb R \to \Bbb R\times \{0\}\subset \Bbb R^2$ with the subspace topology is a homeomorphism.
Then, let $m=\tan\theta$ and $A:\Bbb R^2\to \Bbb R^2$ by $(x,y)\mapsto \pmatrix{\cos\theta & -\sin \theta \\ \sin\theta & \cos\theta}\pmatrix{x\\ y}$. A is also a homeomorphism.
Finally let $T_c:\Bbb R^2\to \Bbb R^2$ by $(x,y)\mapsto (x,y+c)$, another homeomorphism.
Altogether $X= T_c(A(\iota(\Bbb R)))$, since $A(\iota(\Bbb R))=\{a(\cos\theta,\sin\theta)\mid a\in \Bbb R\}$ and after applying $T_c$ we get the set $\{(a\cos\theta, a\sin\theta+c)\mid a\in \Bbb R\}$ which satisfies $$y= a\sin\theta + c = a\cos\theta \tan\theta +c= mx+c$$
By appropriate restrictions of the above maps we have a homeomorphism $f:\Bbb R\to X$ with $$f=T_c\bigg|_{X_1} \circ A\bigg|_{X_2}\circ \iota$$ where $X_2=\iota(\Bbb R)$ and $X_1= A(X_2)$.


Form not being displayed in c#

Question: I am having a program.cs that is something like this :
namespace SumSwamp
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

But when I run the program it executes without any errors But the form1 is not being displayed. Please tell me if am doing something wrong
Here is my form class.
Comment: It depends on what's in `Form1` class...
Comment: please share your form1.cs code
Comment: This is designer code. Please share code behind or Form1_Load.
Comment: Are you sure there are no errors? Look in the output window at the debug console.
Comment: @StuartGrassie Yeah there are no errors.
Comment: @SiD http://pastebin.com/9zNHrHAJ Sorry for previosu link
Comment: @Raptor Added Form1_Load code
Comment: @Senthil Code link added.Please check
Comment: You know that you *can* insert code into the question, right?
Comment: @user3185653 no problem in your code, can you check with debugging mode and set breakpoint to run your programme
Comment: @ThorstenDittmar I think its pretty big code to be added to post.
Comment: @Senthil I guess some loop is running infinite. Can you please help
Comment: @user3185653 s i think comment your code while loops one  by one so you will get which while loop problem
Comment: If you create windows application by default it should work. If you could see the same code in the Program.cs then your form1 will have some error.
Comment: @Senthil I am not able to get it..:(
Comment: @user3185653 y is there any problem
Comment: @Senthil I got the reason. But the loops while(Turn==0) and the While((CompSum < TotalSpaces) & (PlayerSum < TotalSpaces)) are running infinte
Comment: @Senthil But dont know why..Because i replace them with if instead of while and it executes
Comment: @user3185653 second while loop problem i think  while (Turn == 1)
Comment: in first while loop turn value not changed so the second while running infinite times While (Turn==1)
Answer: From your posted code, your error lies in this piece;
public static Boolean WaitForRoll = true;
public static int Turn = 0;

public Form1()
{
    InitializeComponent();
    this.Load += new EventHandler(this.Form1_Load);
    while(Turn == 0) //always true
    {
        if (WaitForRoll==false) //always false
        {
            //never reached code
            DieTotal=DieLargeNum;
            Random rnd1 = new Random();
            DieLargeNum = rnd1.Next(1, 7);
            if (DieTotal>DieLargeNum)
            {
                Turn = 1;
                labelStatus.Text = "Player 1's Turn";
                WaitForRoll=true;
            }
            else
            {
                Turn = 2;
                labelStatus.Text = "Player 2's Turn";
                WaitForRoll = false;
            }
        }
    }

    //...
}

Look at it closely and you will find that your code never leaves the first while loop, and thus the constructor never comes to an end resulting in the Form1 object never to be created.
Some tips;

Rethink your design. You should not place this code in your constructor, but in methods.
Read up on while loops. They are a pain if used incorrectly, which you did.
Comment: Yeah I know its going infinte along with one more while loop. Please help to correct it
Answer: Your Form1 is not visible because there is an infinite loop in your code. Please check the following code it goes infinite.
while ((CompSum < TotalSpaces) & (PlayerSum < TotalSpaces))
{
    ...
}

Comment: Yeah I know its going infinte.Please help to correct it
Comment: Becasue the `Turn=0` it is neither going inside `while (Turn == 1)` or `while (Turn == 2)`. That's why value of `CompSum` is never changed and it stays in while loop. You need to rethink your design. Code in constructor is not a good choice.

Form not being displayed in c#


Central limit theorem to approximate a Poisson distribution.

Question:
Considerable controversy has arisen over the possible aftereffects of a nuclear weapons test conducted in Nevada in $1957$. Included as part of the test were some $3000$ military and civilian "observers." Now, more than $50$ years later, eight cases of leukemia have been diagnosed among those $3000$. The expected number of cases, based on the demographic characteristics of the observers, was three. Assess the statistical significance of those findings. Calculate both an exact answer using the Poisson distribution as well as an approximation based on the central limit theorem.

I was able to calculate the answer using the Poisson distribution such that I found that $\frac{3}{3000}=p$ so $\lambda = (3000)(0.001)$ and then $P(X=8)=\frac{e^{-3}(3^8)}{8!}=0.008101$. (If I am incorrect please correct me.)
I am now having trouble using the central limit theorem to approximate.
Comment: You're probably expected to replace the Poisson distribution with a normal distribution of the same mean and standard deviation. However, note that computing $P(X=8)$ is not the same as "assessing the statistical significance of the findings". There's more for you to do in the exact case, which should bring you closer to a situation where you can see something analogous to do with the normal distribution.
Answer: You've almost got it.  Normally one would reject the null hypothesis that $\lambda\le3$ if $X$ is bigger than some cut-off point, and how big that is depends on how big a probability of Type I error one is willing to allow.  So what you need is
$$
\Pr(X\ge 8) = 1 - \sum_{x=0}^7 \Pr(X=x).
$$
The latter sum may (possibly?) be the quickest way to compute the number.  That probability is the $p$-value.
Comment: Can you please check the following, @Michael Hardy. I computed the above probability assuming the Poisson distribution and got,  $P(X\geq 8) = 1 - P(X < 8)= 1 - [ P(X = 0) + ....+P(X = 7)] = 1 - [ 0.988] = 0.012$. And for the second part using the central limit theorem I conclude $P(X\geq 8) = P(X \qeq 2.888) = 0.9988 = 0.1$. Both of these answers are different from the $p = 0.001$. Can you verify this? Do we have to get the same answer for both? Thank you.


Java Spring Extender @Scheduled para ler um arquivo

Question: Eu tenho tarefas para fazer assim que subo minha aplicação,  elas são executadas repetidamente dessa forma:
<code>  @Scheduled(fixedRate = 10000)
  public void scheduleFixedRateTask() {
        System.out.println("Fixed rate task - " + System.currentTimeMillis()/10000);
  }
</code>
Porém algumas vezes eu preciso atualizar o intervalo de tempo e eu não queria ter que parar a aplicação toda vez para fazer isso. Então queria saber se existe um meio de extender o @Scheduled do spring para que ele leia algum arquivo de configuração, tem como?
Comment: você usa spring boot?
Answer: Você pode parametrizar a annotation do Spring, fica um pouco diferente o parâmetro:
<code>//fixedDelay task:
@Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds}")

//fixedRate task:
@Scheduled(fixedRateString = "${fixedRate.in.milliseconds}")

//A cron expression based task:
@Scheduled(cron = "${cron.expression}")
</code>
Ai basta adicionar a propriedade ao seu arquivo de configuração.
Fonte: http://www.baeldung.com/spring-scheduled-tasks
Comment: Vou tentar no fim de semana, se funfar marco sua resposta.
Comment: Não funcionou?!
Comment: scheduled funiona para Windows ?
Answer: Atualizar propriedades do Spring com a aplicação rodando costuma ser um problema não trivial. Dessa forma muitas vezes acaba sendo mais fácil implementar esse tipo de agendamento de maneira programática:
<code>@Autowired private TaskScheduler scheduler;

private ScheduledFuture scheduledTask;

@PostConstruct
public void init() throws Exception {
    // Dispara com valor padrao, alternativamente
    // isso pode ser lido do arquivo de propriedades
    scheduleFixedRateTask(10000L);
}

public void scheduleFixedRateTask(final long rate) {
    if (scheduledTask!= null) {
        // Em um código real você provavelmente quer fazer algo mais robusto
        // do que interromper a tarefa logo de cara.
        scheduledTask.cancel(true);
    }
    Runnable task = new Runnable() {
       public void run() {
          System.out.println("Fixed rate task - " + System.currentTimeMillis()/rate);
       }
    };
    scheduledTask= scheduler.scheduleWithFixedDelay(task, rate);
}
</code>
Para casos de uso mais complexos o Spring tem suporte ao Quartz, porém o Quartz é um canhão se sua aplicação não possui necessidade real de jobs persistente / transacionais / distribuídos.

Fontes:

Spring Framework Reference - Task Execution and Scheduling
SOen - Creating Spring Framework task programmatically?
SOen - How to cancel Spring timer execution
Spring Scheduling: @Scheduled vs Quartz


What's the best strategy to adopt in designing a system that would substantially duplicate what could be done in MS Excel?

Question: We have a web-based product that is used for project management and planning. Each 'project' in the tool is accessible to 'all members' of that project.
Now, prior to the existence of this product a lot of work was done/managed using spreadsheets and it wasn't visible to all, so to speak - there was a need to have the core functionality/data be visible to all and also have the capability of exporting to excel when the need be (i.e., when presenting for a report or submitting to the higher ups or when not having access to the web-based system etc).
So we are now designing the upcoming version of the product to make it 'social' so that everyone can see what's going on and manage/plan as you go along. The question is what's the best strategy we can employ to prevent from duplicating what excel already does a fine job at, on the web based system.
So here's what we came up with:

Duplicate the functionality - i.e.,  have a table-based matrix-like structure for the content and have javascript calculate the results which could be committed to the server when the user says so (or after some time-out. Latter could be added later :)
Just use the front-end for the data-collection but no numerical calculation - have everything exported into an excel sheet that would do the calculations for you. However, knowing the calculations/numbers is critical for the visible to all part since that's what drives the management/planning effort!
Have some sort of web-based excel plugin that could speed up the development effort - effectively help us do the calculations and pull out the results to be used in the web-app. The problem is I don't know of any solutions like this out there! Any help/pointers/links would be greatly appreciated.

The pain points are keeping developmental time/costs low - each solution is progressively cheaper so to speak. Basically we have the need for a 'math-engine' like design, where the numbers are entered, the results are calculated and we can use that for the project (in the tool). There has to be some way of getting the numbers from the users, calculating the end results/scores and updating the content on the web-app. Exporting to excel (that would have the similar functionality would be required for the above mentioned reasons as well as doing further sensitivity analysis by yourself, so to speak).
What's the best way to approach this problem? We are open to Javascript/Jquery solutions or CSS3/HTML 5. No Flash or Flex though.
Comment: Your question is way too vague to be properly answered here. You should sized down your issue to an actual programming problem instead of rough architecture or design ideas. As your question stands now it is off topic of SO.
Comment: @HolgerJust: I beg to differ. Architectural solutions/design problems are vague in nature - but I've tried to make it objective by specifying the current alternatives and the rationales - I want to know how best to *balance* the forces with what I have. #3 above actually asks a programming solution/plugin!
Answer: I believe you can use the Microsoft Office Excel Web App for this (#3).
Here is a link an example of embedding an Excel Web App. However, I'm not sure of the environment you are developing nor of the costs of getting this Web App, but it may be an option for you.
http://office.microsoft.com/en-us/excel/embed-an-excel-spreadsheet-on-a-web-page-FX102602477.aspx
Comment: I never even knew something like this existed - I know MS was in the works but not sure if they launched it! +1 for the link!
Answer: Option #1 could be very simple or very complex depending on what you actually need to calculate.  If you only need a handful of different calculations, it might just be easier to implement itself.  Html already has support for the matrix-like structure.
I don't know of any Excel-like plugins, but if they exist, I imagine they would be more difficult to implement than just setting up the matrix in the UI, and writing the few functions you need.
Comment: I'm not sure I understand your comment `Html already has support for the matrix-like structure`. Could you please clarify what kind of support are you alluding to?
Comment: oh, sorry, all I meant is that html supports tables, which you can use to easily-create a matrix.


Using jquery-ui datepicker with require.js

Question: I searched some questions in here, but didn't get any solution. I'm trying to use datepicker in backbone.js require.js project.
main.js :
requirejs.config({
   enforceDefine: true,
   paths: {
      "jquery": "libs/jquery/jquery-min",
      "underscore": "libs/underscore/underscore",
      "backbone": "libs/backbone/backbone-min",
      "jquery-ui" : "libs/jquery/jquery-ui"
   },
   shim : {
      "underscore": {
         deps: [],
         exports: "_"
       },
       "backbone": {
         deps: ["jquery", "underscore"],
         exports: "Backbone"
       },
       "jquery-ui" : ['jquery']
   }
});

Here is my view :
define(["jquery","underscore","backbone","jquery-ui"], ,function($, _, Backbone,jqueryUI){

   //view code block

});

Just define it like this, and not yet call any function of jquery-ui then I got one error in my console Error: No define call for jquery-ui http://requirejs.org docs/errors.html#nodefine.
Any help would be appreciated.
Comment: @Evgeniy : It's working after I set `enforceDefine` to `false`, but could you just please tell me, what did it relate to the error issue about it?
Comment: try to set enforceDefine to  false
Answer: To make it work please set enforceDefine to false.
According to official docs

enforceDefine: If set to true, an error will be thrown if a script
  loads that does not call define() or have a shim exports string value
  that can be checked.
Answer: as for jquery plugin, I prefer to convert to UMD module which is much cleaner way to avoid contamination of global variable


How to display column data after first delimiter

Question: I have strings with (a random number of) delimiters and I want to display the string after the first delimiter from the left. What is the query for that?
Example
I have data values like:
DR.V.PRADEEP
MRS.C.S.PRAMEELA
MR.V.G. R. PRUDHVI

...and I have to display the data after the first "." delimiter, i.e, the output should be:
V.PRADEEP
C.S.PRAMEELA
V.G. R. PRUDHVI

How can I achieve this?
Comment: What have you tried so far?
Answer: You can use instr and substr. If your table is called tbl and the column with the data is called name, then it looks like this:
select substr(name, instr(name, '.')+1)
from   tbl


Confidence interval for N, based on binomial

Question: I've searched the web and these forums but couldn't find a subject that resembled my problem. If I missed something then I'd like to apologize upfront.
My problem is this. I have a given probability p, given by an outside agency and the number of successes n from an owned datasource. I'm interested in the population total N and the confidence interval of N.
Background: I know how many passengers there are for a specific bus agency using 2013 data (as in: I have the (micro)data from that specific company). Assumption: this is my n. I also know from transportation figures (from an outside agency) that this specific bus company had a market share (as measured in passengers) of 30% in 2013. Assumption: this is my p. This assumption brings with it certain other assumptions, that is fine.
So now the question is: how many passengers were there in total (assuming this can not be taken from the transportation figures)? ie. what is N and what is the 95% confidence interval surrounding N?
So my questions are:
1) Can I just use the relation: p=n/N, therefore the point estimat for N is: N=n/p? I'd assume so.
2) Can I just use the Clopper-Pearson interval to calculate an interval for p, then using that to get to an interval for N?
3) Suppose the 95% lowerbound for p=plb. Is the 95% lower bound for N then n/plb? Same logic for the 95% upper bound.
4) When calculating the Clopper-Pearson interval, can I just use: n=n, p=p, N=n/p?
5) If any of the answers to my questions 2-4 is 'No', then what is the correct approach?
I realize that using this approach, N is not necessarily an integer. Is that problematic?
Answer: If we treat the $p$ as a fixed, known quantity (rather than something that was an estimate, as it seems it actually was) and we treat the $n$ as having come from a $\text{binomial}(N,p)$, then I believe this is actually a negative binomial problem.
We can view each passenger as a Bernoulli trial, where 'success' is 'travelled with the particular bus company'. As such, the number of trials (passengers) until the $n$th success is negative binomial $\text{NB}(n,p)$ (in the 'number of trials' form; if we're using the 'number of failures' form we need to add $n$ to the result).
We can use the quantiles of that conditional distribution for $N$ to get a confidence interval.
So for example, with $n=1000$ and $p=0.3$ the interval $(3163,3509)$ contains just over 95% of the probability, and has very close to 2.5% in each tail.

If we treat $p$ as an estimate measured with error, then this becomes a bit more complex, and we'd need some information about the estimation of $p$, or to make some assumptions about it. It might be necessary to use simulation in that case. Dealing with this would tend to make the interval a good deal wider.

However, I'd actually be somewhat more inclined to consider a Bayesian approach for this problem, I think it's a pretty natural fit; incorporating prior information about $N$ and uncertainty in $p$ can both be brought in in fairly natural ways.


Structuring longitudinal clinical input for LSTM RNN

Question: Totally new to LSTMs and would like some guidance on how to structure input data for classification using multivariate longitudinal data. Most, if not all, tutorials online are non-healthcare related and I could not find a good analogy as an example to work from.
The problem: predicting that a hospitalization event will occur in the next 30-90 days (where days 0-29 is a lag period for intervention).
The data: Each observation is one patient, and each patient has several lab outcomes with many sequential values. Each patient also has non-sequential data, like gender and race.
Questions:
1. How do I specify the individual values of one lab outcome's sequence from another's?
2. How do I input non-sequential variables along with sequential?
3. How should LSTM parameters/architecture be adjusted to accommodate?
My thinking so far is that the data should be structured using an array, where each row is the sequence of a lab outcome, and non-sequential attributes exist as sequences with the same value in each column. I assume that the LSTM inherently knows that each row is another variable.
Here are two papers that are helpful for context:
1. Learning to diagnose with LSTM RNNs https://arxiv.org/abs/1511.03677v7
2. Multi task prediction of disease onset from longitudinal lab tests https://arxiv.org/abs/1608.00647v3
I am using python: keras with tensorflow.
Comment: Also see papers by Edward Choi https://arxiv.org/abs/1511.05942 and https://arxiv.org/abs/1511.05942 . I believe that in these studies they aligned unevenly sampled measurements (but I am not certain).  So, even if the labs were not drawn e.g. hourly, they kind of coerced them into that structure.
Comment: Isn't these two paper same ?. Did u miss mentioning the other paper . I am just curious about the other paper
Answer: Your concept of an input array where each row is the sequence of a different lab is correct, so long as the observations are at the same time intervals. For example, each lab sequence having one observation per day would work fine. But if you also had observations of other intervals, such as hourly or weekly, you might not want to mix them. In this case you could have multiple LSTM networks that operate on each time scale you need, and their hidden states all connect into your outputs, but that would be getting in pretty deep.
As for how to specify one lab's outcomes from another, this will happen automatically as long as you keep the order of your different labs consistent across all time steps. For example, if lab A is your first input value at timestep T, and lab B is your second, as long as you have the same order at timestep T+1 and so on it won't get confused.
There are two options I'm aware of for adding non sequential data. You mentioned the first one, just have an input that is the same at every time step. Another option would be to process your sequences without them and get a hidden state, then add on each non sequential input to the end of the hidden state vector and calculate your output. For example, if your hidden state size is 50 and you had 3 different inputs you wanted to add on at the end, you would get a vector of length 53 that connects into your outputs.
You may have to experiment with what works best. If one of your non sequential inputs should significantly change the way your sequence is processed it may be best to add it in at every time step. But if not, adding it in over and over can just slow things down and sometimes even decrease performance by drowning out the other more important inputs.
Comment: With regard to the non-sequential inputs, I can think of some cases in medicine where it would be useful to have them alongside the sequential ones.  For example, absolute cholesterol values differ a lot by gender--perhaps variance does as well.  It *might* be useful to have gender therefore mixed in.


Best application IDE to use for Java debugging

Question: I have recently been teaching myself Java code and am looking for a debugging program so I can identify breakpoints and errors in my code. I am on a Windows OS and have some familiarity with Eclipse, but I'm unsure.
Does anyone have any suggestions?
thank you.
Answer: Any major Java IDE will be suitable for debugging of Java code. If you are familiar with Eclipse, try that. Or you can also try to evaluate the different IDEs for other purposes, if you have any specific requirements, but the baseline is that for Java debugging any IDE will be suitable.
Comment: Thanks. I went with NetBeans IDE. Works well.


How to grant access on some functionnalities in system dashboard to a given role

Question: How can I grant access on system dashboard to a given role.
Let's assume the role is "Webmaster". So when a user with this role logged in, he will land to the admin page as if he belongs to the "admin" role, but with fewer options available.
For example he will not be able to see the "configuration" menu, and so fourth...
Because what I actually have is, when this kind of user logged in, he lands on a user page like other authenticated user (I mean a regular front page).
Thanks for your help
Comment: Drupal 7 or Drupal 8?
Answer: By default, when a user logs in on Drupal, they are redirected to /user (the user page). If you want to change that behavior (so they are redirected to a custom dashboard page that you create (ie: /admin/dashboard) you might be able to use Rules (assuming you are on D7 - Rules is not ready for D8 yet as far as I know). You would create a Rule that triggers when a user logs in, add a condition to check there role, and an action to redirect them to another page.
You may also want to read this, because there may be more conditions you want to include, so that they are NOT redirected when they are resetting their password, for example: https://www.drupal.org/node/480584
As for hiding Configuration menu and other things, that is accomplished by assigning (or not assigning) permissions to the user roles. So your admin role should include access to Configuration, but your other roles should not.


Ocaml change type 'a tree to 'b tree

Question: I have defined
type 'a tree =
| Tree of 'a tree * 'a * 'a tree
| Leaf of 'a
| Null;;

Now I have to define a function that will change the whole 'a tree in to an 'b tree.
I have searched on google and tried to solve it myself but I'm stucked. Any tips?
Comment: As a side remark, note that your tree type is a bit odd : you can have two different representation for a leaf  wich let's say contains the value 1. Either  ````Leaf(1) ```` or ````Tree(Null,1,Null)  ````. A more idiomatic binary tree type  - that avoids this redundancy - would be the following : ````type 'a tree = | Tree of 'a tree * 'a * 'a tree | Leaf ````
Answer: One possibility is an analog to the map function but over trees. For example:
let rec treemap f t = match t with
    Null           -> Null
 |  Leaf x         -> Leaf (f x)
 |  Tree (l, x, r) -> Tree (treemap f l, f x, treemap f r)

Here t : 'a tree, f : 'a -> 'b, and treemap : 'a tree -> ('a -> 'b) -> 'b tree, which produces a 'b tree as desired.

This is the most "natural" way of making such a function: you have a tree with values of type 'a, and you want to get a new tree with values of type 'b - so you just need a tree and some way of mapping a value of one type to a value of the other.
I think it's worth pointing out that this isn't the only such function. You could make a function treereplace : 'a tree -> 'b -> 'b tree, which just creates an identically structured tree but replacing every value with the one given, or a function which does the same but flips the left/right branches of each Tree node. There's an infinite number of functions taking an 'a tree and producing a 'b tree that you could make, the above is just arguably the most natural and useful.
Edit: Improvements/critique welcome - I don't know OCaml, I hacked this example together from an understanding of SML.
Comment: Looks good to me. You can drop the double semi-colon at the end (it's only useful in the repl) but apart from that it's pretty idiomatic.

Ocaml change type 'a tree to 'b tree


Resizing/Cropping and Appending 4 images

Question: I'm currently using this command to resize images using imagemagick:
<code> convert \( ${files[0]} ${files[1]} -append \) \( ${files[2]} ${files[3]} -append \) +append $dir.jpg
</code>

What is the best way to deal with images which dimensions differ like in the second picture? can I specify specific width or height and make the image resize and crop to that size if its smaller and crop the center if its really hight so I always get the result like in first picture?
Thanks!
Answer: Try to resize the image to the same size.
<code>for i in *.jpg; do convert $i -resize 80x80 -quality 90 $i.jpg; done
</code>
Now you can append images.
Appending images before resizing

Appending images after resizing