Rastrear requisições AJAX em andamento

Question: Estou trabalhando em uma página onde tenho um botão atualizar, ao clicar nele é executado uma série de requisições AJAX para completar os dados disponíveis na tela (4 requisições para ser mais exato).
Caso o usuário clique no botão de atualizar, eu gostaria de desabilitar o botão enquanto todas as requisições não voltarem, pois caso o usuário clique no botão inúmeros vezes acaba gerando diversas requisições, o que ocasiona que o browser trave também (fiz esse teste).
Existe alguma maneira de verificar se a requisição ainda não finalizou pelo próprio jQuery? Até onde entendi só temos o .done, .fail e .always para utilizar, e somente com essas verificações não consigo realizar essa validação para habilitar/desabilitar o botão.
Não sei se faz alguma diferença, mas estou realizando as requisições com a estrutura
$.post({},function(){});

Por acaso vocês conhecem alguma solução que permita rastrear se a requisição ainda está em andamento ou isso não seria possível?
Comment: Conhece `beforeSend: function(){}`?  Daria pra colocar uma variável de controle nele... Cada requisição iria definir essa variável, e ao final, todas iriam executar uma função pra checar se as outras requisições já foram finalizadas. Se servir pra vc, posso formular uma resposta nesse sentido.
Comment: @LipESprY hmm, dei uma olhada nela, teria como utilizar na estrutura $.post ou somente $.ajax? Então, se eu conseguir realizar uma verificação se todas ainda não voltaram para dar "disabled" no meu button, serve sim!
Comment: Cara, dei uma olhada **superficial** na documentação do *jQuery* e, pelo visto, não tem. Mas tb não tem mt diferença do `$.post()` pro `$.ajax()`... Pode até mesmo fazer um *plugin* pra facilitar na reutilização do código... Se te interessar, posso formular uma resposta dando uma solução pro seu problema.
Comment: @LipESprY se puder eu aceito sim.
Answer:
Existe alguma maneira de verificar se a requisição ainda não finalizou pelo próprio jQuery?

Uma forma simples seria adicionar uma variável de controle. Ao completar a requisição do ajax, definir um valor nessa variável. Fazer assim nas 4 requisições. Dessas forma, utilizar o Promise .aways() da requisição ajax.

eu gostaria de desabilitar o botão enquanto todas as requisições não voltarem

Daí podemos fazer uma função para verificar se todas as requisições foram completadas. Caso sim, habilita novamente o botão...

estou realizando as requisições com a estrutura $.post({},function(){});

Nesse caso, vou usar $.ajax().

Leitura recomendada: SOen - $.post() vs $.ajax()

Teoria explicada, vamos ao código:

        var requisicoes = 0;

        $(function(){
            $('#btnIniciar').on('click', function(){
                $(this).prop('disabled', true); // Desabilitei o botão!

                fazerRequisicoes(); // Chamei as requisições

            });
        });

        function fazerRequisicoes()
        {

            // Requisição #1
            $.ajax({
                url: 'http://foo.bar.com.br/baz/1',
                method: 'post',
                dataType: 'html',
                // Tudo que vai passar via POST
                // Pode passar um form.serialize() também
                data: {
                    // Td que vai passar via post
                }
            })
            .done(function(ret){
                // Tudo que acontece quando terminar com sucesso
                console.log('Requisição #1 finalizada com sucesso.');
            })
            .fail(function(erro){
                // Tudo que acontece quando terminar com erro
                console.log('Requisição #1 finalizada com erro.');
            })
            .always(function(){
                // Tudo que acontece quando terminar
                // Seja com sucesso ou com erro
                // Como o nome sugere: sempre vai ser executado
                requisicoes++;
                console.log('Requisições terminadas: '+requisicoes);
                if (checaRequisicoes(4)) // Serão 4 requisições no total!
                    habilitaBtn();
            });

            // Requisição #2
            $.ajax({
                url: 'http://foo.bar.com.br/baz/2',
                method: 'post',
                dataType: 'html',
                // Tudo que vai passar via POST
                // Pode passar um form.serialize() também
                data: {
                    // Td que vai passar via post
                }
            }).done(function(ret){
                // Tudo que acontece quando terminar com sucesso
                console.log('Requisição #2 finalizada com sucesso.');
            }).fail(function(erro){
                // Tudo que acontece quando terminar com erro
                console.log('Requisição #2 finalizada com erro.');
            }).always(function(){
                // Tudo que acontece quando terminar
                // Seja com sucesso ou com erro
                // Como o nome sugere: sempre vai ser executado
                requisicoes++;
                console.log('Requisições terminadas: '+requisicoes);
                if (checaRequisicoes(4)) // Serão 4 requisições no total!
                    habilitaBtn();
            });

            // Requisição #3
            $.ajax({
                url: 'http://foo.bar.com.br/baz/3',
                method: 'post',
                dataType: 'html',
                // Tudo que vai passar via POST
                // Pode passar um form.serialize() também
                data: {
                    // Td que vai passar via post
                }
            }).done(function(ret){
                // Tudo que acontece quando terminar com sucesso
                console.log('Requisição #3 finalizada com sucesso.');
            }).fail(function(erro){
                // Tudo que acontece quando terminar com erro
                console.log('Requisição #3 finalizada com erro.');
            }).always(function(){
                // Tudo que acontece quando terminar
                // Seja com sucesso ou com erro
                // Como o nome sugere: sempre vai ser executado
                requisicoes++;
                console.log('Requisições terminadas: '+requisicoes);
                if (checaRequisicoes(4)) // Serão 4 requisições no total!
                    habilitaBtn();
            });

            // Requisição #4
            $.ajax({
                url: 'http://foo.bar.com.br/baz/4',
                method: 'post',
                dataType: 'html',
                // Tudo que vai passar via POST
                // Pode passar um form.serialize() também
                data: {
                    // Td que vai passar via post
                }
            }).done(function(ret){
                // Tudo que acontece quando terminar com sucesso
                console.log('Requisição #4 finalizada com sucesso.');
            }).fail(function(erro){
                // Tudo que acontece quando terminar com erro
                console.log('Requisição #4 finalizada com erro.');
            }).always(function(){
                // Tudo que acontece quando terminar
                // Seja com sucesso ou com erro
                // Como o nome sugere: sempre vai ser executado
                requisicoes++;
                console.log('Requisições terminadas: '+requisicoes);
                if (checaRequisicoes(4)) // Serão 4 requisições no total!
                    habilitaBtn();
            });
        }

        function checaRequisicoes(numRequisicoes)
        {
            if (requisicoes >= numRequisicoes)
                return true;
            else
                return false;
        }

        function habilitaBtn()
        {
            // Após tudo terminar, vai esperar 3 segundo pra habilitar o botão
            setTimeout(function(){
                $('#btnIniciar').prop('disabled', false);
            }, 3000);
            requisicoes = 0;
        }
<!DOCTYPE html>

    <title>Projeto secreto</title>
    <meta charset="utf-8">

        <button type="button" id="btnIniciar">Iniciar requisições ajax</button>

Fiz esse código ignorando qualquer boa prática de estética e dinâmica, de forma que fique claro para melhor entendimento.
Como comentei, pode criar um plugin para as requisições do ajax, caso haja semelhança entre as suas requisições (não anexo à pergunta). O intuito aqui é mostrar uma simples forma de "conferir" se suas requisições foram completadas (com erro ou não) para re-habilitar o botão.
Comment: @ViniciusGabriel No final das contas nem usei `beforeSend`... Dessa forma pode fazer com o seu `$.post()`...
Comment: Não. O `always` é chamado logo após o `.done()`. Ou após o `.fail()`, caso haja algum erro... Teoricamente, ele é chamado SEMPRE depois da requisição.
Comment: Cara, show! Essa estrutura é muito boa, muito obrigado.
Comment: O .always, é disparado logo no momento de chamada da função?

Rastrear requisições AJAX em andamento


Limit of ${ \lim_{(x,y)\to(0,0)} {(\left| x \right| + \left| y \right|) \ln{(x^2 + y^4)} }}$

Question: This question comes from Hubbard's textbook "Vector Calculus, Linear Algebra, and Differential Forms: A Unified Approach" (5th edition, exercise 1.5.16b)
I wrote a $\epsilon -\delta$ proof to show ${ \lim_{(x,y)\to(0,0)} {(\left| x \right| + \left| y \right|) \ln{(x^2 + y^4)} }} = 0$, but wanted to ask to check if what I wrote was correct:

Suppose we have $\epsilon > 0$.

First, it can be shown (with L'Hoptial for example) that $\lim_{x\to 0} |x| \ln(x^k) = 0$ for even positive integers $k$. Thus there exists $\delta_{1;k} > 0$ such that $|x| < \delta_{1;k}$ implies $\left| |x| \ln(x^k) \right| = \left| k |x| \ln(x) \right| < \frac{k\epsilon}{6}$. Therefore: $|x| \ln(x) > - \frac{\epsilon}{6}$.

Secondly, clearly we have $\lim_{x \to 0} {|x| \ln(x^2 + c)} = \lim_{y \to 0} {|y| \ln(y^4 + c)} = 0$ for any $c > 0$. So there exists $\delta_{2; c}, \delta_{3;c} > 0$ such that:

$|x| < \delta_{2;c} \implies \left| |x| \ln(x^2 + c) \right| < \frac{\epsilon}{2}$.
$|y| < \delta_{3;c} \implies \left| |y| \ln(y^4 + c) \right| < \frac{\epsilon}{2}$.

Let $\delta = \min(\epsilon, \delta_{1;2}, \delta_{1;4}, \delta_{2;\epsilon}, \delta_{3;\epsilon})$. So if $\sqrt{x^2 + y^2} < \delta$, note that this implies $|x| < \delta$ and $|y| < \delta$. Then:
$$\begin{align} (|x| + |y|) \ln(x^2 + y^4) &= |x| \ln(x^2 + y^4) + |y| \ln(x^2 + y^4) \\ &\leq |x| \ln(x^2 + \epsilon^4) + |y| \ln(\epsilon^2 + y^4) \\ &< \frac{\epsilon}{2} + \frac{\epsilon}{2} = \epsilon \end{align}$$
As $x^2 + y^4 < \epsilon^2 + y^4$ (as $|x| < \delta \leq \epsilon$) and $\ln(x)$ is a strictly increasing implies $\ln(x^2 + y^4) < \ln(\epsilon^2 + y^4)$. Since $|y| \geq 0$ then $|y| \ln(x^2 + y^4) \leq |y| \ln(\epsilon^2 + y^4)$.
Moreover:
$$\begin{align} (|x| + |y|) \ln(x^2 + y^4) &= |x| \ln(x^2 + y^4) + |y| \ln(x^2 + y^4)
\\ &\geq |x| \ln(x^2) + |y| \ln(y^4) \\ &= 2|x|\ln(x) + 4|y| \ln(y) \\ &> -\frac{2\epsilon}{6} - \frac{4\epsilon}{6} = -\epsilon \end{align}$$
Putting these together we have $\left| (|x| + |y|) \ln(x^2 + y^4) \right| < \epsilon$.
Therefore  ${ \lim_{(x,y)\to(0,0)} {(\left| x \right| + \left| y \right|) \ln{(x^2 + y^4)} }} = 0$.
Comment: Your question ask for a proof or for a check of your calculations?
Comment: Didn't look so carefully at the details, but looks like you are on the right track.  As you observed, $\lim_{x\to 0} x \ln x =0$.  In this case, to handle the absolute value, you can consider $\lim_{x\downarrow 0} x \ln x$.
Comment: Hi enzotib, I wanted to ask if proof was correct (I made some changes along the way), but wouldn't mind if someone provides different answers just for insight.
Answer: Given that the function is even with respect to $x$ and with respect to $y,$ it is enough to consider $x,y\geq0,$ and $(x,y)\neq(0,0).$  I would write
$$
\lim_{(x,y)\to(0,0)}\frac{x+y}{\sqrt[4]{x^2+y^4}}\cdot\sqrt[4]{x^2+y^4}\log(x^2+y^4).
$$
Now, it should be rather easy to see that
$$
\lim_{(x,y)\to(0,0)}\sqrt[4]{x^2+y^4}\log(x^2+y^4)=0.
$$
In fact, set $z=g(x,y)=x^2+y^4,$ prove that $g(x,y)\to0$ (use the continuity), then
$$
\lim_{z\to0}\sqrt[4]{z}\log(z)=0,
$$
while the other factor is bounded in a neighbourhood of $(0,0).$ We can equivalently consider its fourth power
$$
\frac{(x+y)^4}{x^2+y^4},\qquad x,y\geq0,\ (x,y)\neq(0,0),
$$
and use polar coordinates
$$
\frac{\rho^2(\cos\theta+\sin\theta)^4}{\cos^2\theta+\rho^2\sin^4\theta},\qquad\rho>0,\ 0\leq\theta\leq\pi/2
$$
It is easy to see that, whenever $0<\rho<1/\sqrt{2}$, the denominator satisfy
$$
\cos^2\theta+\rho^2\sin^4\theta\geq\rho^2
$$
so that
$$
0<\frac{(x+y)^4}{x^2+y^4}=\frac{\rho^2(\cos\theta+\sin\theta)^4}{\cos^2\theta+\rho^2\sin^4\theta}\leq(\cos\theta+\sin\theta)^4\leq4
$$
and
$$
0<\frac{x+y}{\sqrt[4]{x^2+y^4}}\leq\sqrt{2},\qquad x,y\geq0,\ 0<x^2+y^2<1/2.
$$
Comment: In the former case I simply did the derivative with respect to $\theta$ and see that it has three factors, one of them of constant sign if $\rho^2<1/2$. In the latter case I observed that $\cos\theta+\sin\theta=\sqrt{2}\cos(\theta-\pi/4)\leq\sqrt{2},$ but the larger and obvious inequality $\cos\theta+\sin\theta\leq1+1=2$ could be sufficient. If you need further details, let me know.
Comment: Hi @enzotib, thanks for the answer. If it is okay, could you explain how $\cos^2 \theta + p^2 \sin^4 \theta \geq p^2$ for $0 < p < 1/\sqrt{2}$ and $(\cos \theta + \sin \theta)^4 \leq 4$? I'm familiar with basic trig identities (and could derive using those) but was curious if there was something more straightforward/obvious.


symmetric difference of Sets in java

Question: I am trying to implement symmetric difference of Sets in java
I have commented the Line where I am missing some concept. Kindly Help !
public static <T> Set<T> symmetricDifference(Set<? extends T> set1, Set<? extends T> set2) {
        for(<? extends T> a : set1)
        {
            if(set2.contains(a))
                {
                    set1.remove(a);
                    set2.remove(a);
                }
            else
                set2.add(a);  //what is wrong with this line
        }
        return set2;
    }

}

The error on the commented Line is
'Main.java:11: error: illegal start of type Set<> ans=new Set<>();

Comment: Set is an interface and cannot be instantized. Use one of its implementations like HashSet<> for instance.
Comment: `for( a : set1)` is nonsensical syntax. `for (T a : set1)`. But then you've still got the problem that you can't add to `set2` because of the upper-bounded wildcard.
Comment: What's the error?
Comment: 'Main.java:11: error: illegal start of type
        Set<> ans=new Set<>();
            ^'@BenjaminUrquhart
Comment: So the error occurs in code that isn't shown?
Comment: "'Main.java:11: error: illegal start of type
        Set<> ans=new Set<>();" where does that appear on the code?
Comment: Please read "How to create a [mcve]". Then use the [edit] link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. And do not put such infos into comments, update the question instead.
Answer: The symmetric difference of two sets is the union of their differences. Now, the problem in your case is that you have a method which returns a set and you modify the input sets, distorting them. You need to create a new Set and add the elements you need. In order to do that you will need to iterate your first set and add the items into the new set which are not found in the second set, and then iterate the second set and add the items to the new set which were not found in the first set. The formula is:
A △ B = (A – B) ∪ (B – A)
or:
A △ B = (A ∪ B) - (A ∩ B)
Answer: This can be easily done using Java 8 streams:
public static <T> Set<T> symmetricDifference(Set<? extends T> set1, Set<? extends T> set2) {
    Set<T> set =  set1.stream()
            .filter(e -> !set2.contains(e))
            .collect(Collectors.toSet());

    set2.stream()
            .filter(e -> !set1.contains(e))
            .forEach(set::add);

    return set;
}

or a solution for Java 7 and below:
public static <T> Set<T> symmetricDifference2(Set<? extends T> set1, Set<? extends T> set2) {
    Set<T> s = new HashSet<>();

    for (T t1 : set1) {
        if(!set2.contains(t1))
            s.add(t1);
    }

    for (T t2 : set2) {
        if(!set1.contains(t2))
            s.add(t2);
    }

    return s;
}

But however this does not makes much sense. If generic type of set1 differs from generic type of set2 there is not much of a chance to exclude any element because both set1 and set2 will contain different implementations of T (except you forced your equals() and hashCode() methods to do so).
Comment: An easier way with streams would be `Stream.concat(set1.stream(), set2.stream()).filter(e -> !set1.contains(e) || !set2.contains(e)).collect(toSet())`.

symmetric difference of Sets in java


Turn off animations when resizing row height?

Question: I have an NSTableView which has custom row heights. I would like to temporarily turn off animations while I resize the heights. When there are many rows in view, or the user scrolls fast, the animation is just too much. How can I do this?
Answer: In the documentation for NSView you find
"- (void)setLayerContentsRedrawPolicy:(NSViewLayerContentsRedrawPolicy)newPolicy", what should fit to your needs.
Comment: macrene, looks promising, but where would I place this? I have a place where I am setting the row height (return the height) and a place where I get the subview (return the view), but neither seems to be a good place to put this.
Comment: I'd disable it in the method where you "reloadData", before "reloadData" and after that enable it again or in the method "numberOfRowsInTableView" before return (...), depending on where you want the effects


On the sup convolution of upper semi continuous function

Question: Let $f$ is a bounded upper semi continuous function on $[-1,1]$ and for any $\epsilon>0$, we define
$$f^{\epsilon}(t):=\max\limits_{s\in[-1,1]}\left\{f(s)+\epsilon-\frac{1}{\epsilon}|t-s|^{2}\right\},\ \forall t\in[-1,1].$$
Can we prove that $f^{\epsilon}$ converges to $f$ uniformly on $[-1,1]$ as $\epsilon\rightarrow0$ or is there counterexample?
Answer: The expression $ f(s)+\epsilon-\frac{1}{\epsilon}|t-s|^{2}$ is a Lipschitz function of $t$, with constant $4/\epsilon$. Taking the supremum over $s$ preserves this property. Hence, $f^\epsilon$ is a Lipschitz function, in particular continuous. And continuous functions cannot converge uniformly to $f$ unless $f$ is itself continuous.
Pointwise convergence holds, however (as was indicated elsewhere).


Get the parametric equation of a line

Question: How I can get the parametric equation of this line?
$$r\equiv\begin{cases} x-y=2 \\2x-z+1=0\end{cases}$$
Thanks.
Comment: Let $x=t$ so express $y$ and $z$ with $t$.
Answer: Let $x=t$. Then $y=t-2$ and $z=2t+1$.
Comment: Is there any reason why you have chosen the **X**? And if I have: **r:**   **x+y+z=1** and **2x+y=3** ?
Comment: Sorry, I add this after you answered me: And if I have: r: x+y+z=1 and 2x+y=3?
Comment: I don't know how, I got stucked in all my attemps.
Comment: Ok finally done.
Answer: HINT : Set $x=t$, then represent each of $y,z$ by $t$.

Get the parametric equation of a line


How to predict the loudness of an amp based on description

Question: Related question: Is there an amp power formula?
When I look at amps in a shop or online, I ask myself what the amp is suitable for:

Can it be played quietly enough for home use without disturbing the neighbours/sleeping wife/etc.?
Is it loud enough to play along with acoustic instruments?
Is it loud enough to be heard by an audience in a room of a certain size?
Is it loud enough to be heard alongside a drumkit
etc.

It's clear that wattage isn't an adequate indicator: the Beatles played gigs on Vox AC15s -- I have owned a 15 watt guitar amp that couldn't possibly be heard over a drumkit.
It's also clear that size isn't much of an indicator either -- there are tiny guitar amps that are seriously loud.
When choosing an amp, how do I know how loud it's going to be?
Quick word on scope:
 - Let's not talk about micing up amps for the PA.
 - Let's be general and talk about bass, guitar, keyboard amps, and amps for any other electric instrument.
Answer: Although watts actually are a pretty decent way to predict the loudness of an amp, it's worth understanding what the listed wattage of an amp means.  Remember that an amp is designed first and foremost to amplify the input signal, and that for many applications, it's desirable that the amp do so while keeping the signal as clean as possible.  So an amp's wattage rating is traditionally listed as the amount of power it can produce while keeping the total harmonic distortion (THD) of the output under a certain percentage.
But maybe the guitarist doesn't care about keeping the signal pristine---in fact, maybe he'd like the amp to produce some distortion, maybe even a lot of distortion.  In that case, he's going to be running the amp at higher wattages than its rating and thus it will seem louder than its rating would imply.  It matters, too, whether the amp uses tubes or solid state transistors, because tube distortion is often thought of as being more pleasant than solid state distortion.  This means that a guitarist playing through a 100 watt tube amp may turn it up to get distortion from the amp, while a guitarist playing through a 100 watt solid state amp may rely on pedals for his distortion and leave the amp turned down to avoid the unpleasant solid-state distortion.
You mention the Beatles playing through 15 watt Vox AC15's, which are tube amps.  In concert, they turned those amps way up and got a fair amount of distortion from them, meaning their amps were producing way more than 15 watts of power.  Perhaps the 15 watt amp you mentioned as being underpowered was a solid-state amp?
As far as amplifying other instruments is concerned, each instrument has its own specific needs, and so its hard to compare wattages across different instrument categories.  Keyboard amps, for example, are designed to be as clean as possible, so a keyboardist is not likely to turn an amp up beyond its listed rating.  Bassists, as a general rule, require higher-rated amps because their lower frequencies require more power to produce a similar volume.  For example, in a typical rock band, the guitarist might play through an amp rated anywhere between 50 and 150 watts (if you're planning on cranking your amp up to AC/DC-type distortion levels, btw, 50 W is plenty loud), while many bass heads are rated in the 300-400 W range.  In my own case, my guitar amp is a Fender Twin Reverb rated at 85 watts and my bass rig is powered by a Crown K2 power amp which produces 1,600 watts in bridge-mono mode.  I can tell you that the Twin absolutely keeps up with the bass rig in terms of volume---but then, I want to distort the guitar amp, and I want to keep the bass amp as clean as possible.
In any event, wattage is not bad as an indicator of an amp's loudness, so long as you understand what it does and doesn't actually mean.
Answer: Watts output(RMS) and the efficiency of the speaker(s) are just about all you can use to estimate.  The rule of thumb is that it takes a doubling of watts to increase output by 3 db.
I have seen speakers with sensitivity ratings of 95db (cheesy no-name '70s 12" speaker I found in an old Fender Amp) to 101db (A quality EV 12" guitar speaker in an Ampeg VT-22... LOUD)
I'm going to try to explain this with an example rather than writing a detailed post because I'll likely get the details wrong...
Take a Fender Deluxe (A 20ish Watt(RMS) amplifier) and put in the 95db speaker and you'll struggle with volume (you'll be at 80% to 100% on the volume control) but you'll get pretty good power amp distortion because the amp has to work very hard to push the speaker to an acceptable volume.
Now, take the same Fender Deluxe and install the 102db speaker.  It will be too loud to turn up past 40% or so and the power amp distortion will be minimal because the amp does not have to work as hard to produce an acceptable volume.
I hope this makes sense...
Edit:  This link explains the math.
Comment: I find it very surprising that the best answer - the only one to mentions decibels and speakers efficiency - is the least upvoted.
Answer: Wattage and size are actually the single best indicator, but you are right - they aren't the whole story.
For example a 150W guitar amp is likely to be a lot louder than a 150W hi-fi system as the amp model doesn't require that much accuracy in a guitar amp, whereas a hi-fi amp should reproduce sound very accurately.
I have played some small venues using just a 150W amp for my guitar - turned up halfway even a 100W Marshall through a 4x10 can be nice and loud.

I wouldn't want to try with anything smaller, as even when mic'ed up I want to be able to hear my monitor over the drums, house PA, even the singer! Admittedly I play rock and metal, but it is blues based rather than thrash based so I want enough headroom that I can accurately decide my clipping and distortion in my pedal, not the amp.
If you want clarity, go for a higher power amp - then you are less likely to hit any headroom/distortion constraints.
I have played in bands where we used 12 kW of amplification between 2 guitars, bass, vocals and a keyboard to halls of up to 1000. Loud, but we had headroom so we never had to turn it up close to clipping. Nowadays I like to have my pedal connected directly to the PA system and just use my wedge monitor. (means we don't need a large van for travelling to gigs, which is nice)
You can always turn an amp down low, but to avoid disturbing sleeping flatmates you want a headphone amp:

That may all seem a bit of a ramble, but what it comes down to is that you just need to try them out. Start at 150W if you have a standard drum kit on stage with you (this is also a good size for mic'ing up for the PA with either a 2 or 4 speaker cab) and work up from there.
Comment: Don't forget that with tube amps you need to take into account the actual power tubes and preamp tubes and if the output tubes are optimally biased. e.g. if you substitute a 12au7 for the 12ax7 in the preamp section, suddenly your screaming amp is a bedroom practice amp.
Comment: very true - never tried that though :-)
Comment: It's great to try when you can no longer lift your vintage 1965 Super Reverb and have confined to it to your bedroom. :>
Comment: When it comes to guitars, a 40W amps with a single mildly efficient 12'' is already loud enough to overpower a drummer (and I mean a metalhead drummer pounding his own beloved metalhead drumkit).
Answer: All I can say is that this topic is complained about a lot, and is controversial. The answers seem to be really complex. But the consensus is, no, there is no clear, simple relationship between the manufacturer's reported wattage and the practical, real-world volume that the amp can produce. Indeed, different models of amps produced by different manufacturers which report the same power wattage will in fact sound different in practical volume level.
Here's a good technical note/blog post, "Watts vs. Volume" by a well-respected guitar amp builder who talks about the issues involved. He has a lot to say about the Fletcher/Munson curve (the frequency response of the human ear at varying levels of volume) and perceived volume, how he designs his amps, and how he tries to report honest numbers to reflect how loud his amps are going to be.
Answer: I hear this question a lot but the answers are all over the place, which is very understandable due to variable nature of guitar amplifiers.
I used to own a Vow AC30 with twin 12s. circa 1968, which is what I believed the Beatles used to use. I know I was a fool to sell it but I was only a kid. That Vox would stand up to any drummer with any drums. but there are some good reasons.
The Vox AC30 was rated at 30 watts RMS, which is the continuous output rating. Vox valve amps often peaked at more than twice the continuous rating. Solid state amps never exceed the continuous rating hence valve amps are usually a lot louder for the wattage and are usually paired with better speakers.
Speakers also add volume. Goodman Audiom 15w 12" speakers were used in my model AC30. They had huge magnets and made the amp weigh in at something like 60 pounds which made it a huge throbbing monster that would kick and hiss at you when you had it above 5 or 6. It was almost as loud as the more modern Marshal 100 with 4x12s. It was a "Dirty' amp at almost any volume with almost no clean headroom. At times we even played a bass through it at the same time as a guitar, but it admittedly sounded a little rough, but it worked.
The Vox AC30 that I remember had rows of valves and got really hot. Todays valve amps usually advertise that they have one or two valves and are not the same beasts as they once were but the tone is still there and the volume.
Fast forward to today, I use a Fender Mustang II 20watt with an 8" speaker when I go down to jam at my local pub. I can play lead on it and its loud enough to be heard over most drummers, but the venue is fairly small.  As the venues get bigger, bigger and better speakers seem to make a difference.
To be loud enough to be heard over the loudest drummer you need to have 40 watts or more for a SS amp but 20 watts is seems good enough with a good valve amp with good speakers provided the venue is fairly small. As the venue gets larger, amp wattage and number/size of speakers has to go up. This of course can get uncomfortable for those playing, so then the best option is to mice the smaller amps through a good PA system.
Comment: The AC30s (and 50s) I used in the '60s had jennings (or jennens?) as original speakers. None of mine were very loud. Goodmans Axiom were not original.  General valves at the time were a couple of EL34s and 4 ECC83, I think. DI ing is the usual way to go these days, or use mics, with all their inherent problems.
Comment: 'mice the smaller amps through a good PA system.' Just wondering: would it be louder if you used rats? It's hard to know...
Answer: Others have answered in good detail- especially Alex Basson's answer.
Perhaps a few rules of thumb might work- this is from my experience (so please feel free to add "ah but.." comments if need be):
In terms of watts ..
If you're using an electric guitar,

Under 50watts is possibly enough to play with a drum kit, but will depend a lot on the amp
Over  50watts is probably loud enough to use with a drum kit, if you don't mind with a bit of "crunch"
Over 100 watts is likely to give you enough headroom to give you any sound you like (clean/distorted) with a drum kit.

If you're playing an acoustic guitar through a clean amp, full range (that is:  The amp must reproduce the sound as accurately as possible):

Under 150 watts might struggle, and start to distort
Over 150 watts is likely to be ok with a drum kit

Given you want the sound to be clean, any more wattage just means more volume- it won't change what sounds you can get out of the amp.
There's also speaker size/number : Some amps claim to be quite loud (high watts) but have, say, only one 12" speaker which might not be meaty enough to output the full chunky sound that you'd like, and when you turn them up they go a bit weedy. I'm thinking of my 1990's Session amp here. I think it's 75W but it really needs a speaker cab to help it out.
To play alongside a drum kit, you probably want either a 15" speaker or twin 12" speakers.
There are exceptions of course, but if I was looking for an amp for use with a band, this is the way I'd be thinking.
My own amp is a circa- 1970 Marshall (valve) JMP 50w with a cab containing  2 x 12" drivers. It's just starting to get to its limit of clean sound (quite nicely) at the kind of volume that's right for playing with a mediumly-played drum kit (not brushes, not mental earbleeder), so if I poke it up a bit for solos, it has a bit of crunch.
Answer: From my personal experience of building audio amplifiers, I have built a 1W amplifier that sounds quite loud through a good speaker. Even this 1W through a good speaker would be annoying to neighbours. A 5W amplifier through the same speaker is a little louder. I could only tell a very slight increase in volume between 5W and 10W through the same speaker. 20W was noticeably louder than 10w but 40w only slightly louder. The quality of the speakers is much more important than the power an amplifier can produce. Sound is about air waves, a speaker makes air move. Imagine the air a 2.5" speaker that can handle 20W can move versus a 12" speaker rated at 20W? Put just 1W into them both and you will see which is the winner.
Summary:

To play electric along with an acoustic guitar you would need 5-10Wthrough a good speaker
20W through a good speaker to play to a room with people with no other instruments.
To play with drums you'd need 50W+ into 2-4 x very good speakers in a cab for heavy rock drumming probably 100W into a 4x12" cab.

If you are playing to a large crowd, these numbers become irrelevant because it will be put through the PA system. In which case you want to go with the tone of amplifier you like best. A small overdriven 10W tube amp can be heard by everyone! The engineer will mic up your amplifiers and deal with the sound levels at the mixer.
Answer: Hmmmm. Well I admit I dont do numbers and i am not a scientific brainbox..  Im just an old guy that has played guitar ( or claims to)  for loads of years.
What do i think? .
Well i know what my ears tell me (gettin deafer now though) I know and have owned the old valve marshall stacks,fender twins 100 watt. Had little amps too, However I came across a Harley Benton 120 watt, price was right and sounded fine..  Then i moved ( DOWNSIZING)  to a 1 bedroom flat. :'(   BUT during the day i could CRANK IT UP full and sounded fine,  I had the downsizing bug and saw a Marshall haze 15. vallve halfstack, 15 watts and i cant even get the valves to kick in  on distortion channel i have gain cranked and volume just about 1 or 2.  Clean channel  only just past 1
It is so incredibly loud.  It puts the 120 watt HB to bed.
I admit I have pushed it on a few occasions but i have to make sure neighbours  are out or ok with it.  I STILL COULDNT CRANK IT.  It is a great bit of kit.
I also have a Rolland cube.  Thats just for takin outside.
There is only two things I dont like  about the Haze 1 no aux in/out an 2 no headphone socket. A drag for a flat. But it's  staying i love it lol.
Sometimes it is also " Where you live  as to how loud you can kick it "  without "official complaints"
I have just got a volume pedal and have yet to try and crank the amp an see how that works. .  Fingers crossed.
Anyway
PEACE OUT N KEEP ON ROCKIN
( I may be old  but i nevah stop lernin)
![this is my hifi (1000 wat bt speaker and my Haze 15,, oh an Alesis mixer to bring varied options :-D  ( the little tower on top is a filter fan btw)    (https://i.stack.imgur.com/EBgkI.jpg)


How to show that a process has independent increments and is, as a result, Poisson?

Question: Question
$N$ Daleks are invading Earth, where $N$ is a Poisson random variable with mean $\lambda$. Assume each Dalek dies independently. Let $X_i$ be the lifetime of the $i^{th}$ Dalek in the battlefield, which is a positive random variable with PDF $f$ and CDF $F$ and $N(t)$ be the number of Daleks who have died by time $t$.
$(a)\quad$ Find the mean of $N(t)$ for each $t > 0$.
$(b)\quad$ Identify the distribution of $N(t)$ for each $t > 0$.
$(c)\quad$ Show that, for any $0 \leq t_1 < t_2 \leq t_3 < t_4$, $N(t_2) - N(t_1)$ and $N(t_4) - N(t_3)$ are independent. What type of process is $N(t)$?

I have thought long and hard about this problem, but as my professor has just covered Poisson processes, I probably do not have enough exposure to know what the problem requires, so I would like to know how to approach each part. In particular, how do I show that $N(t_2) - N(t_1)$ and $N(t_4) - N(t_3)$ are independent? Any intuitive solutions for the three parts will be greatly appreciated :)
Edit
I have made some progress following some help from an answer. In particular, I know that $N(t)$ is a thinned Poisson random variable with parameter $\lambda F(t)$. However, I am still unsure of my working for part $(c)$, which I replicate below:
Consider the case when $t_3 = t_2$.
$$\begin{aligned}
\implies & \mathbb{P}[N(t_4) - N(t_3) = x, N(t_2) - N(t_1) = y)]\\[1 mm]
& = \mathbb{P}[N(t_4) - N(t_2) = x, N(t_2) - N(t_1) = y)]\\[1 mm]
& = \sum^{\infty}_{z = 0} \mathbb{P}[N(t_1) = z, N(t_2) = z + y, N(t_4) = z + y + x]\\[1 mm]
& = \sum^{\infty}_{z = 0} \mathbb{P}[N(t_1) = z]P_{z, z + y}(t_2 - t_1)P_{z + y, z + y + x}(t_4 - t_2)\\[1 mm]
& = \sum^{\infty}_{z = 0} \mathbb{P}[N(t_1) = z]P_{0y}(t_2 - t_1)P_{0x}(t_4 - t_2)\\[1 mm]
& = P_{0y}(t_2 - t_1)P_{0x}(t_4 - t_2)\\[1 mm]
& = \mathbb{P}[N(t_4) - N(t_2) = x]\mathbb{P}[N(t_2) - N(t_1) = y)]\\[1 mm]
& = \mathbb{P}[N(t_4) - N(t_3) = x]\mathbb{P}[N(t_2) - N(t_1) = y)]
\end{aligned}$$
Now, consider the case when $t_3 > t_2$.
$$\begin{aligned}
\implies & \mathbb{P}[N(t_4) - N(t_3) = w, N(t_3) - N(t_2) = x, N(t_2) - N(t_1) = y)]\\[1 mm]
& = \sum^{\infty}_{z = 0} \mathbb{P}[N(t_1) = z, N(t_2) = z + y, N(t_3) = z + y + x, N(t_4) = z + y + x + w]\\[1 mm]
& = \sum^{\infty}_{z = 0} \mathbb{P}[N(t_1) = z]P_{z, z + y}(t_2 - t_1)P_{z + y, z + y + x}(t_3 - t_2)P_{z + y + x, z + y + x + w}(t_4 - t_3)\\[1 mm]
& = \sum^{\infty}_{z = 0} \mathbb{P}[N(t_1) = z]P_{0y}(t_2 - t_1)P_{0x}(t_3 - t_2)P_{0w}(t_4 - t_3)\\[1 mm]
& = P_{0y}(t_2 - t_1)P_{0x}(t_3 - t_2)P_{0w}(t_4 - t_3)\\[1 mm]
& = \mathbb{P}[N(t_4) - N(t_3) = w]\mathbb{P}[N(t_3) - N(t_2) = x)]\mathbb{P}[N(t_2) - N(t_1) = y)
\end{aligned}$$
Thus, in both cases, we have independence and can conclude that $N(t_2) - N(t_1)$ and $N(t_4) - N(t_3)$ are independent $\forall\ 0 \leq t_1 < t_2 \leq t_3 < t_4$. In particular, $N(t)$ is a homogenous Poisson process.
Is my reasoning sound and in particular, would I be able to actually combine both cases?
Comment: Is the lifetime PDF $f$ specified somewhere else, or is it intended to be arbitrary?
Comment: @angryavian This is the entire problem, so I suppose it is intended to be arbitrary? There are parts (d) and (e) too, but they relate to a compound Poisson process defined in part (d) itself, so I actually intended to write about it in another post once I have understood parts (a) to (c) here.
Comment: Then shouldn't your answers depend on $f$?
Comment: I'm not sure (c) is even true. It obviously is not if you replace the assumption that a Poisson number of Daleks initially exist with a deterministic number (because then if $N(t_2)-N(t_1)=N(0)$ (i.e. all the Daleks died between $t_1$ and $t_2$) then $N(t_4)-N(t_3)$ must be $0$ (they're all dead before $t_3$ so no more can die before $t_4$).
Comment: I've definitely seen incorrect/incomplete exercises written down before. But I think the Poisson nature of the initial population changes things.
Comment: It's not actually a standard Poisson process unless the lifetimes are exponentially distributed.
Comment: @Ian Yes... And the question does not provide that information (the pdf of the lifetime is deliberately left vague). According to my professor, he says that we should be able to prove this from "first principles" using the information provided in the question, but I've got no clue how to proceed...
Comment: Well, you can condition on $N(t_1)$ and sum over that, which gets you the actual value of $N(t_2)$ in each summand. Having that, you can further condition on $N(t_3)$ and sum over *that*, and at that point you have what you need. But this seems awfully laborious considering how simple the previous two parts are.
Comment: @Ian hmm… I think I am getting what you are saying. In other words, I should try to prove $N(t_2) - N(t_1)$ is independent of $N(t_3) - N(t_2)$ first and then do the same for $N(t_4) - N(t_3)$ and $N(t_3) - N(t_2)$?
Comment: No, I'm not talking about proving this for overlapping increments. You want to say that the distribution of $N(t_4)-N(t_3)$ is the same even when conditioned on a value of $N(t_2)-N(t_1)$. The distribution of $N(t_4)-N(t_3)$ depends explicitly on $N(t_3)$. So you condition on $N(t_3)$. But $N(t_3)$ depends on $N(t_2)$. So you condition further on $N(t_2)$. You already conditioned on $N(t_2)-N(t_1)$, so to know $N(t_2)$ you finally *also* condition on $N(t_1)$.
Comment: @Ian I have tried a somewhat different approach now. Would you be so kind as to take a look at my edit and see if that makes sense to you?
Answer: Conditioned on $N=n$, the distribution of $N(t)$ is $\text{Binomial}(n, F(t))$.

(a) So, $E[N(t) \mid N=n] = nF(t)$. Thus,
$$E[N(t)] = E[E[N(t) \mid N]] = E[N\cdot F(t)] = \lambda \cdot F(t).$$

(b) For the unconditional distribution of $N(t)$, again go through conditioning on $N=n$.
\begin{align}P(N(t)=k)
&= \sum_{n = k}^\infty P(N(t)=k \mid N=n) P(N=n)
\\
&= \sum_{n=k}^\infty \binom{n}{k} F(t)^k (1-F(t))^{n-k} e^{-\lambda} \frac{\lambda^n}{n!}
\\
&= \sum_{n=k}^\infty e^{-\lambda F(t)}\frac{(\lambda F(t))^k}{k!}
\cdot e^{-\lambda (1-F(t))}\frac{(\lambda (1-F(t)))^{n-k}}{(n-k)!}
\\
&= e^{-\lambda F(t)} \frac{(\lambda F(t))^k}{k!}.
\end{align}

(c)
$$P(N(t_2)-N(t_1) = k, N(t_4)-N(t_3)=k') = P(N(t_2)-N(t_1) = k) \cdot P(N(t_4)-N(t_3)=k')$$
for any $k,k'$. I suspect if you start from the left-hand side and do a similar conditioning on $N=n$ you can arrive at the final result with a lot of tedious accounting. Not sure if there is a slicker way. I may revisit this later.
Comment: Thank you for the quick answer! I will be glad to see any further in-depth answers for part (c) later on, but firstly, may I know how you deduced that the probability for the binomial is $F(t)$?
Comment: @EthanMark The probability that the $i$th Dalek is killed by time $t$ is $P(X_i \le t) = F(t)$.
Comment: I have now understood fully parts (a) and (b) and I think I have also made some progress regarding (c), which I have shown in an edit to my post. Are you able to help me from there or at least tell me if I am on the right track?


How well should I know understand the theorem before proving it?

Question: Im reading "How to prove it" by velleman, and in a lot of the exercises you need to prove some theorem is true.
How well should I understand why the theorem is actually true before proving it? For me it's pretty easy to prove something just by following the rules, but idk if that's smart.
For example:
Suppose $R$ and $S$ are symmetric on $A$.
Prove that $R\circ S$ is symmetric iff $R\circ S=S\circ R$
Here is my answer:

Before writing the proof, I didn't take the time to fully understand why its true, but I could still write the proof by following the rules.
What I mean by not fully understanding it, is that if someone asked me:
"If you have two relations on a set, why is it true that their composition is symmetric if and only if their composition is commutative?"
I could only explain it by doing a step by step proof.
I feel like that kind of says I don't understand relations, compositions and symmetricity. Because with something like 2+2=4 I obviously understand why its true without writing a proof.
Comment: Your question is clear and imo very interesting, but too general to get an appropriate answer, I think. As for you example, the "reason why" is that a relation $R$ is symmetric iff it is equal to its opposite $R^{op},$ and that $(R\circ S)^{op}=S^{op}\circ R^{op}.$
Comment: But can you *prove* that 2+2=4?
Comment: Sometimes it's probably not possible to recast the result to something that allows you to understand why it is correct, such as the product of $3384$ and $2187$ is equal to $7400808.$ Other times such a reduction may not occur until you learn more, such as what @Anne Bauval said in a comment. Indeed, a large part of the "theory-building" part of mathematics is seeking such reductions (see [*The Two Cultures of Mathematics*](https://www.dpmms.cam.ac.uk/~wtg10/2cultures.pdf) by Gowers and [this search](https://www.google.com/search?q=math+%22problem+solving%22+%22theory+building%22)).
Comment: By the way:  Nice proof.
Comment: You asked: "How well should I understand why the theorem is actually true before proving it?" I would say there is no need to understand why the theorem is true before proving it.  Of course, it is nice to have an intuitive understanding of why a theorem is true.  But if you insist on achieving that understanding before you write your proof, then the only theorems you will ever be able to prove are those that are so simple that you can see intuitively why they are true before working out the proof.
Answer: Some theorems have profound proofs, and require developing a clever idea. And some theorems follow very directly from definitions, and their proofs are basically bookkeeping*. Your example seems to be of the latter type, and I wouldn't worry about the way you're approaching them.
Of course, even trivial facts can be seen in a more general setting, and one can get a bit more insight viewing them that way. That's what AnneBauval's comment does. But that usually comes later, and you're not expected to come up with that insight the first time you encounter an idea.
*In algebraic topology there are some theorems whose proof just say "diagram chase", which means "At each step there is only one obvious thing to do. If you do that, everything does in fact work out.".


Tilegrid error in Phonegap

Question: I'm constantly having this error:
06-27 10:19:40.503: E/TileGrid(24474): Unexpected portion:left, top, right, bottom 0.000000 0.000000 -0.002500 0.018672

06-27 10:19:40.503: E/TileGrid(24474): Unexpected portion:left, top, right, bottom 0.000000 0.000000 -0.002500 1.000000

06-27 10:19:40.503: E/TileGrid(24474): Unexpected portion:left, top, right, bottom 0.000000 0.000000 -0.002500 1.000000

06-27 10:19:40.503: E/TileGrid(24474): Unexpected portion:left, top, right, bottom 0.000000 0.000000 -0.002500 1.000000

06-27 10:19:40.503: E/TileGrid(24474): Unexpected portion:left, top, right, bottom 0.000000 0.000000 -0.002500 1.000000

06-27 10:19:40.503: E/TileGrid(24474): Unexpected portion:left, top, right, bottom 0.000000 0.010391 -0.002500 1.000000

I'm using Phonegap 3.5.0, JQuery 2.1.1 and JQuery Mobile 1.4.2 (targeting Android), and had this error before (in another apps), but it didn't affect the functionalities. This time, however, in my multipage app, it seems to be affecting the pagecontainer('change', 'mypage') method... the page transition works before the error, but after that, it only changes pages by 5 (I'm using swipe events, so it needs 5 swipes to change page, and jumps from 1 to 5, e.g.). The error occurs sometimes after 2 or 3 page changes, other times after 50, so I can't figure it out...
I found this error message in TileGrid.cpp, on android (line 357):
http://osxr.org/android/source/external/webkit/Source/WebCore/platform/graphics/android/rendering/TileGrid.cpp
...but couldn't find a solution.
Any help would be very appreciated!
Answer: Ok, I found the problem and will answer in case someone have the same issue: the problem was I was using JQuery 2.1.1, and JQMobile was expected to work correctly only with 1.9+ versions (it was explained on the documentation).
Changing to JQuery 1.11.1 made page transitions work correctly.

Tilegrid error in Phonegap


Implementing a statistical estimator in Python based on Fortran/Julia code

Question: I'm trying to implement the O(nlogn) algorithm for calculating Sn (a statistical estimator of scale) as described in "Time-Efficient Algorithms for Two Highly Robust Estimators of Scale", Christophe Croux and Peter J. Rousseeuw.
The paper provides Fortran code, and I also found this Julia implementation (function scaleS!) and tried to convert it to Python, but my code doesn't work. I think it's because I keep messing up the indexing - both Fortran and Julia start indexing arrays at 1 and Python starts at 0. So here's the Python code:
def sn(x):
    N = len(x)

    x.sort()
    a2 = [0] * N
    a2[0] = x[round(N / 2)] - x[0]

    for i in range(1, round((N + 1) / 2) - 1):
        nA = i - 1
        nB = N - i
        diff = nB - nA
        leftA = leftB = 1
        rightA = rightB = nB
        Amin = round(diff / 2) + 1
        Amax = round(diff / 2) + nA
        while leftA < rightA:
            length = rightA - leftA + 1
            even = 1 - (length % 2)
            half = round((length - 1) / 2)
            tryA = leftA + half
            tryB = leftB + half
            if tryA < Amin:
                rightB = tryB
                leftA = tryA + even
            elif tryA > Amax:
                rightA = tryA
                leftB = tryB + even
            else:
                medA = x[i] - x[i - tryA + Amin - 1]
                medB = x[tryB + i] - x[i]
                if medA >= medB:
                    rightA = tryA
                    leftB = tryB + even
                else:
                    rightB = tryB
                    leftA = tryA + even
        if leftA > Amax:
            a2[i] = x[leftB + i] - x[i]
        else:
            medA = x[i] - x[i - leftA + Amin - 1]
            medB = x[leftB + i] - x[i]
            a2[i] = min(medA, medB)

    for i in range(round((N + 1) / 2), N - 2):
        nA = N - i
        nB = i - 1
        diff = nB - nA
        leftA = leftB = 1
        rightA = rightB = nB
        Amin = round(diff / 2) + 1
        Amax = round(diff / 2) + nA
        while leftA < rightA:
            length = rightA - leftA + 1
            even = 1 - (length % 2)
            half = round((length - 1) / 2)
            tryA = leftA + half
            tryB = leftB + half
            if tryA < Amin:
                rightB = tryB
                leftA = tryA + even
            elif tryA > Amax:
                rightA = tryA
                leftB = tryB + even
            else:
                medA = x[i + tryA - Amin + 1] - x[i]
                medB = x[i] - x[i - tryB]
                if medA >= medB:
                    rightA = tryA
                    leftB = tryB + even
                else:
                    rightB = tryB
                    leftA = tryA + even
        if leftA > Amax:
            a2[i] = x[i] - x[i - leftB]
        else:
            medA = x[i + leftA - Amin + 1] - x[i]
            medB = x[i] - x[i - leftB]
            a2[i] = min(medA, medB)

    a2[N] = x[N] - x[round((N + 1) / 2)]
    lomed = a2[round((len(a2) + 1) / 2)]

    return lomed

Answer: Here is a working direct translation from the Julia function. The fastest method that I generally use to convert any Julia code into Python is: comment out all ends and put the : for all conditionals and loops, subtract 1 from all indices, finally replace equivalent functions.
These are some specific points for your code. Note that I removed the lomed function and put sum as I'm not familiar with the low median concept in statistics.

Since Python starts indexing arrays at 0, you'll need to adjust some of the indices in your code to match that.
The line round(N / 2) needs to be changed to N // 2 since Julia uses div and Python equivalent is //.
In the for loop where i goes from 1 to round((N + 1) / 2) - 1, you'll need to adjust the indices in the slice x[i - tryA + Amin - 1] so that they start at 0 instead of 1.
In the second for loop where i goes from round((N + 1) / 2) to N - 2, you'll need to adjust the indices in the slice x[i + tryA - Amin + 1] so that they start at 0 instead of 1.

def sn(x):
    N = len(x)

    x = sorted(x)
    a2 = [0 for _ in range(N)]
    a2[0] = x[N//2]-x[0]
    for i in range(2,(N+1)//2+1):
        nA = i-1
        nB = N-i
        diff = nB-nA
        leftA = leftB = 1
        rightA = rightB = nB
        Amin = diff//2+1
        Amax = diff//2+nA

        while leftA < rightA:
            lent = rightA-leftA+1
            even = 1 - lent%2
            half = (lent-1)//2
            tryA = leftA+half
            tryB = leftB+half
            if tryA < Amin:
                rightB = tryB
                leftA = tryA + even
            elif tryA > Amax:
                rightA = tryA
                leftB = tryB+even
            else:
                medA = x[i-1]-x[i-tryA+Amin-2]
                medB = x[tryB+i-1] - x[i-1]
                if medA >= medB:
                    rightA = tryA
                    leftB = tryB+even
                else:
                    rightB = tryB
                    leftA = tryA+even
                # end
            # end
        # end
        if leftA > Amax:
            a2[i-1] = x[leftB+i-1]-x[i-1]
        else:
            medA = x[i-1]-x[i-leftA+Amin-2]
            medB = x[leftB+i-1]-x[i-1]
            a2[i-1] = min(medA,medB)
        #end
    #end

    for i in range((N+1)//2+1, N):
        nA = N-i
        nB = i-1
        diff = nB-nA
        leftA = leftB = 1
        rightA = rightB = nB
        Amin = diff//2+1
        Amax = diff//2+nA
        while leftA < rightA:
            lent = rightA-leftA+1
            even = 1-lent%2
            half = (lent-1)//2
            tryA = leftA+half
            tryB = leftB+half
            if tryA < Amin:
                rightB = tryB
                leftA = tryA + even
            elif tryA > Amax:
                rightA = tryA
                leftB = tryB+even
            else:
                medA = x[i+tryA-Amin]-x[i-1]
                medB = x[i-1]-x[i-tryB-1]
                if medA >= medB:
                    rightA = tryA
                    leftB = tryB+even
                else:
                    rightB = tryB
                    leftA = tryA+even
                # end
            # end
        # end
        if leftA > Amax:
            a2[i-1] = x[i-1]-x[i-leftB-1]
        else:
            medA = x[i+leftA-Amin]-x[i-1]
            medB = x[i-1]-x[i-leftB-1]
            a2[i-1] = min(medA,medB)
        # end
    # end # 20

    a2[N-1] = x[N-1]-x[(N+1)//2-1]

    # Normalization
    cn = 1.0
    if N < 10:
        cn = [0, .743, 1.851, .954, 1.351, .993, 1.198, 1.005, 1.131][N-1]
    elif N%2 == 1:
        cn = N/(N-0.9)
    # end
    return cn * 1.1926 * sum(a2)


Custom view for displaying contents in folder

Question: We are using Plone 4.1, and would like to have a custom view of the contents in a folder.
The "Select a content item to be used as a default view in this folder" display won't work for us because we have Private subfolders which should only be listed when the logged-in user has the right permissions.
For example, we have a main folder called "IT".   Inside this "IT" folder, we have subfolders called "Admin", "Users", "FAQ", etc.  The "Admin" folder is not published, i.e. is private, and it should listed in the Folder display view only if the logged-in user is part of the admin group.   The "Users" and "FAQ" folders are published -- so no problem here.
If we use "Select a content item to be used as a default view in this folder", the content page does not have the intelligence to list the "Admin" subfolder only when the logged-in user is  part of the admin group.
We do not want to use the default views, i.e., Summary View, Standard View, Tabular View, although these views are able to list the "Admin" subfolder only when the logged-in user is part of the admin group.
Is there a way to have our own custom view which will display "Admin" subfolder when the logged-use is part of the admin group?
Answer: Yes, you can do this a couple different ways.  It is recommended to do this in a theme product (or other product with a skins folder), but I will also give you instructions for doing this in the ZMI.
(1) Customize the template for one of the default views. Find the original template in Products/CMFPlone/skins/plone_content (copy the original template into your product's skins/templates folder), or in the ZMI at portal_skins > plone_content (click the customize button). Then adjust the template to your liking.
~ or ~
(2) Create a new template that will also be available in the Display dropdown. I would start by using one of the default templates so you have a good place to start from. Put the template in your product's skins/templates folder, or ZMI > portal_skins > custom folder, but this time give it a custom name.  Then in portal_types > Folder, add the template id (the name without .pt) to the list of 'Available view methods'. This information can be exported to a product from portal_setup > export tab, an export the Types Tool.
Answer: Here is a product I created to add a new view to folders and collections that displays event objects in a tabular layout (something different than the default Tabular View). It's a very minimal product and should get you started on creating your own custom template.
https://bitbucket.org/paulrentschler/tabulareventsview


Habilitar campo ao selecionar "Tipo"

Question: Tenho o seguinte campo:

        Tipo
        <select class="input-xxlarge idTipo" name="idTipo" id="idTipo" onChange="getParametro()" style="width: 715px !important;">
        <option value="">Selecione o Tipo</option>
        <option value="819">Faltas</option>
        <option value="60">Atrasos</option>
        <option value="69">Saída Antecipada</option>
        </select>

    Data Solicitado
    <input id="dp1" class="input-small" style="width: 135px" name="data" type="date" required="required">

    Data Cadastro
    <input id="dp1" class="input-small" style="width: 135px" name="data" type="date" required="required">

    Horários
    <input id="dp1" class="input-small" name="hora_inicio" type="time" disabled>
    <input id="dp1" class="input-small" name="hora_final" type="time" disabled>

Gostaria que ao selecionar o idTipo, e se for idTipo = 60, habilitasse então os campos de horários que temos mais abaixo... Como fazer isso em Jquery?
Este jQuery faz a busca do próximo campo (que não coloquei no código ai), mas podemos integrar nesse jQuery para habilitar o horário.
    function getParametro() {
        var id = $('#idTipo').val();
        $(".idParametro").append('<option value="0">Carregando...</option>');
        $.post("<? echo base_url(''); ?>faltas/ajax/parametro/" + id,
            {idParametro:jQuery(id).val()},
            function(valor){
                 $(".idParametro").html(valor);
            }
        );
    }

Answer: Podes ter um oscultador de eventos no jQuery que detete se o select mudou e para o valor 60. Aí coloca ou retira o disabled.
Seria algo assim:
var inputs = $('input[name="hora_inicio"], input[name="hora_final"]');
$('#idTipo').on('change', function(){
    if (this.value == '60') inputs.removeAttr('disabled');
    else inputs.attr('disabled', 'true');
});

jsFiddle: http://jsfiddle.net/ctr0wj6r/

Habilitar campo ao selecionar "Tipo"


Intersection beween circle and line

Question: So I have the circl $x^2+y^2=5$ and the line $y=2x+c$ and I want to find all the points were the two intersect. I know how to solve this for a specific value of $c$, but I do not know how to handle the problem for a general case. Any sugestions?
Answer: HINT
Substituting $y = 2x + c$ in $x^{2} + y^{2} = 5$ results
$x^{2} + (2x + c)^{2} = 5.$ So, the equation is
$$5x^2+4cx+c^2-5=0.$$
The solution then is
$$x_{1,2}=\frac{-4c\pm\sqrt{16c^2-20(c^2-5)}}{10}.$$
That is, $c$ is simply a parameter of the solution.
If $$16c^2-20(c^2-5)<0$$ then there is no intersection.
Comment: Thank you! This was a whole lot easier than i thought it was going to be.
Answer: $$
\begin{cases}
x^2+y^2=5\\
y=2x+c
\end{cases}\Longleftrightarrow
$$
$$
\begin{cases}
x^2+(2x+c)^2=5\\
y=2x+c
\end{cases}\Longleftrightarrow
$$
$$
\begin{cases}
5x^2+4xc+c^2=5\\
y=2x+c
\end{cases}\Longleftrightarrow
$$
$$
\begin{cases}
5x^2+4xc+c^2-5=0\\
y=2x+c
\end{cases}\Longleftrightarrow
$$
$$
\begin{cases}
x=\frac{-4c\pm\sqrt{\left(4c\right)^2-4\cdot 5\cdot \left(c^2-5\right)}}{2\cdot 5}\\
y=2x+c
\end{cases}\Longleftrightarrow
$$
$$
\begin{cases}
x=\frac{1}{5}\left(\pm\sqrt{25-c^2}-2c\right)\\
y=2x+c
\end{cases}\Longleftrightarrow
$$
$$
\begin{cases}
x=\frac{1}{5}\left(\pm\sqrt{25-c^2}-2c\right)\\
y=2\left(\frac{1}{5}\left(\pm\sqrt{25-c^2}-2c\right)\right)+c
\end{cases}\Longleftrightarrow
$$
$$
\begin{cases}
x=\frac{1}{5}\left(\pm\sqrt{25-c^2}-2c\right)\\
y=\frac{1}{5}\left(c\pm 2\sqrt{25-c^2}\right)
\end{cases}
$$
So the solutions are:
$$x_1=\frac{1}{5}\left(-\sqrt{25-c^2}-2c\right)\space,\space y_1=\frac{1}{5}\left(c-2\sqrt{25-c^2}\right)$$
$$x_2=\frac{1}{5}\left(\sqrt{25-c^2}-2c\right)\space,\space y_2=\frac{1}{5}\left(c+2\sqrt{25-c^2}\right)$$

Intersection beween circle and line


Collaborative ontology construction and Prolog

Question: What technologies would be appropriate for creating a web page which lets users add facts, edit facts and query this information? I have been building a knowledge base and inference rules in Prolog but would like to make the facts section and the querying accessible on the web. More specifically i am looking for the following functionality:

A web interface where end users can add and edit facts, e.g. "smoking causes cancer with probability 0.02". This should preferably be something accessible and not involve writing Prolog or other code (e.g. selecting a subject, relation and object from three lists). Here it would also be nice to have some functionality for seeing whether some concepts already exist in the knowledge base (e.g. if a user were to enter a fact about cancer and the concept cancer is already present in the knowledge base, this should be shown, preferably also related concepts). Maybe some drop down menus or lists could achieve this.
Functionality for managing user profiles, passwords, privileges, etc.
A web interface where end users can query the facts section, e.g. "what are causes of cancer?". The rules which compute answers to queries would not be something that end users edit (i want to do this instead). They just see the results in a easy to comprehend format.
A language which is Prolog or as powerful as prolog which i (and not end users) can use to create inference rules (which generate answers to queries from users).
If it is possible, some means for end users to get a graphical representation of the knowledge base.

A summary of what i mean in terms of a Prolog program:
<code>%This kind of thing should be entered by end users in a friendly interface (i.e. not code like here).
causes(smoking, cancer, prob(0.05)).
causes(cancer, death, prob(0.1)).

%This kind  of thing should be entered by me (and not end users)
inferCauses(C, E, prob(P)):-
    causes(C, E, prob(P)).
inferCauses(C, E, prob(P)):-
    causes(C, I, prob(P1)),
    causes(I, E, prob(P2)),
    P is P1 * P2.

%This should be entered by end users, again in a friendly interface
?-whyCancer?
</code>
I know about the excellent SWISH and Pengines but I am not sure if these are full fledged ontology editors or if these can be interfaced to existing ontology editors.
I have also been looking at Protegé, OWL and SWRL rules but I am not sure if these are as powerful as Prolog or in what way they could interface with Prolog.
Any help would be greatly appreciated! Thank you.
/JCR
Comment: "add and edit facts, e.g. "smoking causes cancer with probability 0.02". This should preferably be something graphical and not involve writing Prolog or other code" - what could be more simple then declaring this as a fact?  Do you want to draw a graph to represent the facts or something?  Maybe use a combination of javascript (D3 for example) and pengines?
Comment: If you look at number 11 here: you can see an example of a javascript gui interacting with pengines https://swish.swi-prolog.org/?code=https://raw.githubusercontent.com/samwalrus/reactome_notebook/master/reactome_pengine.swinb
Comment: https://academic.oup.com/bioinformatics/article/34/16/2856/4956665 For more details
Comment: E.g edit something like : http://bl.ocks.org/benzguo/4370043 so that when you draw an edge that makes the facts like: causes(smoking, cancer, prob(0.05)).
Comment: Maybe i was a bit unclear in the original post. By graphical i meant a GUI which could, for example, involve selecting a subject, relation and object from three lists... Does not have to be arrows and such things.
Comment: This looks interesting!
Comment: @user27815 Thanks! I'll read the paper.
Comment: @GuyCoder Sounds good, should i just post my question there in the public forum (or contact you privately? what user name in that case?).
Comment: @GuyCoder yes I am. :)
Comment: @GuyCoder cool no problem :)
Answer: Some more info about this here.
Comment: So what did you decide to do @user3170496?  I followed this link to your post.  Did you end up creating this concept?  Any github repo?


How do I LINQify this?

Question: Is there any way to clean up this type of loop using LINQ?
  List<Car> result;
  List<string> makes;
  List<string> models;

  for (int i = 0; i < makes.Count() && i < models.Count(); i++)
  {
    result.Add(new Car() { Make = makes[i], Model = models[i] });
  }

Basically I'm looking for some way to collate multiple arrays of individual fields into a single array of objects made up of those fields.
Comment: why you haven't a constructor for Car with 2 parameters... Make and Model... ?
Comment: I didn't have one in this case but that would clean things up a bit.  I do like the syntax above though since it allows you to keep from exposing fields in two places.
Answer: You could use Enumerable.Range, like so:
List<Car> result = Enumerable.Range(0, Math.Min(makes.Count, models.Count))
    .Select(i => new Car { Make = makes[i], Model = models[i] }).ToList();

If makes and models always contain the same number of items, you can use more compact syntax:
List<Car> result = makes.Select((make, i) => new Car { Make = make, Model = models[i] }).ToList();

Comment: This works but I was hoping there would be something more syntactically compact.
Comment: I've updated the answer to show an overload of Select() that allows more compact syntax.
Comment: Need a ToList() on the second answer. +1
Answer: It sounds like you really need a new LINQ operator - one which wasn't included in LINQ, somewhat accidentally: Zip. It would basically take two enumerables and return a single enumerable which paired entries, until one or other of the original sequences finished.
I don't have anything like that up my sleeve, but it shouldn't take too long to write if you're interested. The resulting code would be something like:
List<Car> cars = makes.Zip(models)
                      .Select(pair => new Car(pair.First, pair.Second))
                      .ToList();

Let me know if you'd be interested in this and I'll code it up in MiscUtil.
Comment: Actually this would be perfect, even better if it could "Zip" more than just 2 enumerables.
Answer: Depending on how frequently you are going to need to write LINQ queries against these arrays, it may be worth building a class that wraps the arrays and implements IEnumerable<Car>.  Then your code looks like this:
IEnumerable<Car> cars = new MyClass(makes, models);
var result = from cars...

It's not especially complicated to build this; it's just four simple methods (well, six, if you count constructors) spread across two classes (you also need to implement IEnumerator<Car>).
This approach keeps you from having to embed implementation details in all of your LINQ queries.  Also, if you've never done this, it's really something worth learning.  Being comfortable implementing IEnumerable<T> significantly expands the space of things that you can readily use LINQ for.
Answer: List<Car> result = makes
                   .Take(model.Count)
                   .Select((make, index) => new Car {Make = make, Model = models[index]});

Note that this works even if makes and models aren't the same length.

How do I LINQify this?


Acrescentar tags HTML quando aparecer um caractere A-Z javascript

Question: Tenho uma string com o seguinte formato:
let texto = "Dub. - 16h00A, 19h00A, 22h00A"

Gostaria de fazer colocar as tags sup e b entre as letras A. Por exemplo:
let new_texto = "Dub. - 16h00A, 19h00A, 22h00A"

A primeira string é resultado de uma query de banco e existem outras strings neste mesmo formato, porém além do caractere A, podem surgir outros caracteres como B,C,D, etc. Gostaria de fazer uma função para verificar a ocorrência da letra na string e colocar as tags entre esta letra.
Outro exemplo:
let texto2 = Leg. - 18h10D, 18h20C, 21h40D, 22h00C

Como seria:
let new_texto2 = Leg. - 18h10D, 18h20C, 21h40D, 22h00C

O que consegui fazer é fazer a substituição por uma string fixa e não dinâmica de acordo com a letra que aparece. Meu código de teste é esse:
let texto = "Dub. - 16h00A, 19h00A, 22h00A";
    let regex = /[A-Z]/g; // regex de todas as letras do alfabeto maiusculas
    let legenda = texto.substring(texto.indexOf('-') , 0); // pega o tipo de legenda do filme
    let substitui = texto.substring(6).replace(regex, 'A'); // substitui as ocorrências das letras
    console.log(legenda + '-' + substitui);

Comment: Em vez de substring, vc pode substituir somente se a letra estiver depois de "dois números, letra h, dois números", algo assim: https://ideone.com/XYeoAL
Answer: let texto = "Dub. - 16h00A, 19h00A, 22h00A";
let regex = /[A-Z]/g

texto = texto.substring(6).replace(regex, "$&");

Testa isso.
Comment: Melhorou bastante mas ainda o D do Dub está sendo substituído. *Dub. -*
Comment: @Sr.Caveira Deu certo, obrigado. Apenas tinha que substituir nesta linha: let substitui = texto.substring(6).replace(regex, '$&').


.Split() in for loop not returning list

Question: I wrote a for loop that is supposed take win-loss records of a football team and split them, to get a value for games won and games lost. Unfortunately my split('-') command does not seem to be returning a list when used in the for loop I wrote.
The data set was picked up from wikipedia  and the data is within a pandas dataframe.
Here is how I got the dataframe:
test = pd.read_html('https://en.m.wikipedia.org/wiki/
    List_of_Michigan_Wolverines_football_seasons')

year_football = test[-1].T.set_index(0).T.dropna(axis=0, thresh=3)

The list that I am trying to iterate through is:
#format W-L
win_loss = ['7–1' '6–2' '2–6' '1–7' '3–5' '6–2' '6–2' '3–5' '3–5' '6–2' '7–2']

Which I got by doing a bit of cleaning and then calling:
print(year_football['Conference'].values)

My for loop is:
wins = []
games = []

for season in year_football['Conference'].values:
        win_loss = season.split('-')
        wins.append(win_loss[0])
        games.append(int(win_loss[0])) + int(win_loss[1]))
        print(season)
        print(type(season))
        print(win_loss)

The output for the first member of the list is:
7–1 #print(season)
<class 'str'> #print(type(season))
['7–1'] #print(win_loss)

I cant figure out what I did wrong, .split() is working fine outside of the for loop. hoping is not spelling error. (Also running in Jupyter if that helps)
Comment: You are splitting on `-`, but your `season` contains `–` - see the difference? Not the same character.
Comment: `ord('–')` is 8211; `ord('-')` is 45.
Comment: Can @Błotosmętek or DYZ please post an answer so I can delete mine
Comment: And just to clarify, it *is* returning a list, it just isn't split where you want.
Comment: Thanks, didn't realize they were separate characters
Answer: Change your for loop to split on that actual character
for season in year_football['Conference'].values:
        win_loss = season.split(chr(8211))  # I changed this line
        wins.append(win_loss[0])
        games.append(int(win_loss[0])) + int(win_loss[1]))
        print(season)
        print(type(season))
        print(win_loss)

.Split() in for loop not returning list


How to match a range of string that doesn't contain an specific word using only regular expression?

Question: I have a string like this.
var str = "[cat dog] [dog cow] [cow cat] [cat tiger] [tiger lion] [monkey dog]";

I want to match the pair of animals that doesn't contain a specific one.
For example I want to select all pair of animals that doesn't contain dog.
So the output should be
[cow cat]
[cat tiger]
[tiger lion]

Is it possible to match using Regular Expression using str.match() method?
Comment: Dupe of https://stackoverflow.com/questions/37240408/regular-expressions-ensuring-b-doesnt-come-between-a-and-c
Comment: Sorry @CertainPerformance, that question is different.
Comment: No, it's the same, just match `[`, lazy-anything which doesn't contain `dog` (using linked method), then match `]`
Answer: This seems to work:

var regex = /\[(?!dog)([a-z]+) (?!dog)([a-z]+)\]/gi;
var string = "[cat dog] [dog cow] [cow cat] [cat tiger] [tiger lion] [monkey dog]";
console.log(string.match(regex));

The above regex matches only two animals in each pair of brackets - this one matches one or more:

var regex = /\[((?!dog)([a-z]+) ?){2,}\]/gi;
var string = "[cat dog] [dog cow] [cow cat] [cat tiger] [tiger lion] [monkey dog] [one animal two animal three animal]";
console.log(string.match(regex));


Python: Como armazenar a documentação(help) de uma classe numa String?

Question: Eu estou fazendo um explorador explorador de classes em Python. Consigo armazenar os métodos e atributos da classe com
 dir(obj)

e colocá-los num TreeView. Gostaria de exibir as referências deste quando fosse clicado. Para isso eu usaria o texto do
 help(obj)

da classe em questão. Para isso precisaria do texto armazenado numa String, e assim localizar as referências sobre este com
 String.find(nome_do_atributo)

O problema é, que quando chamo o help(obj), ele imprime o texto no outuput. Alguém sabe como fazer com que o texto do help(obj) seja armazenado numa variável, em vez de ser impresso na saída do sistema?
Answer: Sem precisar importar nada, voce poderia usar o atributo _doc_ da funcao ou classe
eg:
def foo():
    """Minha docstring epicamente epica"""
    pass

class Bar():
    """Minha documentacao 100% profissional"""
    pass

func_docstring = foo.__doc__
class_docstring = Bar.__doc__

print(func_docstring)
print(class_docstring)

# Minha docstring epicamente epica
# Minha documentacao 100% profissional

Answer: desculpem a minha barbeiragem, mas ralando bastante consegui achar a solução.
Primeiro, é preciso importar o pydoc
import pydoc

No Python 3:
string_help = pydoc.render_doc(nome_da_classe, renderer=pydoc.plaintext)

E se o nome da classe vier como string:
string_help = pydoc.render_doc(eval("nome_da_classe"), renderer=pydoc.plaintext)

Cuidado: o eval tem seus riscos, pois executa qualquer coisa!!!
No Phython 2, não experimentei, mas dizem que é assim, vou passar passar de boa fé, caso não funcione, me avise.
 string_help = pydoc.plain(pydoc.render_doc(nome_da_classe))

Espero que ajudade.


Which child does jquery pick if there are multiple children?

Question: I have a unordered list
. There are 3 list items in the list and in each item there is an image. Each image has a different width. How does jquery deal with the following.
var width = $('#images li img').width();

which of the 3 image widths will the var 'width' contain?
Comment: It returns the `width` of first `element` among `selected set`.
Comment: @joy if you turn that into an answer I will accept it
Comment: Reading the documentation would have answered this for you: ["Description: Get the current computed width for the first element in the set of matched elements."](http://api.jquery.com/width/#width1)
Answer:
It returns the width of first element among selected set of elements.

Read more on .width()
Answer: It will return the width of the first matched element - http://jsfiddle.net/FGchc/
Answer: The description for the width method:

"Get the current computed width for the first element in the set of
  matched elements."

So, it will return the width of the first of the matched elements.
Answer: The first image's width. And jQuery works depth first so in the following:

The img inside div will be the first img.


Trying to change a radio value during form validate

Question: I have a form that includes a set of radio inputs, and other fields that will or will not be relevant, depending on which radio option is selected. I'm using #states for client-side UX sugar.
However there are certain conditions, picked up in the validate function that need to change the value the user entered for the radio, and re-present the form with a different option selected. I'm having problems with this, as the form comes back but the option is not changed. e.g. Submitting this should with 'a' selected should change it to 'b' and re-present.
What happens is that the value is set to b, the form rebuilds, but the browser still shows 'a' selected.
<?php
function x_a_form($form, &$form_state) {
  return [
    'switcher' => [
       '#type' => 'radios',
       '#options' => [
           'a' => 'Aye',
           'b' => 'Bee', ],
       '#default_value' => empty($form_state['values']['switcher'])
                           ? 'a'
                           : $form_state['values']['switcher'],
    ],
    'submit' => ['#type' => 'submit', '#value' => 'Go' ],
  ];
}

function x_a_form_validate($form, &$form_state) {
  // silly example of a condition...
  if ($form_state['values']['switcher'] == 'a') {
     // Change the value.
     // Nb. form_set_value() is a very long winded way to do just this:
     $form_state['values']['switcher'] = 'b';
     // We will not be saying anything is invalid, but we don't want
     // the form to submit.
     $form_state['rebuild'] = TRUE;
     return;
  }
  // other validation...
}

Comment: What about using jquery and something like this: http://stackoverflow.com/questions/7757381/change-form-option-through-a-function-with-js-or-jquery
Answer: Did a little more digging. It seems when Drupal (re)builds a form, it sets the element values based on the actual form input ($form_state['input']) and not the form values ($form_state['values']). See _form_builder_handle_input_element. So form_set_value does changes the form value, but it does not update the form input and, therefore, does not get processed how you want it to in this case. While I don't know if this is the "proper" way to do this, but in your form function, you can try throwing in something like:
if (!empty($form_state['values']['myelement']) {
  $form_state['input']['myelement'] = $form_state['values']['myelement'];
}

I tried this with a textfield element, and the value I set using form_set_value was displayed in the textfield when the form was rendered.
Comment: Came to same conclusion. Thanks, accepted your answer. Basically what happens is: form build → copy input to values → validate changes values and sets rebuild → rebuild triggers form build → original input copied **again** over values. So values set in validate that are in input are lost when rebuild is triggered.
Comment: Pls see comment in my code and/or the source for that function on the page you linked to.
Comment: Sorry, missed that part. Long winded or not, form_set_value does what you want it to do. You could alternatively set a separate variable in $form_state. Something like $form_state['my_module']['switcher'].
Comment: My point is that it doesn't do anything. You can replace that line of code with form_set_value(['#parents'=>['switcher']], 'b', $form_state) and the behaviour is identical.
Comment: Edited my answer. Please see.
Comment: Would you remove the first part of your answer, which is not part of the solution? For others' +future reference.


Can we write an algorithm which gives me two whole numbers X and Y when I want to get a desired fraction F such that F= X/Y?

Question: I am working to prepare a test data set in which I have to check rounding. Suppose I want to check round, round_up and round_down is working correctly at 10 th decimal place or not.
Then

if, X=100 and Y = 54 so, X/Y = 1.8518518518518518518518518518519 (test round equidistant)
if, X= 10 and Y = 7 so, 1.4285714285714285714285714285714 (test round_up)
if, X= 10 and Y = 3 so, 3.3333333333333333333333333333333 (test round_down)

Can we write an algorithm in which

input will be rounding mode (round_up, round, round_down) and decimal place I want to round at(in our example 10)
output will be X and Y like above?
Comment: This is a problem that's solved in lots of languages on the Rosetta Code site: http://rosettacode.org/wiki/Convert_decimal_number_to_rational.
Comment: Are there any more requirements on `X` and `Y`? Because otherwise you can select `Y=10^{number of digits you need+1}` and easily select `X`.
Answer: If the required location is p (=10 in your example), then y=10^p and then you can choose any x you want.
Depending on the language you are using, p might be too big for you to do 10^p, so in the worst case just divide the result from x/y by 10, 100 or whatever is necessary.
Comment: 10 is given as an example. My input will be like that
Give me two whole numbers X and Y, when I divide them, the fraction will have 5 at suppose 6 th place
Comment: Also, taking from your example of x=100 and y=54 giving you 5 in the 10th place, you can just multiply x by 10^(something) and get that            x/y=1851.8518518 **5** 1851
Answer: Actually, if the required digit is d, then if d is not 9, the answer would be x=d,y=9 regardless of p which is the position of the digit. If d is 9, then if p is odd, the answer is x=10,y=11 and if p is even, x=1,y=11. If a trivial answer for d=0 won't do, the mirror answer for d=9 is suitable, that is, if d=0 and p is odd, the answer is x=1,y=11, and if p is even, x=10,y=11. A lot shorter than an answer with y=10^p and certainly fitting in nearly any architecture.
Answer: Or you can do like this
# n = number of fraction you want to return
def getFraction(a, b, n):
    result = ""

    for i in range(n):
        f = int((a % b) * 10 / b)
        result += str(f)
        a = a * 10 - b * f

    return result

 getFraction(10, 7, 11) # return 42857142857 which 10/7 = 1.42857142857...

What I do is like what you have learnt in elementary school on how to do division by pen and paper.


Regression with paired, repeated measures design

Question: I have a large population of books. Each book is either a hardback or softback (thus hardback and softback books are paired with one another by title), and can fall into two categorical genres - Action or Thriller. For each book, the sales volume is measured annually (hence it is a repeated measures design). Importantly, some books have sales measurements over many years, whilst for some books it was only possible to measure sales for the first year or two years.
Data are structured as followed, just as an example. There are approximately 10,000 books in the sample (5,000 hardback, 5,000 softback).
Title    Type        Genre       SalesYear1   SalesYear2   SalesYear3
AAA      Hardback    Action      100          150          180
AAA      Softback    Action      80           105          125
BBB      Hardback    Thriller    50           90           110
BBB      Softback    Thriller    20           45           80
CCC      Hardback    Action      120          200          --
CCC      Softback    Action      120          245          --
DDD      Hardback    Action      75           --           --
DDD      Softback    Action      95           --           --
...      ...         ...         ...          ...          ...

I want to conduct a regression analysis to determine whether hardback books have higher sales than softback books, taking into account other variables, i.e. genre of the book, as well as time.
For a single year, I could potentially do this with a linear regression model assuming sales were normally distributed, as follows (with R):
lm(formula = SalesYear1 ~ Type + Genre, data=data)

summary(lm)

However, this does not take into account the paired nature of the books, and ignores the repeated measures approach. How might I do this? I have read that the lmer function of the lme4 package would be suitable. In that case I would reorder my data into a long format, with a single column for Sales, and a column for Time, and then do something like:
lmer(Sales ~ Time + Type + Genre + (Type| Title), data = data)

This would seem to account for the nesting of Title in Type, but I don't know if another random effect is required for Time. Does this syntax look right? I'm very confused - any pointers to resources would be much appreciated.
Comment: I don't see why you can't do a paired T test. Each factor in your dataset is a between-cluster factor. If you calculate paired differences, you remove the influence of the factor. If you want to know about the ancillary factors, you can sum the sales values and use those in a regression model against year and genre.
Answer: You have indeed a complex type of design and a rich dataset to explore it. A couple of considerations:

To explore the following (nested) structure, you will need to put the data in the long format with measurements over time in the same book and type put one underneath the other, and also create a time variable.
It would be expected that sales of the same book over time are correlated. To explore this, you will need to include random effects for the Title grouping factor.
Moreover, sales in the same type may be more correlated than measurements from different types. To explore this you will need to include a nested random effect for Type.
In the fixed effects if you only include the main effect of Type you postulate that the difference between types is constant over time. If you want to explore whether the difference between types changes over time, you will need to include the interaction of Type with Time.
Logically you would expect that the sales of a book over time would follow a nonlinear pattern. To explore this you could include splines of time.
Putting all these together, some potential models to consider are:

# Random intercepts & linear random slopes nested random effects
fm_nested <- lmer(Sales ~ ns(Time, 3) * Type + Genre +
                  (Time | Title) + (Time | Title:Type), data = data)
# Random intercepts and linear random slopes only for Time
fm_title <- lmer(Sales ~ ns(Time, 3) * Type + Genre +
                  (Time | Title), data = data)
#Likelihood Ratio Test between the two models
 anova(fm_titleRE, fm_nested)
Function ns() is from package splines and is used to model a potential nonlinear time effect using natural cubic splines.

You will also need to explore the residuals to see if the assumptions of the model are validated.


how to cbind and keep latest columns if duplicated in r

Question: I have a dataframe in r
 df1
 a   b   c   d    e
 1   2   3   4    5

 df2
 c   d   e
 10  11  12

When I cbind both df1 and df2 I want to retain columns of df2.
My final dataframe would be
 a  b  c   d   e
 1  2  10  11  12

How can I do it in r?
Comment: are you looking to replace values of df1 with df2 values for c, d, e
Answer: You could use modifyList for this
df1 <- data.frame(a=1,b=2,c=3,d=4,e=5)
df2 <- data.frame(c=10,d=11,e=12)

modifyList(df1, df2)
#   a b  c  d  e
# 1 1 2 10 11 12


Sumbit user name and surname and go to the next page

Question: I can't figure out how to connect function that will save name and surname in local storage and go to the other page. If you could point out the problem I would be very grateful :)
index.html
<form id="from" action="" method="post">

 Име

        <input id="name" name="name" type="text"  required>

 Презиме

        <input id="surname" surname="surname" type="text"  required>

    <button onclick="sumbit()"> Започни тест </button>
</form>

script.js
let infs = [];
    const addInf= (ev)=>{
        ev.preventDefault();  //to stop the form submitting
        let inf = {
            id: Date.now(),
            name: document.getElementById('name').value,
            surname: document.getElementById('surname').value
        }
        infs.push(inf);
        document.forms[0].reset(); // to clear the form for the next entries

        //saving to LS
        localStorage.setItem('MyInfList', JSON.stringify(infs) );
    }
    document.addEventListener('DOMContentLoaded', ()=>{
        document.getElementById('btn').addEventListener('click', addInf);
    });

Comment: it should store data in the local storage
Comment: With this code it is storing, I can not figure out how to redirect to the other HTML page with the same button :)
Answer: Try this, use window.location for redirecting to another page, it has same functionality as href.
<form id="from" action="" method="post">

 Име

    <input id="name" name="name" type="text" required>

 Презиме

    <input id="surname" surname="surname" type="text" required>

  <button id="btn"> Започни тест </button>
</form>


What NFL teams have been shutout in consecutive games?

Question: Miami Dolphins were almost shutout for the 2nd consecutive game. A TD as time expired last week vs. Jets are only points Miami has in last 2 games.
Has a team ever been shutout in consecutive games?
Answer: There are many teams who have been shutout in consecutive games. Searching after 1970 Oakland Raiders had been shutout in 3 games consecutively. While the record is of 7 consecutive games shared by Louisville Colonels and Hammond Pros. The most recent consecutive shutout was of Cleveland Browns.
Using team streak finder of pro-football-reference.com the table generated is as follows:

(Source)
Complete table:

(Source)
Most recent:
Comment: +1.  Most recent occurrence of back-to-back shutouts was the [Cleveland Browns in December 2008](https://www.pro-football-reference.com/play-index/team_streak_finder.cgi?request=1&streak_type=games&year_min=1970&year_max=2017&game_type=R&game_num_min=0&game_num_max=99&week_num_min=0&week_num_max=99&streak_event=points&streak_event_gtlt=eq&streak_num=0&streak_event_gtlt_2=gt&streak_length=2).


Find logarithm of matrix in diagonalform

Question: I'm trying to decide whether there is a matrix $A \in \text{Mat}(2, \mathbb{R})$ with
$$e^A = \begin{pmatrix}1 & -1 \\ -1 & 1\end{pmatrix}$$
I was already able to diagonalise the matrix into
$$\begin{pmatrix}1 & -1 \\ -1 & 1\end{pmatrix} = S^{-1} \cdot \text{diag}(0, 2) \cdot S \hspace{30pt} \text{with} \hspace{30pt} S = \begin{pmatrix} 1 & 1 \\ 1 & -1
\end{pmatrix}$$
I'm not sure how to proceed from here. What could be the next step?
Answer: The answer is negative: $e^A$ cannot have a vanishing eigenvalue; in fact it is always invertible and the inverse is $e^{-A}$. So the matrix $A$ does not exists
Comment: Thank you really much. This is a neat solution. Do you have an idea how to decide in the case $e^A \stackrel{!}{=} \begin{pmatrix}1 & 0 \\ 0 & -1\end{pmatrix}$?
Comment: Use the remark of José Carlos Santos: $ \det e^A=e^{\textrm{Tr}A}>0$
Answer: There is no such matrix. If there was a matrix $B$ such that $e^B=A$, then\begin{align}0&=\det A\\&=\det e^B\\&=e^{\operatorname{tr} B}.\end{align}
Comment: Thank you. Till now I didn't know about the trace formula. Is there an intuitive explanation for this? For now I'm accepting @DiegoG7's solution, since it only used the non-singularity of matrix-exponentials.
Comment: If $A$ is upper triangular, the entries of the main diagonal of $e^A$ are the $e^{a_{ii}}$'s and therefore its determinant is$$\prod_{i=1}^ne^{a_{ii}}=\exp\left(\sum_{i=1}^na_ii\right)=e^{\operatorname{tr}A}.$$
Comment: Thanks a lot, but how do we know that $e^B$ is upper triangular?
Comment: And don't understand you question. There was no $B$ in my comment.
Comment: I'm also looking for the existence of the logarithm of $\begin{pmatrix}1 & 0 \\ 0 & -1 \end{pmatrix}$. Can this approach be used here?
Comment: Oh, excuse me. "If $A$ is upper triangle.." why can we assume that $A$ is upper triangle?
Comment: We can't. But *every* square matrix is similar to an upper triangular matrix.
Comment: This does makes sense. Thank you for the explanation.
Comment: Concerning your new question, I suggest that you post it as such.


What is the intuition behind the law of quadratic reciprocity?

Question: Law of quadratic reciprocity states as follows:

Law of quadratic reciprocity — Let $p$ and $q$ be distinct odd prime numbers, and define the Legendre symbol as:
$$ \left(\frac {q}{p}\right)=\left\{\begin{array}{rl} 1 & \text{if } n^2\equiv q \pmod p \text{ for some integer } n, \\ -1 & \text{otherwise.} \end{array} \right.$$
Then:
$${\displaystyle \left({\frac {p}{q}}\right)\left({\frac {q}{p}}\right)=(-1)^{{\frac {p-1}{2}}{\frac {q-1}{2}}}.}$$

I have heard from class that there are hundreds of proof of this theorem. But the proof that I have learned in class is a very elementary one. As we know that many theorems in number theory have some very nice explanations using abstract algebra. Is there a proof of this theorem from the perspective of abstract algebra? And what is the intuition behind it? Thank you!
Comment: I think it's a result too deep for it to be "intuitive." Of course, Gauss's intuition could say something about it but it is not just any intuition but the intuition of a genius.
Comment: Perhaps of interest is this excellent [youtube video](https://youtu.be/X63MWZIN3gM) containing an elementary proof (based on [this blog post](https://mattbaker.blog/2013/07/03/quadratic-reciprocity-and-zolotarevs-lemma/)) that gives more intuition than any other proof I've seen.
Comment: You may find of interest Wyman's *Monthly* exposition [What is a Reciprocity Law?](https://doi.org/10.1080/00029890.1972.11993090)
Comment: Gauss, who discovered it, gave 6 different proofs. For me, it's not intuitive; it's just a fact.
Comment: I think all theorems become more intuitive the more proofs of them you see.
Answer: It would help if you told us what proof or proofs you already know.
From the perspective of algebraic number theory, the quadratic reciprocity law can be described using
the cyclotomic field $\mathbf Q(\zeta_p)$ and its unique quadratic subfield, which is $\mathbf Q(\sqrt{p^*})$
for $p^* = (-1)^{(p-1)/2}p$, where $p$ is an odd prime.
Write the quadratic reciprocity law (for two different odd primes $p$ and $q$) as
$$
\left(\frac{q}{p}\right) = \left(\frac{p^*}{q}\right).
$$
The intuition behind this formula is that, using the field extension $\mathbf Q(\zeta_p) \supset \mathbf Q(\sqrt{p^*})$ mentioned above, the two sides of this equation describe in different ways the Frobenius element associated to $q$ in ${\rm Gal}(\mathbf Q(\sqrt{p^*})/\mathbf Q)$, which as a quotient ${\rm Gal}(\mathbf Q(\zeta_p)/\mathbf Q) \cong (\mathbf Z/(p))^\times$ is $(\mathbf Z/(p))^\times$ modulo its squares.  For further details about this approach you need to learn algebraic number theory; this proof can't be described at an intuitive level. That's part of what makes the quadratic reciprocity law so mysterious.
Comment: @reuns do you mean run through this proof with $p = 3, 5$ and arbitrary $q$?  Because $\mathbf Q(\zeta_3) = \mathbf Q(\sqrt{3^*}) = \mathbf Q(\sqrt{-3})$, I think that example is too simple.  There's also a quick elementary way to show  $(q|3) = (-3|q)$: $(-3|q) = 1$ for an odd prime $q$ if and only if $\mathbf Z/q\mathbf Z$ contains a cube root of unity (thinking of the formula $(-1+\sqrt{-3})/2$ in $\mathbf C$), and that's equivalent to $3\mid (q-1)$ since $(\mathbf Z/q\mathbf Z)^\times$ is cyclic.  So $(3^*|q) = 1$ if and only if $q \equiv 1 \bmod 3$, which is the same as $(q|3) = 1$.
Comment: It's possible to keep things down to earth by looking only at $p=3,5$, it isn't too hard to guess that it generalizes to every $p$ even if the detailed proof needs good knowledge of number fields
Answer: The proof that best fits the intuition represented by this formula is Eisenstein's one.
Briefly, Eisenstein uses Gauss' lemma and finds that $(\frac{p}{q})(\frac{q}{p})$ equals $-1$ or $+1$  depending on the parity (odd/even) of the number of lattice points in the square with as boundary lines the $x$-axis, the $y$-axis, and the lines $x=\frac{p}{2}$ and $y=\frac{q}{2}$.
And that number is clearly equal to $\frac{p-1}{2}\cdot\frac{q-1}{2}$


Colocar link para uma Window dentro de um TextBlock C# WPF

Question: Olá! Tenho um poup-up e gostaria que ao ser apresentado a usuário possa clicar nele e ir direto ao Window referente, como posso inserir esse link dentro de uma string? É Possível? Minha aplicação e para desktop e estou utilizando C# e WPF
Comment: SIm, é possível. Utilize Hyperlink
Answer: Adicione um HyperLink no text block no formulário XAML com algumas funções como:
NavigateUri
RequestNavigate
Hyperlink.InLines que seria o texto do textblock
<TextBlock>
        <Hyperlink
            NavigateUri="https://pt.stackoverflow.com/"
            RequestNavigate="Hyperlink_RequestNavigate">
            <Hyperlink.Inlines>
                <Run Text="Clique aqui"/>
            </Hyperlink.Inlines>
        </Hyperlink>
</TextBlock>

Agora no arquivo cs crie um método  onde acontece o processo de navegação para a URL definida.
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) => System.Diagnostics.Process.Start(e.Uri.ToString());

referencia: https://stackoverflow.com/questions/2092890/add-hyperlink-to-textblock-wpf