What tempo is andante con moto?

Question: I'm learning Beethoven's 5th symphony 2nd movement, and I have some questions.

What tempo is andante con moto?

How do you read the 32nd and 64th notes? For example, you count 16th notes with 1 e & a 2 e & a....

What's the difference between 3/4 and 3/8 time when using a metronome?
Comment: @Neil Meyer, I partially disagree--Con Moto is a character indication, but Andante is a tempo marking. Andante indicates that the piece is relatively slow (slower than the middle-speed Moderato) but faster than Adagio.
Comment: As I mention in my answer, Andante Con Moto is a character indication not a tempo marking.
Comment: @NeilMeyer - if andante is not a tempo mark, albeit vague, why is it on my metronomes?
Comment: So what about counting 32nd and 64th notes?
Comment: @NabeelRasheed see the answers to https://music.stackexchange.com/questions/9530/what-are-the-various-ways-of-vocalizing-rhythmic-figures
Comment: related: https://music.stackexchange.com/questions/10474/tempo-andante-allegro-vs-allegro-moderato https://music.stackexchange.com/questions/3294/what-tempo-is-agitato
Answer: Andante means at a walking pace, Con means with and Moto means movement. So it basically means... At a walking pace with movement.
So you would probably have a slight accent on the strong parts of beats and then no accent on the down beats as to accentuate the idea of movement. A slightly more loud upbeat followed by a slightly softer down-beat. It should just have a general effect of movement at a not brisk pace.
That would be my interpretation if I ever saw such a character indication for a guitar score, the piano players in the audience here may have a view more specific to the piano.
And take note Andante con moto is a character indication, not a tempo marking.
Answer: Andante con moto isn't an exact tempo in b.p.m. It's a vague (on purpose) idea of how a tempo can be arrived at. Listen to several recordings of that movement, and you'll realise they are not all at the same speed.
The metronome can be set to whatever you require. With 3/4, it can work so that each click represents one crotchet, or a beat. With 3/8, the same can be used, although the 8s - quavers - are usually shorter, but not necessarily half of what a crotchet is in a different piece.Check b.p.m. at the top of the piece.You could even set it so that each crotchet is represented by 2 clicks.
Answer: The core questions are:
1. At what tempo should the second movement of Beethoven's Fifth begin?
2. How should it be counted?

About Beethoven and tempo indications
At the time Beethoven composed the fifth symphony (1804–1808), the metronome had not yet been invented (1815).1,2 Although in 1817 he would go back and add metronome marking to his symphonies, at the time he composed the fifth, his attitude was that the metronome "is silly stuff; one must feel the tempos."3,4
This suggests that the tempo is genuinely up to the interpreter. In that case, it's worth asking a few experts what tempo they use.
What do various conductors do?

Iván Fischer begins the movement at around 80bpm.
Daniel Barenboim is closer to 76bpm.
Leonard Bernstein is almost exactly 76bpm.
Herbert Von Karajan zips right along about about 84bpm.
Wilhelm Furtwängler takes a more stately 66bpm.

So what's the right tempo?
Based on the composers above, it seems that the questions comes down to whether one prefers to emphasize the andante end of things, in which case the tempo will be on the slower end of things, or the con moto, in which case the tempo will be a bit quicker. Even the marked tempo of 92bpm is worthy of consideration. It certainly fits the con moto bill.
In any case, Beethoven clearly intends this movement to allow for some relative calm after the excitement of the first, so any tempo must allow for that sense of being carried along gently.
How to count?
Consider that the 1 e & a counting pattern need not be strictly for sixteenth notes. Think of it as a way to count the quarter division of a beat. Thus, in 3/8 time, the 1 e & a would be applied to the 32nd notes — those being the fourth division of the basic eighth-note beat.
The movement contains no 64th notes, so they are not a concern.
What's the difference between 3/8 and 3/16 time when using a metronome.
There is no difference. As it only keeps the pulse, the metronome is only concerned with the numerator in the time signature and the bpm. At that level, 3/4, 3/8, 3/16, 3/32, 3/anything are all identical. The denominator relates to which notation corresponds to the pulse, so while it can have interpretive significance, once the tempo is chosen, the metronome reflects only that.

Notes
1Wikipedia entry for Beethoven's Fifth Symphony.
2"A Brief History of the Mechanical Metronome", by Charlene Kluegel, August 12, 2021
3"Reflections on Beethoven's metronome markings", by Martin Pearlman, n.d.
4Ibid. Emphasis mine.

What tempo is andante con moto?


Calculation of angle between joined line segments

Question: I'm struggling with this. What is the best way to calculate the angles identified in the image, see link. Is there a general solution for all cases.
Example problem
Thanks once again
Comment: What information do you start with?
Comment: Thanks, I know the x,y of each point
Comment: In that case, I would just start creating right-triangles between each point with the next point, starting from the first point.  Then you can solve for the angles in those right-triangles which will let you do some simple geometry to get those other angles.
Comment: Thanks, I was wondering if there was a general solution to this. I am trying to code a solution in c++
Answer: As I understand your question, you are looking for a practical method.
Do you know that there exist a function ((which exist in Matlab but has an equivalent in many scientific packages) overcoming the difficulty of the "$\pi$ barrier" : it is $atan2$ (with two parameters)
Indeed, working with the formula $\cos \theta = \dfrac{xx'+yy'}{\sqrt{x^2+y^2} \sqrt{x'^2+y'^2}}$ is insufficient for dealing, as you need it, with angles in the $[0, 2 \pi)$ range. In fact, knowing $\cos \theta$, you cannot decide between $\theta$ and $2 \pi - \theta$. A remedy for the elimination of this ambiguity would be to compute as well $\sin \theta$.
But, in fact, $atan2(Y,X)$  ($Y$ first, $X$ second) does all the work !
For example $atan2(-1,-1)$ will give $5\pi/4$, $atan2(-\sqrt{3}/2,1/2)$ will give $5\pi/3$, etc.

Edit 1: Your problem will be easier to work on if you replace  exterior angles by interior angles. See figure below. Doing that, the "current  polygon", having the sum of its interior angles equal to $(k-1)\pi$ (think to this polygon as decomposed into $n-1$ triangles), considered as "closed" by $V_k=\sum_{i=1}^k V_i$, or more exactly by taking $-V_k$. In this way, you can follow the angles' modification by reference to this "invariant" $(k-1)\pi$.
Remark: the fact that the polygon is convex or not is unimportant (one deals with signed quantities, either signed angles, signed areas, etc.)

Edit 2: Here is a Matlab program that "solves" your problem, more or less in the spirit of Edit1 ; it uses complex numbers. I wish you can work with complex numbers in your environment ; otherwise, take real and imaginary parts when necessary...
Two keypoints : %(1) for the minus sign in order to reverse the next coming vector and %(2) for dealing with the good side (left hand side, when you imagine you follow the broken line).

<code>clear all;close all;hold on;
X=[0,2,5,6.8,10,8,8.8];
Y=[0,2,2,-2,5,-3,-4.2];
plot(X,Y);
Z=X+i*Y;
D=diff(Z);
for k=1:length(D)-1
    an=angle(-D(k+1)/D(k))*180/pi;%(1)
    if an<0
        a(k)=abs(an);
        else a(k)=360-an;%(2)
    end
    text(X(k+1),Y(k+1),[num2str(k),' ',num2str(a(k))]);hold on;
end;
a
</code>
Comment: yes I know about atan2
Comment: Please, have a look at the two "Edits" I have done to my first answer.
Comment: Thanks @JeanMarie, your effort is much appreciated
Answer: Hint:
If you have three points $A=(x_A,y_A)$,$B=(x_B,y_B)$ and $C=(x_C,y_C)$ find the vectors: $\vec a=(x_A-x_B,y_A-y_B)^T=(a_x,a_y)^T$ and $\vec b=(x_C-x_B,y_C-y_B)^T=(b_x,b_y)^T$ ( this is a translation of the origin at $B$).
Find the angles $\alpha$ and $\beta$ such that:
$$
\cos \alpha=\frac{a_x}{|\vec a|} \quad \land \quad \sin \alpha=\frac{a_y}{|\vec a|}
$$
$$
\cos \beta=\frac{b_x}{|\vec b|} \quad \land \quad \sin \beta=\frac{b_y}{|\vec b|}
$$
these angles are uniquely determined and $0\le \alpha <360°$,$0\le \beta <360°$ and, if I well interpret your picture we have always $\alpha \le \beta$.
Now, using the knowledge of the signs os the components of $\vec a$ and $\vec b$, you can separate the cases when the searched angle is $\theta= \alpha-\beta$ or $\theta'=360°-\theta$.
(Eventually you can solve analogously  also the case $\alpha \ge \beta$).
Comment: Thanks but this does not give a solution to the outer angles of the connected polylines, which is the problem I'm trying to solve
Comment: I see! And I've changed my answer. I hope that it works now :)
Comment: Thanks @Emiliio, I'll have to get out my maths books :)


Dúvida com layout Responsivo bootstrap

Question: Tenho um layout que gostaria de deixar no seguinte modelo.

Para deixar ele responsivo não estou conseguindo adicionar a coluna (1) maior.
Como está agora
http://comajudacoletiva.com.br/estudo/

Answer: Olá, irei te ajudar a entender um pouco mais deste sistema.
Para conseguir esta divisão você terá que dividir duas vezes.
Percebi que o bloco inicial ficaria são quatro, correto?
Sendo 1/4, 1/4, 1/4, e 1/4.
A maneira mais correta é:
1º - Dividir a largura total em 4, e a segunda com o resto.
2º - Dividir a segunda coluna em três para colocar os quadrados menores.
Exemplo abaixo:

 Conteúdo

 Conteúdo

 Conteúdo

 Conteúdo

 Conteúdo

 Conteúdo

 Conteúdo

 Conteúdo

 Conteúdo

Dúvida com layout Responsivo bootstrap


Inequalities involving summation

Question: I have been struggling with the following math problem for quite a while without any real progress:
Let $\ n \in \mathbb N$
Show  that $$\frac{127}{7}(n-1)^7 \le \sum_{n=k}^{2n-1}  k^6 \le \frac{127}{7}n^7.$$
I would like to know how to approach the problem above and also how to approach these kinds of problems in general since I barely have any previous experience with them. Thanks a lot in advance!
Comment: Induction might work ? or area under a graph approximated by rectangles
Answer: The function $y=x^6$ is increasing, so by considering the area under the curve
\begin{eqnarray*}
\int_{n-1}^{2(n-1)} k^6 dk \leq \sum_{k=n}^{2n-1}  k^6 \leq \int_{n}^{2n} k^6 dk.
\end{eqnarray*}
Comment: @MartinR That's right ... I wish I had said that. I will edit.
Comment: Unless I am mistaken, it suffices to note that $y= x^6$ is *increasing,* the convexity is not needed.
Answer: The right inequality you can prove by induction, for which prove that:
$$\frac{127n^7}{7}+(n+1)^6\leq\frac{127(n+1)^7}{7}$$ and

Inequalities involving summation


Abertura do dialog() não funcionando

Question: Bem, de certa forma fiz algumas alterações em meu código, ou seja ao invés de se usar uma table eu estou usando uma hierarquia de lista em HTML li.
O codigo no fiddle está exatamente igual o meu codigo dentro do sistema (com a diferença que os li são gerados dinamicamente).
Mas de forma alguma meu $('#dialog').dialog() abre quando vou testar dentro dentro do sistema. Isso é estranho, pois no fiddle ele funciona normalmente.
No console ele me dispara a seguinte pilha:
Uncaught TypeError: undefined is not a function  service:1084
 (anonymous function)   jquery.js:4618
 jQuery.event.dispatch   jquery.js:4302
 elemData.handle

Já tentei alterar o lugar da div que contem o id="dialog", mas nao obtive sucesso.
Comment: João o HTML do jsFiddle é o mesmo que do código original? Dá uma olhada aqui: http://jsfiddle.net/a66fx2L5/
Comment: João esse HTML é bem diferente da pergunta... acho que valia a pena mudar a pergunta. De qq maneira nesse novo HTML falta-lhe a div #dialog. Dê uma olhada aqui: http://jsfiddle.net/a66fx2L5/5/ - se fôr isso que quer posso colocar uma resposta a explicar melhor o que faltava.
Comment: Pois, no jsFiddle eu adicionei o jQueryUI, `.js` e `.css`, é isso que fez funcionar o dialog. Vou ver se encontro o modal do Boostrap e coloco aqui se encontrar...
Comment: Pois estou a preparar uma resposta mas já não acabo hoje. Coloco amanhã. Ou faz com jQuery UI ou com Bootstrap que tem limitações mas tem a vantagem de não precisar de mais ficheiros a serem carregados...
Comment: Oi Sergio, na verdade é quase isso. Mas no meu é uma lista. Criei alterei o arquivo para ficar semelhante como estou usando no projeto. Cada item da lista tem um ID gerado automaticamente, quero apenas que quando o usuário clique em "Remover" uma chamada AJAX seja feita e com o sucesso da mesma a linha seja retirada. Será que é possivel fazer com a lista? Aqui está o link: http://jsfiddle.net/joaoManolo/a66fx2L5/1/
Comment: @Sergio, concordo com você. Bem, a parte de "sumir" o componente funciona normalmente, assim como a abertura do `dialog()`, mas quando eu passo para meu sistema o mesmo não funciona, ou seja, o dialog não abre e dispara um erro no console. Editei a pergunta com a pilha de erros para facilitar a visualização.
Comment: Então @Sergio, eu uso o jQuery. Achei o dialog do BootStrap (`BootstrapDialog.show({});`), mas o mesmo não funciona. Ele acusa `BootstrapDialog is not defined`.
Comment: Agradeço a atenção @Sergio. Vou aguardar sua resposta, mas em paralelo a isso vou tentar resolver também.
Answer: O problema e alguma confusão sua (e minha, pois tive de estar a estudar o jQuery UI e o Bootstrap para responder) é que ambos o Bootstrap e o jQuery UI têm dialogs/modals. Assim no seu código estava carregar o Bootstrap mas a usar código JavaScript/jQuery para um dialog do jQueryUI.
A minha resposta assume que continua a usar o Bootstrap, e remove parte do código que tinha que era para o jQuery UI.
Assim precisa alterar:
#1 - junte o HTML do modal/dialog algures na página, por exemplo:

        <button type="button" class="close" data-dismiss="modal">×Close</button>

Modal title

        Tem a certeza?

        <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
        <button type="button" class="btn btn-primary">Apagar</button>

#2 - mude o HTML dos botões para ter atributos Bootstrap:
data-toggle="modal" data-target="#myModal"

#3 - mude o JavaScript para usar a maneira da biblioteca do Bootstrap
$('#myModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget) // botão que abriu o modal
    var aRemover = button.closest('tr');
    $('#confirmar').on('click', function () {
        $('#myModal').modal('hide')
        aRemover.fadeOut(500, function () {
            aRemover.remove();
        });
        // aqui pode chamar o seu AJAX
    });
});

$('#myModal').on('hide.bs.modal', function (event) {
    $('#confirmar').off('click');
});

Note que neste caso/exemplo usei o HTML sugerido na documentação do Bootstrap, e dei uma ID ao botão de apagar para ser mais cómodo. O HTML que acrescentei é:

                <button type="button" class="close" data-dismiss="modal">×Close

                </button>

Modal title

Tem a certeza?

                <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                <button type="button" id="confirmar" class="btn btn-primary">Confirmar</button>

P.S: Vi agora que editou a pergunta para usar listas em vez de tabela. Aí precisa mudar:
var aRemover = button.closest('tr');

para
var aRemover = button.closest('li');

Comment: Olá @Sergio. Peço desculpas pela demora, mas acabei viajando e acabou não dando tempo em responder. Funcionou perfeitamente. Obrigado mais uma vez pela ajuda. Creio que a confusão estava mesmo em definir qual dialog/modal usar, jQuery ou Bootstrap.
Answer: Usando seu jsfiddle de base eu fiz algumas modificações. Acredito que eu tenha entendido corretamente o que você quer.
Eu coloquei o remove() fora do successdo AJAX para você ver funcionando, depois é so colocar la dentro de volta.
Link jsfiddle
Comment: Oi Daniel é quase isso mesmo, mas queria realizar o mesmo com uma lista. no comentario da minha pergunta coloquei um finddle que ilustra exatamente o que eu estava querendo fazer, mas caso não funcione eu vou adaptar meu codigo para funcionar com a tabela. Obrigado pela atenção

Abertura do dialog() não funcionando


Absolute Convergence of a series in Browder

Question: I'm quite stuck on an exercise in Browder's Mathematical Analysis and could use a push in the right direction. The question reads:
Show that if $(a_n)$ is a sequence in $\mathbb{R}$, and $a_nr^n \rightarrow 0$ for some $r \neq 0$, then $\sum_{n=0}^{\infty}{\frac{a_nx^n}{n!}}$ converges absolutely for every $x \in \mathbb{R}$.
Intuitively, I can see that the $a_n$ need not tend to zero or to converge at all (as the r might be quite small), and surely we may make the value for x as large as we like, so the convergence of the series given seems to rest solely on the fact that n! grows quite quickly.
Now, the series looks like it would lend itself well to a proof using the ratio test, but what I end up with upon computing the appropriate ratio is $$\limsup\lvert\frac{a_{n+1}}{a_n}\rvert\cdot\frac{|x|}{n+1}$$
and I'm not sure how to proceed with the knowledge I have about $a_nr^n$. Am I moving in the right direction here?
Thanks!
Answer: Let $x\in \Bbb R$. Since $a_n r^n \to 0$, there exists a positive integer $N$ such that $|a_n r^n| < 1$ for all $n \ge N$. Thus $$\left|\frac{a_n x^n}{n!}\right| = |a_n r^n| \frac{|x/r|^n}{n!} < \frac{|x/r|^n}{n!} \quad \text{for all} \quad n\ge N.$$
Since $\sum_{n = 0}^\infty \frac{|x/r|^n}{n!}$ converges, by direct comparison the series $\sum_{n = 0}^\infty \frac{a_nx^n}{n!}$ converges absolutely. Since $x$ was arbitrary, $\sum_{n = 0}^\infty \frac{a_nx^n}{n!}$ converges absolutely for every $x\in \Bbb R$.
Comment: V. slick. Also this explains why $r \neq 0$, which was bugging me. Thanks for your help!


Confusion regarding ($d = rt$) vs ($x_1 = x_0 + v_o t + 0.5 at^2$) usage.

Question: I'm following an online physics course and I can't understand why for the question below the equation distance = speed $\times$ time can't be used while the equation $x_1 = x_0 + v_0t + 1/2at^2$ can. Could somebody please clarify why this is the case?
"A plane is moving at $30 \ m/s$. It accelerates at $2 \ m/s^2$ for $11$ seconds. How far does it travel during this time?"
Here's how I solved it which is wrong according to my book which uses the other equation.

I started by calculating the final velocity using $v_1 = v_0 + at$ which is $52 \ m/s$.
Using the final velocity I calculated the average velocity using $(v_1 - v_0) / 2$ resulting in $ 11 \ m/s$.
Inserting it into the equation $d = rt$ ($d = 11 \ m/s \times  11 \ s$) the answer is $121 \ m$.
Comment: How does it make sense that the _average velocity_ is less than the _initial velocity_ which undergoes _positive acceleration_?
Comment: On the other hand, the average _change_ of velocity, the $11\text{ m}\cdot\text{s}^{-1}$ that you computed, added to the initial velocity, yields an average velocity of $41\text{ m}\cdot\text{s}^{-1}$. And over a period of $11\text{ s}$, this is precisely $451\text{ m}$.
Answer: This is because you have to distinguish two different cases: (1) when you move at constant speed ($s=v t$) in a straight direction and when you have acceleration ($x_1=x_0+V_0 t+\frac{1}{2} a t^2$), i.e. a change of speed versus time.
Answer: The plane accelerates at $\ddot{x}=2\ \text{m}\cdot\text{s}^{-2}$ for $11\text{ s}$. Therefore, its velocity is given by:
$$\dot{x}=\int_0^{11}\ddot{x}\ dt=\int_0^{11}2\ dt=2t+C_1$$
The integration constant $C_1$ is obtained by comparison with the boundary condition:
$$\dot{x}(t=0)=v_0=30\ \text{m}\cdot\text{s}^{-1}=C_1$$
The velocity is then:
$$\dot{x}=2t+30$$
The distance traveled in $11\text{ s}$ is, once again, obtained by integration:
$$x=\int_0^{11}\dot{x}\ dt=\int_0^{11}(2t+30)\ dt=t^2+30t+C_2$$
And once again, we compare this result with the boundary condition for the position $x(t)$ to obtain the value of $C_2$:
$$x(t=0)=x_0=C_2$$
We don't need to know the initial position of the plane, since we're only interested in the change of position:
$$\Delta x=x(t=11)-x(t=0)=(11^2+30\times 11+x_0)-x_0=151$$
The distance traveled by the plane in $11\text{ s}$ is $\Delta x=451\text{ m}$.
Comment: I appreciate the effort but a lot of that went over my head given my current level of physics/calculus.
Comment: No problem. This is just how all the relations you've learnt ($x(t)=x_0+vt+\frac{1}{2}at^2$) are derived. Once you know this technique, you don't have to remember all these silly formulas.


JQuery rotate - re-initiate rotation in chrome

Question: I have a circular image that rotates on page load and stops and starts on mouseover/out.   The circle is also draggable so that I can manually spin it.  This all works fine in Mozilla, but doesn't work so well in Chrome.  The problem is that it doesn't re-initiate the rotateCircle(); on mouseout.  can anyone help find out why this is?  I am using jQueryRotate and Greensock Draggable for this.

$(function() {

    var angle = 0;
    var int;
    rotateCircle();

    function rotateCircle() {
        int = setInterval(function() {
            angle += 3;
            $("#circle").rotate(angle);
        }, 100);
    }

    $("#circle").mouseover(function() {
        clearInterval(int);
        Draggable.create("#circle", {type:"rotation",throwProps:true});
    }).mouseout(function() {
       rotateCircle();
    });

});

</script>

Comment: its mostly because you are using 2 libraries for rotating the same element so in chrome GreenSock uses the css3 transform property and jQuery rotate uses -webkit-transform property
Comment: here's how i did it using jquery transit, vector math & livescript http://codepen.io/furqanZafar/pen/myeXPo
Comment: Ah ok.  Any ideas on a solution?  I need the two libraries as they both do different things. thanks
Comment: That works great, but looks quite advanced for me.  I can't really use it if I don't understand it, would prefer to find a solution to get the above working together if possible.  Thanks anyway.
Answer: A simpler way is to add a rotateBy method to the GreenSock Draggable class.
Here is the updated Draggable class:
https://raw.githubusercontent.com/furqanZafar/GreenSock-JS/master/src/uncompressed/utils/Draggable.js
I only added the following method to Draggable.js:
this.rotateBy = function(amount) {
    self.rotation += amount;
    self.x = self.rotation;
    dirty = true;
    render();
}

Here is the jsfiddle that works on both chrome & ff using the new Draggable class: http://jsfiddle.net/58rauhsL/
$(function() {

    var draggable = Draggable.create("#circle", {type:"rotation",throwProps:true}),
        interval;

    function rotateCircle() {
        interval = setInterval(function() {
            draggable[0].rotateBy(3);
        }, 100);
    }

    rotateCircle();

    $("#circle").mouseover(function() {
        clearInterval(interval);
    }).mouseout(function() {
        rotateCircle();
    });

});

Answer: I don't quite understand why Javascript is required for this?
http://jsfiddle.net/nmmkLpqo/ (example only for chrome, add vendor-prefixes for FX etc.)
img {
    border-radius: 50%;
    -webkit-animation: rotation 5s linear infinite;
}
img:hover {
    -webkit-animation-play-state: paused;
}
@-webkit-keyframes rotation {
  from {
      -webkit-transform: rotate(0deg);
  }

  to {
      -webkit-transform: rotate(360deg);
  }
}

This should do exactly the same?
Comment: I would have used that if I hadn't used the draggable plugin, thanks


Semi-stable locally free sheaves on a curve of constant slope form an abelian category

Question:
I have some difficulty understanding the above proof.
Here $C(\mu)$ denotes the category of semi-stable vector bundles (locally free sheaf) of slope $\mu$. Here the sheaves are considered over a smooth connected algebraic curve $X$.
A locally free sheaf $F$ is called semi-stable if for every subsheaf $G$, the slope of $G$, $\mu(G)$, is less than equal to slope of $F$, $\mu(F)$. The slope of a locally free sheaf is defined as $deg(F)/rank(F)$.
I've two questions about the above proof

It says that the $ker(f)$ and $coker(f)$ are locally-free sheaves. Well, the $ker(f)$ is a subsheaf of $E$, which is a locally-free sheaf, so $ker(f)$ is also a locally free sheaf ( because these are sheaves on a smooth curve and therefore stalks are pid, and a submodule of a free module over a pid is again a free module). But I've absolutely no idea how it says $coker(f)$ is also a locally-free sheaf. Why is this true?
In the proof of $ker(f)$ is semistable, it says if it's not semistable it would have a sub-bundle of slope of slope greater than $\mu$. So, somehow there are assuming slope of $ker(f)$ is also $\mu$. So, I guess since slope of $E$ and $F$ is $\mu$ and they are semistable then it is forcing the slope of both $ker(f)$ and $coker(f)$ to be $\mu$. Is this correct?
Answer: 1) If $Coker(f)$ is not locally free, it has a summand $T$ which is a torsion sheaf. The kernel $G$ of the composition $F \to Coker(f) \to T$ is a locally free sheaf, whose slope is less than $\mu$. The image of $f$ is contained in $G$, so, we obtain a morphism $E \to G$ from a semistable sheaf to a sheaf of smaller slope, which is impossible.
2) Consider the image $G = Im(f)$. We have an epimorphism $E \to G$, hence all quotients of $G$ have slope greater or equal than $\mu$. On the other hand, we have a monomorphism $G \to F$, hence all subsheaves in $G$ have slope less or equal than $\mu$. It follows that in the Harder-Narasimhan filtration of $G$ all factors have slope $\mu$, hence $G$ is semistable of slope $\mu$. Therefore $Ker(f) = Ker(E \to G)$ and $Coker(f) = Coker(G \to F)$ also have slope $\mu$.
Comment: @grok: A torsion sheaf on a curve is an iterated extension of structure sheaves of points. Its length is the number of factors in such iterated extension.
Comment: Thank you very much for the answer! I don't understand why the slope of $G$ should be less than $\mu$. Why can't it be equal to $\mu$?
Comment: @grok: Because its rank equals the rank of $F$, and its degree is equal to the degree of $F$ minus the length of $T$, i.e., less than the degree of $F$.
Comment: Thanks for the reply! What exactly do you mean by the term length of $T$?


Extract links from a web page

Question: Using Java, how can I extract all the links from a given web page?
Comment: Are you looking for anchor tags, quoted URLs, or any URL even if it occurs in plain text?
Answer: download java file as plain text/html pass it through Jsoup or html cleaner both are similar and can be used to parse even malformed html 4.0 syntax and then you can use the popular HTML DOM parsing methods like getElementsByName("a") or in jsoup its even cool you can simply use
File input = new File("/tmp/input.html");
 Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");

Elements links = doc.select("a[href]"); // a with href
Elements pngs = doc.select("img[src$=.png]");
// img with src ending .png

Element masthead = doc.select("div.masthead").first();

and find all links and then get the detials using
String linkhref=links.attr("href");

Taken from http://jsoup.org/cookbook/extracting-data/selector-syntax
The selectors have same syntax as jQuery if you know jQuery function chaining then you will certainly love it.
EDIT: In case you want more tutorials, you can try out this one made by mkyong.
http://www.mkyong.com/java/jsoup-html-parser-hello-world-examples/
Answer: Either use a Regular Expression and the appropriate classes or use a HTML parser. Which one you want to use depends on whether you want to be able to handle the whole web or just a few specific pages of which you know the layout and which you can test against.
A simple regex which would match 99% of pages could be this:
// The HTML page as a String
String HTMLPage;
Pattern linkPattern = Pattern.compile("(]+>.+?<\/a>)",  Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
Matcher pageMatcher = linkPattern.matcher(HTMLPage);
ArrayList<String> links = new ArrayList<String>();
while(pageMatcher.find()){
    links.add(pageMatcher.group());
}
// links ArrayList now contains all links in the page as a HTML tag
// i.e. Text inside tag

You can edit it to match more, be more standard compliant etc. but you would want a real parser in that case.
If you are only interested in the href="" and text in between you can also use this regex:
Pattern linkPattern = Pattern.compile("]+href=[\"']?([\"'>]+)[\"']?[^>]*>(.+?)<\/a>",  Pattern.CASE_INSENSITIVE|Pattern.DOTALL);

And access the link part with .group(1) and the text part with .group(2)
Comment: I think you ment '...href=[\"']?([^\"']+)...'. But then again..what if href="blablalba/Mc'Chicken". Won't the string get cut off the moment it hits the single quote?
Comment: what if url not contain <a href  tag then I think it won't trace the url.
Answer: You can use the HTML Parser library to achieve this:
public static List<String> getLinksOnPage(final String url) {
    final Parser htmlParser = new Parser(url);
    final List<String> result = new LinkedList<String>();

    try {
        final NodeList tagNodeList = htmlParser.extractAllNodesThatMatch(new NodeClassFilter(LinkTag.class));
        for (int j = 0; j < tagNodeList.size(); j++) {
            final LinkTag loopLink = (LinkTag) tagNodeList.elementAt(j);
            final String loopLinkStr = loopLink.getLink();
            result.add(loopLinkStr);
        }
    } catch (ParserException e) {
        e.printStackTrace(); // TODO handle error
    }

    return result;
}

Comment: This is really good. You can get the parser here: http://htmlparser.sourceforge.net
Comment: @shams: if the URL have an special char like (www.google-gmail.com) got an exception "org.htmlparser.util.EncodingChangeException: character mismatch (new: ? [0xfeff] != old:  [0xefï]) for encoding change from ISO-8859-1 to UTF-8 at character offset 0" how can solve this
Answer: This simple example seems to work, using a regex from here
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public ArrayList<String> extractUrlsFromString(String content)
{
    ArrayList<String> result = new ArrayList<String>();

    String regex = "(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(content);
    while (m.find())
    {
        result.add(m.group());
    }

    return result;
}

and if you need it, this seems to work to get the HTML of an url as well, returning null if it can't be grabbed. It works fine with https urls as well.
import org.apache.commons.io.IOUtils;

public String getUrlContentsAsString(String urlAsString)
{
    try
    {
        URL url = new URL(urlAsString);
        String result = IOUtils.toString(url);
        return result;
    }
    catch (Exception e)
    {
        return null;
    }
}

Comment: Upvote for **not** omitting the import statements: makes the difference for those new to regex in Java
Comment: Is there a way to restrict this to all links within a table with specified id value?
Comment: @santafebound - This couldn't really do that - you'd need to [use something like jsoup](https://jsoup.org/cookbook/extracting-data/selector-syntax) to do that i think.
Answer: import java.io.*;
import java.net.*;

public class NameOfProgram {
    public static void main(String[] args) {
        URL url;
        InputStream is = null;
        BufferedReader br;
        String line;

        try {
            url = new URL("http://www.stackoverflow.com");
            is = url.openStream();  // throws an IOException
            br = new BufferedReader(new InputStreamReader(is));

            while ((line = br.readLine()) != null) {
                if(line.contains("href="))
                    System.out.println(line.trim());
            }
        } catch (MalformedURLException mue) {
             mue.printStackTrace();
        } catch (IOException ioe) {
             ioe.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException ioe) {
                //exception
            }
        }
    }
}

Comment: Adding imports needed:(If using terminal and not knowing the imports)
import java.io.*;
import java.net.*;
Answer: You would probably need to use regular expressions on the HTML link tags  and
Comment: Anyone thinking of going down this path should read this post: http://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not

Extract links from a web page


Slice Assignment with a String in a List

Question: I did quite a bit of perusing, but I don't have a definite answer for the concept that I'm trying to understand.
In Python, if I take a list, such as:
L1=['muffins', 'brownies','cookies']

And then attempted to replace the first pointer to an object in the list, namely 'muffins' by using the code:
L1[0:1] = 'cake'

I would get a list L1:
['c', 'a', 'k', 'e', 'brownies', 'cookies']

Yet if I took the same list and performed the operation (now with the 4 elements from the string cake):
L1[0:4] = ['cake'] # presumably, it's now passing the string cake within a list? (it passed into the modified list shown above)

I get the output I initially desired:
['cake', 'brownies', 'cookies']

Can anyone explain why that is, exactly?
I'm assuming that when I take cake initially without it being in a "list", it breaks the string into its individual characters to be stored as references to those characters as opposed to a single reference to a string...
But I'm not entirely sure.
Comment: Your last example `L1[0:4] = ['cake']` yields `['cake']` for me, not `['cake', 'brownies', 'cookies']` on python 2.6. -- Also note that since you already have 5 upvotes, apparently you asked a pretty good question :)
Comment: Ah, the last example was with respect to the code that had already been modified - as in, instead of using: 'L1=['muffins', 'brownies','cookies']', I was performing the last example with 'L1 = ['c', 'a', 'k', 'e', 'brownies', 'cookies']'.
Answer: Two important points:

Slice assignment takes an iterable on the right-hand side, and replaces the elements of the slice with the objects produced by the iterable.
In Python, strings are iterable: iterating over a string yields its characters.

Thus
L1[0:1] = 'cake'

replaces the first element of L1 with the individual characters of 'cake'.
To replace the first element with the string 'cake', simply write:
L1[0] = 'cake'

or, using the slice assignment syntax:
L1[0:1] = ['cake']

Answer: If you specify a slice, the righthand side is presumed to be a list/tuple (actually, any iterable - but watch out for generators that produce an indefinite number of values).
To replace an item in a list, use:
my_list[0] = "cake"

(You could also do
my_list[0:1] = ["cake"]

if you really want to use a list slice.
See also:
slice assignment
Comment: @Levon - thanks for saying something nice! I really like your profile BTW - can I copy / restate it for mine? I'm pretty sick of the yah-yah attitude I see in the answers. I try to answer with just enough info to help the person, targeted at what I perceive is their level (and interest).
Comment: Sure, go ahead, glad I'm not the only one who notices the attitude of some members.  And I totally agree, I try to tailor responses to the OP's level too .. no point showing off Python prowess if the question is very basic. Better to help with a solid basic answer and save the fancy stuff for more advanced questions :) .. having said that, this was a good question and got an upvote from me too.
Comment: the relevant refs points to same ref https://stackoverflow.com/questions/10623302/how-does-assignment-work-with-list-slices which one is the missing ??
Answer: Think of strings as being a sequence container that stores characters. When you try to do assignments that way, it adds each item in the character sequence to the list. By wrapping "cake" in its own 1-element list first (let's call it L2), you're instead adding each element of L2 to L1 -- it does not recursively split up sequence containers beyond the outermost sequence.
L1 = ['muffins', 'brownies','cookies']
L2 = ['cake']
L1[0:1] = L2
print L1
['cake', 'brownies', 'cookies']

This is also true for other nested sequence objects. Try experimenting with more nested sequence objects like this:
L3 = [['pie', 'eclairs'], ['bacon', 'chocolate']]
L1[0:1] = L3
print L1
[['pie', 'eclairs'], ['bacon', 'chocolate'], 'brownies', 'cookies']

It's also worth noting that if you don't care about order/positioning in the list, you can use append() and not have to worry about your string getting split up:
L1 = ['muffins', 'brownies','cookies']
L1.append('cake')
print L1
['muffins', 'brownies', 'cookies', 'cake']


html2canvas Imagem na div

Question: Tenho a seguinte div

        <input type="text" ng-model="yourName" placeholder="Seu nome">

         Get Screenshot

{{yourName}}

A função genScreenshoot()
    function genScreenshot() {
    html2canvas($('#cont_img'), {
        allowTaint: true,
        letterRendering: 1,
        onrendered: function (canvas) {
            if (navigator.userAgent.indexOf("MSIE ") > 0 ||
                          navigator.userAgent.match(/Trident.*rv\:11\./)) {
                var blob = canvas.msToBlob();
                window.navigator.msSaveBlob(blob, 'Test file.png');
            }
            else {
                $('#test').attr('href', canvas.toDataURL("image/png"));
                $('#test').attr('download', 'Test file.png');
                $('#test')[0].click();
            }

        }
    });
}

Mas essa função só está salvando o texto, as imagens dentro dessa mesma div não estão sendo renderizadas. Lembrando que o src delas são setados quando o usuário escolhe uma imagem. E essa função de screenshot só é chamada quando usuário clica no botão, então as imagens estão lá.
Answer: Não sei se este código te ajuda um pouco ele captura a imagem eu só não coloquei a função de download.
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Html2 Canvas</title>

        <link rel="stylesheet" type="text/css" href="http://www.tecnologicbrasil.com.br/leaflet/leaflet.css">

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

        <button onclick="prints();" data-toggle="modal" data-target="#exampleModal" >Click para dar print</button>

Tecnologic Brasil- Inovando a cada Dia

html2canvas Imagem na div


Installing Windows 2003 over remote DRAC 4

Question: I'm trying to install windows 2003 over a DRAC 4 console session by using a ISO file.
But it keeps freezing during the GUI installation then when login back Windows Setup says some files not found and setup won't continue.
What's the best approach to install Windows 2003 over a DRAC 4 console session?
Answer: are you installing over LAN or WAN? in wAN environments, because of the slow link, you might experience problems.
also, since it's a dell server, use the SMTD/SBUU ISO to ready the server for windows installation instead of booting with a windows ISO directly
Comment: It's over the internet. I don't have physical access, I'm not sure what is a "SMTD/SBUU ISO" ?
Comment: I've just found out Dell OpenManage and looking into it
Comment: I've seen corrupt installations many times, when done over the internet like this. DRACs and other avocent clones are designed to be used over a LAN link not over internet
Answer: I wrote a blog post a few years ago about this, and although it refers to DRAC5, it should help you.


Ctrl-Alt-Del doens't work in logon on VirtualBox Windows 2003 server guest by RDP

Question: When i try to access a VirtualBox Windows 2003 server guest hosted in a Google Compute Engine Debian Wheezly by any RDP, the logon screen appears and when i press Ctrl-Alt-Del task manager came up.
Answer: Menu : Machine > Inser Ctrl Alt Delete . That is it!
Answer: Press Right-Ctrl+Delete. It has to be the Right-Crtl, the Left-Ctrl does not work.
Comment: on windows keyboard its Right-Ctrl + Entf
Answer: Well i found a realy nice solution. If you quickly press 5 times left shift StickyKeys will appear, then press OK and StickyKey will activate. Then you press the Ctrl Alt Del sequencially, not at the same time.
Answer: On the newest versions of Virtual Box the option given by Abdennour TOUMI have been moved to the Input menu: Input->Keyboard->Insert Ctrl+Alt+Del which shortcut is Host+Del
Answer: Its the same way you would delete a file in OSX, simply: cmd+backspace
This is the same as ctrl+alt+delete or whatever required on the log in screen on Win Server 2012 in Virtualbox on a OSX host.
Answer: in sign-in page of win server you should
first click on ' Ease of access ' icon and choose ' On-Screen Keyboard '
then click ctrl+alt+del on the keyboard that have been appeared
Answer: I found, Host+del and then your host key might be CTrl+(left or right arrow key)+del.
I am using Windows server 2012 in Virtual box
Answer: to do it press cntrl+Shift+Delete (right side of the keyboard)


Asymmetric stream cipher with short plaintext => short ciphertext

Question: I am looking for an asymmetric cipher which has the property that very short inputs result in very short outputs.
.NET's standard RSACryptoService seems to output a minimum of 128 bytes for any short plaintext, including the empty plaintext. Minimum supported BlockSize is 128 and the only supported Mode is CBC.
The perfect algorithm would not expand the plaintext at all, while providing the asymmetric property. Expected input size is 50-100 bytes, certainly never more than 150.
Answer: It is certainly possible to achieve your goals for the sizes you are interested in by using elliptic curve ElGamal encryption and variants. The Bouncycastle C# library is one option for implementation.
So for example by using the NIST P-256 curve you can encrypt 32 bytes of data and get a 64 byte result. If you use proper padding you can encrypt less data. I believe PGP once considered implementing this but I don't know if they ever did.
Answer: Asymmetric ciphers need long keys because there are many very powerful techniques for narrowing the key-space and the input-space.  If, by seeing that you've sent a short encrypted message, I know that the plaintext is also short, then that further narrows the input-space.
So if such a cipher exists, then it would by definition be unsafe to send short messages.
Comment: An attacker can use special techniques to narrow the space of possible short inputs.  This is why RSA mandates that you use random padding to fill out your message so it's approximately as large as the key.  Keep in mind that it's possible to crack a public-key encrypted message by searching either the key-space or the input-space.  For instance, if you ask me a yes or no question and I encrypt the answer with your public key and send it to you, Eve can simply encrypt the words 'yes' and 'no' with your public key and then see which one matches.  She doesn't need to search the keyspace.
Comment: I don't mind if the key is very long. I don't mind if you know the plaintext is short; there's still a heck of a lot of keys to try (provided that the algorithm managed to use the whole key to encrypt the short message, rather than just the first short part of the key). (I guess I have by now revealed how much of a crypto noob I am...)
Answer: Asymmetric ciphers are extraordinarily slow. So slow as to be unusable, in practice, on anything but the smallest inputs. Symmetric ciphers, however, can be very fast.
The technique for using an asymmetric cipher is as follows:

using a cryptographically strong random number generator, create a secret key S
encrypt the data using a symmetric algorithm (e.g., AES-256-CBC) and key S
encrypt key S using an asymmetric algorithm (e.g., RSA) and key A of the key-pair
prepend the encrypted form of key S to the encrypted message

In other words, the message is encrypted with a random key using a symmetric algorithm, and then the random key is encrypted with one of the keys using an asymmetric algorithm.
You also have to take into account the IV and padding for the CBC mode, and you have to take into account the padding for the RSA. It adds up. Perfect algorithms require IV's and padding. Given that you have one IV, two paddings, and the random symmetric key (encrypted) to store along with the message (encrypted), the crypto stuff will have to take up space.
Comment: Hmm, my inputs are always going to be tiny, so speed is not an issue. That leaves just one padding, right? (assuming I correctly understood that the IV was for the symmetric bit)
Answer: I don't think you can get a ciphertext noticeably smaller than the size of the key, and your keys for asymmetric crypto algorithms should probably be in the hundreds to thousands of bits. Can you not combine multiple things together and encrypt a bigger chunk?
Comment: I am surprised to hear this - is this a general property of asymmetric algorithms? It does not seem to be true of symmetric block ciphers, which can use Ciphertext Stealing for creating ciphertexts much shorter than the key.
Comment: Well RSA requires exponentiating mod n, where n is a 1000bit+ number, so you'll be stuck there. I'm confused by your reference to ciphertext stealing. That only applies if your input is bigger than a full block.
Comment: I didn't realise that about CTS... /blush
Comment: If you want that, use (instead of CTS) the blockcipher in a stream cipher mode, like CFB or CTR mode. Then size input = size output (in bytes)
Comment: @Henno Brandsma: But how do you use an asymmetric algorithm in CFB or CTR?


ssh works fine when using public interface, but slow when using private interface

Question: My Linux(UbuntuEEE) to Linux(CentOS) ssh takes a long time to log in(~15 seconds) when using the private interface, but not when using the public one.
I have a Linux box acting as my router. As such, it has multiple interfaces(75.xxx.xxx.xxx, 192.168.1.1). I can ssh in from the internal interface(192.168.1.65 to .1), but it will take a while. I can ssh into the public address, and it goes quickly(~1 second).
I have another box that I can ssh into the inside interface from and it goes quickly.
iptables is set to accept packets coming into the interface immediately. sshd's UseDNS is normally on; I get the same problem if I turn it off and restart sshd. I normally use public-key authentication; I have done a mv ~/.ssh/ ~/ssh/ and it will ask me for a password after going slowly.
After logging in(using either interface), speed is quick.
ssh client version(via ssh -v):OpenSSH_4.7p1 Debian-8ubuntu1.2, OpenSSL 0.9.8g 19 Oct 2007
ssh server version(via rpm -qv openssh_server):openssh-server-4.3p2-29.el5
Answer: UseDNS no

Set that in your /etc/ssh/sshd_config and restart the daemon, that should do the trick.
Answer: This kind of problem is always caused by DNS. When you log into the 192.168.1.1 interface, sshd attempts to do a lookup of whatever IP address you're coming from and it can't.

Verify my claim by starting a ssh session to your router.
Start tcpdump on your external interface, filtering so you see all packets to/from port 53.
Ssh into your router on the internal interface. tcpdump will show DNS queries leaving your router, asking for the hostname of whatever 192.168.1/24 source address.

Run this experiment again when you think UseDNS has been set to 'no'.
My guess is you sent SIGHUP to the wrong sshd after you changed UseDNS to no.
Answer: In /etc/ssh/sshd_config turn of reverse mapping,  its trying to do an rDNS lookup on your internal ip address.
"VerifyReverseMapping no"
Comment: "/etc/ssh/sshd_config line xxx: Deprecated option VerifyReverseMapping" did not help.
Answer: Use strace -p  on the client and server to determine what the ssh/sshd process is waiting on.
Not sure what it could be - delays are usually caused by the DNS reverse lookup but you said you already turned that off.
Answer: strace is an option as Dave mentioned, but I would try enabling verbosity on the client when logging in.  You can do this by providing the -v switch (up to 3 times for maximum verbosity), for example:
ssh -vv email@example.com

Answer: On Alex's recommendation, I ran a packet sniffer and found that the client was doing DNS lookups. As a short-term solution to test, I added 192.168.1.1 servername to the client's /etc/hosts file and things went quickly.
Comment: Consider accepting the above answer, so others with slow SSH logins can find a trouble-shooting strategy.
Comment: When I first tried, I got the message that said something to the effect of "You must wait 18 hours before accepting your own answer."


Errow using googletranslate package in Python: Expecting value: line 1 column 1 (char 0)

Question: I have extracted the tweets from twitter and now trying to convert the text to English. It should detect the source language itself and convert to English.
This is the code i'm using:
from googletrans import Translator

translator = Translator()

tweet['English']= tweet['text_clean'].apply(translator.translate,dest='en').apply(getattr, args=('text',))

It was working initially but not anymore. Tried closing the jupyter notebook and restarting it again. It gives the same error even for processing 1 record:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Any work-around?
I have already read posts and questions here on stackoverflow regarding this and tried the following:
1) Clean Text: Removed URL, smileys, blank rows, punctuation and etc.
2) Processed data in batches using chunk in order to deal with Google Translate API limit point.
Comment: Probably related: https://stackoverflow.com/questions/61042396/googletrans-suddenly-stopped-working-and-giving-error. Seems there may be a problem with the API right now.
Answer: It's working fine now, seems to be a API issue yesterday.


How do I connect to Oracle Netsuite using OAuth 2.0 Client Credentials Flow and JWT certificate with .net core


Just how specific is the term "hemiola"?

Question: In Name and structure of staggering beat in Ramones' "Merry Christmas," the rhythm in the second measure of the following example is described as a hemiola:

But to me, these are just triplets and not an example of a hemiola. Hemiolas, in my experience, are more in line with the following two examples:

Scott Wallace brought this issue up in the comments, and it led me to look up a definition. In the Harvard Dictionary of Music, hemiola is defined as:

the use of three notes of equal value in the time normally occupied by two notes of equal value.

In which case the top example would be a hemiola.
But I have yet to find a resource that explicitly shows something like the top example as a hemiola. The examples cited in the Harvard Dictionary are:

the French courante
the Viennese waltz
music by Schumann and Brahms (e.g., the opening of their third symphonies)

Note that every cited example is either in 3/4 or some other meter with a triple subdivision of the beat and/or meter. And of Wikipedia's eleven notated examples, every single one is also in one of these meters.
Based on these examples, a better definition may be:

within a meter of predominantly triple subdivision, the use of three notes of equal value in the time normally occupied by two notes of equal value.

The Ramones' example, which has a predominantly duple subdivision, would not be a hemiola following this definition.
Is our definition of the rhythmic hemiola lacking? I'm not trying to redefine a term here; I'm curious if either a) I'm being needlessly specific, b) there is a way to differentiate between these two types of hemiolas, and/or c) if other scholars/resources are more specific in their definition of the term.
Comment: In my experience hemiola is used to describe regrouping of two groups of three into three groups of two as in your second definition.  (I like to say that it is a musical manifestation of the commutative property of multiplication.) But the Oxford English Dictionary says that its plain meaning is simply "one and a half," that is, a synonym of _sesquialtera._ Both words were used both for the rhythmic proportion and to denote the pitch interval we know as the perfect fifth. The history of its use in later music theory is not covered other than to refer the reader to the 1880 Grove dictionary.
Comment: It's funny: the textual part of the definitions seem to be more general, basically saying 3:2, but the notation examples are all triple/compound.
Comment: @Aaron It depends on the predominant subdivision of the 2/4. In your stated example, where we've had eighth-note triplets (thus a predominant triple subdivision), it would be a hemiola. But if we've only had eighth notes leading into it, I'd argue it's just a triplet.
Comment: Update: the 1880 Grove only mentions the perfect fifth and triplets.  It says "three minims, sung against two, are called _Hemiolia major;_ three crotchets (_semiminims_) against two, _Hemiolia minor."_  I note that in 3/4 time, the regrouping of two measures into three groups of two beats may perhaps be seen as "the same as" three minims against two if you reach back into mensural concepts of perfection and imperfection, but otherwise it would be instructive to find out when the term began to be applied to the pre-cadential regrouping so common in triple meters in the Baroque period.
Comment: @leftaroundabout It would just be a semantic difference: whether "hemiola" describes a notational or experiential shift in rhythm.
Comment: Great question! But are you intending to suggest that by rewriting your 6/8 measure in 2/4, where the first measure was eighth-note triplets and the second measure was a quarter-note triplet, the second measure would no longer be a hemiola?
Comment: @Aaron why not? It's not much different from the other way around, when you rewrite from 2/4 to 6/8, the quavers stop being triplets.
Comment: Related question: [Is there a name for a 3-3-2-2-2 rhythm?](https://music.stackexchange.com/questions/107736/is-there-a-name-for-a-3-3-2-2-2-rhythm). [My answer](https://music.stackexchange.com/questions/107736/is-there-a-name-for-a-3-3-2-2-2-rhythm/107738#107738) there quotes the *Oxford Companion to Music*, which defines hemiola as being interchange between triple and duple meters (in either direction).
Comment: I saw the term _cadential hemiola_ several times in Baroque examples, but don't really understand the meaning. Possibly a useful distinction for terminology.
Comment: @Michael Curtis My thoughts exactly. The *text* suggests possibilities that the examples usually don't. As for the "cadential hemiola," I like it. (Where did you hear it?) I see this a fair amount in Corelli: a hemiola approaching a cadence, much like the modern idea of changing the harmonic rhythm at the end of a phrase.
Comment: here https://books.google.com/books?id=hueMBAAAQBAJ&pg=PA88 and here https://mtosmt.org/issues/mto.96.2.3/mto.96.2.3.willner.html, I only skimmed the text, searching high and low for hemiola in 4/4 :-)
Comment: My Oxford Companion to Music doesn't even contain the term! I'm happy with 'triplets', as that's what they are.
Comment: Interesting discussion to be sure.  I would agree with Richard that there's a difference in feel between three notes in the time of two depending on the subdivisions.  I would call the example from the Ramones song triplets, because the quarter notes in the first measure are not subdivided in threes (i.e. 12/8 rhythm) but into eighths, so you can't get the triplet rhythm in the second bar by simply regrouping existing note values.  This is also how I've always heard the term "hemiola" used, as the regrouping of existing note values (typically eighths) from 2-2-2 to 3-3, or vice versa.
Answer: Hemiola turns out to be fairly strictly defined (see Sources and Definitions, below). The key distinction from other 3:2 relationships is that it is a metrical event, as opposed to a rhythmic one. That is, hemiola temporarily redefines the meter of a piece by affecting the beat level or without changing the primary subdivision pulse.
Thus, the following would be hemiola
X: 1
T: Hemiola
T: 6/8 to 3/4
M: 6/8
L: 1/8
K: C clef=perc stafflines=1
!>!BBB !>!BBB | !>!BB!>!B B!>!BB |

X: 1
T: Hemiola
T: 2/4 to 3/4
M: 2/4
L: 1/4
K: C clef=perc stafflines=1
!>!B B | !>!B B | B2- | B B- | B2 |

Note that in both cases, the predominant rhythmic pulse doesn't change, but the metric accent does.
By contrast, the following are not hemiola, because the 3 and 2 divisions comprise different subdivisions of the primary beat.
X: 1
T: Not Hemiola
T: eighths versus triplets
M: 2/4
L: 1/4
K: C clef=perc stafflines=1
V:V1
V:V2 name="basic subdivisions"
[V:V1] B/2B/2 B/2B/2 | (3BBB |
[V:V2] B/2B/2 B/2B/2 | (3B/2B/2B/2 (3B/2B/2B/2 |

X: 1
T: Not Hemiola
T: eighths versus triplets
M: 2/4
L: 1/4
K: C clef=perc stafflines=1
[V:V1] B/2B/2 B/2B/2 | B      B      | (3BBB    |
[V:V2] B/2B/2 B/2B/2 | B/2B/2 B/2B/2 | B/2B/2 B/2B/2 |

Because these examples rely on duple versus triple subdivisions of the same basic pulse, they affect the rhythm but not the meter. Thus, by the strict definition, they are not hemiola.

Sources and Definitions
It is not immediately obvious from any individual source the metrical quality which distinguishes hemiola. Some sources describe it as "rhythmic." However, in all cases, it is described as affecting meter, all examples are metrical, and no examples of, say, duplets against triplets are give.
1. The Oxford Companion to Music, edited by Alison Latham (Oxford University Press, 2002), page 579.

A term denoting the ratio 3:2. In modern notation, a hemiola occurs when two bars in triple meter (e.g. 3/2) are performed as if they were notated as three bars in duple meter (6/4), or vice versa.

2. The Norton/Grove Consice Encyclopedia of Music, edited by Stanley Sadie (Macmillan Press, 1994), page 359.

In the modern metrical system it denotes the articulation of two bars in triple meter as if they were three bars in duple.

3. Stephen G. Laitz, The Complete Musician, 2nd ed. (Oxford University Press, 2008), page 63.

Another type of metrical disturbance, closely related to syncopation, is the hemiola. In a hemiola, the established meter temporarily is displaced by a competing meter.

4. Edward Aldwell and Carl Schachter, Harmony and Voice Leading, 2nd ed. (Harcourt Brace Jovanovich, 1989), page 41.

In triple and compound meters, shifted accents sometimes transform two groups of three beats into three groups of two beats. ... The technical name for this rhythmic device is hemiola.

(Note the description as "rhythmic" device, although the example given in the book is metric. That "rhythmic" and "metric" are used interchangeably is, I believe, the source of ambiguity in defining the term.)
5. Richard Hoffman, The Rhythm Book, 2nd ed. (Richard Hoffman, 2009), page 70.

Hemiola is a special form of syncopation describing the use of three even durations in place of two. ... [For example,] regroupings within the measure of triple meter.
Comment: "Because these examples rely on duple versus triple subdivisions of the same basic pulse, they affect the rhythm but not the meter." Doesn't either device effect meter? If you kept playing the rhythm of either device you would get the feel of a new meter of three.
Comment: @MichaelCurtis My understanding is that the scenario you suggest would be an actual change of meter, as opposed to the perceived, temporary change of meter brought about by hemiola.
Comment: but other than notation, how do you say that aurally the same 'perceived, temporary change of meter' isn't happening in duple time with triplets displacing the sense of beat?
Comment: @MichaelCurtis One would have to be able to distinguish aurally between, say, a 3/4 meter and a triplet rhythm. However, your question makes clear I should find a better way to express the rhythmic basis of "things that aren't hemiola", since clearly they could still suggest a change in meter.
Comment: My point is your first line "Hemiola turns out to be fairly strictly defined" explains things well. (Maybe 'arbitrary' is an appropriate description.) It's only triple/compound changed to duple and not vise versa. It seems there isn't any deeper theory of rhythm/meter at play. Otherwise it seems our reference sources don't provide enough diverse examples.
Answer: The primary use of hemiola is to describe a sort of aliasing of 3 beats vs 2 beats. There are two examples I remember from early music (actually, I remember seeing, not really being there): one is two-quarter-notes in one voice against a quarter-note triplet in the other. The author called this a "vertical" hemiola. The other example was two quarter-notes in one measure vs a quarter-note triplet in the next measure (called, of course, "horizontal" hemiola).
One modern version of the "horizontal" hemiola is the song "America" from "West Side Story." (The music I've seen just alternated 3/4 with 6/8 time. I've heard some strumming patterns of 6/8 vs 3/4 in the bass. This yields a vertical hemiola.
Sometimes this is done in waltzes over pairs of measures using half notes followed by two quarters tied across the bar line then another half note.
I think the term is used rather broadly for any 3 vs 2 rhythmic organization.
Answer: My Honegger-Massenkeil reference provides a similar dry definition, but adds a consequence, which seems more accessible (my translation):

Such hemiolas, which effect a significant shift of emphasis in the musical flow, are frequently found in the works of Dutch composers since Dufay, but also in the Baroque era, especially preceding cadenzas and also with even shorter note values. The shift is frequently shared by a corresponding sung text.

In the examples I encountered, hemiolas therefore superimpose a structure to at least two bars, so only every second one begins with a strong beat.


How To Link XCTest Dependency To Production / Main Target?

Question: I am trying to write an extension for the XCTest framework in Swift. In order to do so, I created a project with two targets: the main/production target and a test target.
As I am writing an extension for XCTest, I need to import XCTest within my main/production target as well. However, I am having trouble to do so. When in Xcode and I click on my project, then select the main target, go to Build Phases, Link Binary With Libraries and add XCTest there, I get a compile error:
ld: framework not found XCTest
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I also tried the solution provided here which unfortunately doesn't work either.
Comment: For your use-case computing test coverage, the official solution may also be appropriate: https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/07-code_coverage.html
Answer: Auxiliary information on XCTest itself is sparse and hard to find, I was also chasing down the same functionality and finally managed to get it working.
I am on XCode 10.1 and running on a real iPhone with iOS 11. I am certain the general technique will work for other versions, but probably will require a few tweaks.
The general steps are described in this stackoverflow answer, but required several additional steps and tweaks to work for me on a real iPhone:
Is it possible to run XCTest tests in an iOS app?
Follow the steps in the above link. The below steps are deviations from those instructions that were required for me.

Copy in the XCTest framework as described in the above link. NOTE: Use the framework for the iPhone.OS platform and not the simulator as it describes. You can find this framework file inside the actual XCode Application package on your mac. (Right click, "Show Package Contents", then look in ./Contents/Developer/Platforms/iPhoneOS.platform
Disable bitcode in your app target. This solves a linker error. Here is an example of enabling it: how to ENABLE_BITCODE in xcode 7?
When dragging the XCTest.framework file to the linked binaries in your target, ensure that you also drag it to the "Embedded Binaries" which is directly above the "Linked Frameworks and Libraries" option. If you don't do this you will get a runtime error.

The ViewController code to start the tests is slightly different in new Swift, here is what I am using:

import UIKit
import XCTest

class ViewController: UIViewController {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("running tests!")
        let suite = XCTestSuite.default;
        for test in suite.tests {
            test.run()
        }
    }

}

That should be it! When I run the above app, then touch the screen, all of the tests from my UITesting target run flawlessly and pass!
Comment: Unfortunately, It's still impossible to get running something like: `XCUIApplication(bundleIdentifier: "com.apple.springboard")`. It will just freeze app for 60 seconds and log error: Unable to update application state promptly for Application 'com.apple.springboard'.
Comment: Cheers for the answer!
Comment: Glad it helped!
Comment: When built with XCode 11.1, running gives the error "Library not loaded": `/private/var/containers/Bundle/Application/UUID_HERE/test2.app/Frameworks/XCTest.framework/XCTest
  Reason: image not found` any ideas?
Comment: Try opening up the .app archive on your local machine, is the framework present?
Comment: Complementing this answer: if you have problems, double check the framework search paths. It should point to the path to your copied XCTest.framework.


Why do I lose contents of my database after a heroku dyno restart?

Question: Anytime my app goes to sleep and comes back on, I lose data in my database
And I'm not storing any media, it's just form data (texts)... I built the app on strapi and I've followed all their guidelines but it keeps happening. I'd be happy if anyone can help
Comment: Which database are you using? SQlite?
Answer: Local data (files, db) is cleared after a Dyno restart because the Heroku File System is ephemeral. A Dyno is restarted (at least) every 24hrs.
In your case Strapi uses SQLite where data is saved in a local file.
Strapi suggests to configure Postgres on Heroku, alternatively you can use an external DB storage service.
Answer: First of all:

As you create content types with strapi it generates the code (= new files) for the according controllers/routes/services
Heroku does not persist data after a restart
After a restart strapi checks which content types exist in the code and deletes the tables of nonexisting types from the database.

Therefore, on Heroku you have to set up all your content types locally and connect to an external db (e.g. Heroku Postgres) but never strapi's default textfile based db.
Then push the generated files and finally deploy.
Thus, on Heroku you should always run in production mode. This way the option to alter content types is completely blocked and you will not run into the issue of data loss after a restart.


c# devexpress xtragrid LocateByValue is not working

Question: Using Devexpress Xtragird and trying to find row by ItemID column.
GridView activeView = this.DataGridSection.SectionGridControl.MainView as GridView;

1st way:
int rowHandle = activeView .LocateByValue("ItemID", 12345);
            if(rowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
                activeView .FocusedRowHandle = rowHandle;

2nd way:
        for (int i = 0; i < activeView.DataRowCount; i++)
        {
            DataRow dr = activeView.GetDataRow(i);
            if (Convert.ToInt32(dr["ItemID"]) == SelectedItemIDForEdit)
            {
                activeView.SelectRow(i);
                break;
            };
        }

Neither of them works.
Did I missed something?
Thanks.
Comment: I need to highlight that Row.
Comment: Can you tell why you need to find row from grid? Why do not get data from a bound bindingsource
Answer: LocateByValue works to me fine. Please check if first parameter is really FieldName.
To be sure, I am using GridView.LocateByValue(colId.FieldName, value);
Answer: In my case DataController.IsReady was false.
Make sure you use this function after data has been loaded.


Iterate a script X times

Question: I have several functions that may or may not need to be repeated a certain number of times. The number of times is set by the user, and is stored in a variable: xTcount.
if (xTcount > 0) {
    for (i=0; xTcount <= i; i++) {
        $(document).miscfunction();
    }

}

I haven't actually tested the script above, as i'm sure it's incorrect. What makes what i want tricky, is that i don't want to have to code a "check xTcount" clause into every function that is repeatable. if possible, i'd like to create some master checker that simply repeats the next-called function xTcount times...
Answer: Repeat some things xTcount times? Maybe I'm misunderstanding, but it looks pretty simple:
for(var i = 0; i < xTcount; i++) {
    doSomething();
    doSomethingElse();
}

If the trouble is that you don't like the look of the for loop, or that your script requires you to build the same loop multiple times, you could extract it if you reeeaaallllly wanted to:
function repeat(fn, times) {
    for(var i = 0; i < times; i++) fn();
}

repeat(doSomething, xTcount);
// ...later...
repeat(doSomethingElse, xTcount);

Comment: I have a variety of functions that i could/want to loop. I don't want to have to go into each one and create the loop clause. It'd be more flexible if the loop looped the next called function.
Comment: - i re-read your post and you did provide a master repeater function, thank you, but i can't get it to work, is there anything i should know about using it? It looks straight forward enough...
Comment: @Jason: I'm out of town with limited internet access, so can't help a ton. Regardless, I've checked and the function runs correctly. Do you get an error message or anything? Remember, pass the function as an object, rather than calling it, e.g., with `function lol() { alert("lol") }` run `repeat(lol, 5)` rather than `repeat(lol(), 5)`.

Iterate a script X times


Codeception - How to test manipulated select box option values?

Question: I want to force codeception to select a non-existing option in a html select box:
<code>$I->selectOption('#foobar', 100000);
</code>
Once I hit the test, following message gets returned:
<code>Input "foobarId" cannot take "100000" as a value (possible values: 0, 1, 2).
</code>
I want to check if there are errors shown after submitting the form. I got asked to write tests for manipulated option values.
Is there any work-around to achieve this?
Comment: If I use nice-select, how I can choose?
Answer: I think that they are asking you to test what happens when the user clicks the various options, not submit an invalid option. I don't think most browsers will allow you to submit an invalid check box. Anyway, that would seem to just be a form validation, nothing to do with "manipulating" the values.
What happens when the user doesn't click anything?
What happens when the user clicks option1, then clicks option2, then submit?
What happens when the user clicks all three options?
etc.


Roolback no Mysql 5.7 Workbench não funciona! Ajuda

Question: Ola galera tudo bem ? Sou novo no Mysql, gostaria de tirar uma dúvida.
estou usando um comando que não é DML.
porém quando dou roolback, ocorre o erro abaixo. Será que é alguma configuração
de permissão no workbench , tipo esse auto commit ali?
(uso wampserver)
Answer: Você provavelmente está utilizando tabelas no formato MyISAM que não tem suporte a transações.
Ao invés disso utilize tabela no formato InnoDB.
Como criar tabelas nesse formato:
<code>CREATE TABLE t1 (a INT, b CHAR (20), PRIMARY KEY (a)) ENGINE=InnoDB;
</code>
Também é possível alterar essa informação na opção de operação da tabela:
Comment: vixi, deu certo!!! terei que estudar sobre MyIsan e InnoDB para entender as diferenças
!!!!!!!!!!!!!!!
Answer:
Como nosso amigo ali em cima disse, o roolback não funciona em MYisan . tem que criar a tabela para innodb


Does this set of linear equations only have the trivial solution?

Question: Let $p$ be a prime and $\xi$ a $p$th root of unity in $\mathbb{C}$.
I would like to solve the system of linear equations
\begin{equation}
\sum_{n=1}^{p-1}(\xi^{nj} - 1)x_n = 0, \quad j=1, \dots, p-1
\end{equation}
over $\mathbb{C}$.
I suspect that it only has the trivial solution for every prime.
I thought of computing the determinant
\begin{equation}
\sum_{\sigma \in S_{p-1}} \operatorname{sgn} \sigma \prod_{j=1}^{p-1} (\xi^{\sigma(j) j} - 1)
\end{equation}
and show it is nonzero, but I don't see how.
Comment: Your equation is of the form $Ax=x$, where $A$ is a matrix of complex $p$th roots of one. I think it's a vandermonde matrix, and much is known about its eigenvalues and eigenvectors.
Answer: If$\ x_1,x_2,\dots,x_{p-1}\ $ is a solution of the linear equations, then the polynomial $\ q(y)=$$\sum_\limits{n=1}^{p-1}\big(y^n-1\big)x_n\ $, of degree at most $\ p-1\ $, has at least $\ p\ $ distinct roots $\ 1,$$\,\xi,$$\,\xi^2,\dots,
\,\xi^{p-1}\ $.  This is impossible unless $\ q(y)=0\ $.
Comment: I was hoping for such a beautiful and easy solution!
Comment: @lonzaleggiera e presta molto?
Comment: Ma di pel macolato non sono coverto.


HTTPS works only with Load Balancer DNS - AWS

Question: I have a problem with HTTPS configuration on AWS hope you can help.
What I already have:

EC2 - with Elastic IP, open ports screen shot with security group.
Load Balancer attached to EC2 (with same security group as EC2).
SSL certificate from AWS (ACM)
Domain - "Transferred", From another service (not amazon) using just Elastic IP for DNS configurations. (Can this be the problem?)
Route53 - configured for Domain with AWS (SSL) and for IPV4 address I am using alias for Load Balancer.

How it works:

EC2: Elastic IP and public DNS (are working only for http) as it should work I guess.
LOAD BALANCER: Works and gives HTTPS and HTTP access just from DNS name.
Route53(domain) - Works just for HTTP, every HTTPS request returns ERR_CONNECTION_REFUSED

How I explain this problem for myself (if there is problem please tell me)
So if Domain is redirecting from DNS settings to Elastic IP that's attached to EC2 there can not be SSL connection as I am using ACM for ssl certificate, that's when LOAD BALANCER comes for help to connect the Domain and SSL, but as in Domain's DNS there is not connection with LBS, AWS is not able to give the SSL just from Route53 configurations?
Is it going to fix the problem if I will change EC2's elastic ip in Domain DNS with Load Balancer's public DNS name?
Answer: Yes, using the instance's Elastic IP as a DNS A record is exactly the cause of the problem.  The DNS record needs to point directly to the load balancer.
Comment: Thanks for the answer mate, I believe it will solve the problem, as soon as I try to I will write back.
Answer: Point the DNS to tge ELB CNAME and configure Nginx/Apache as X-Proto Forward so that server can forward https redirection requests to load Balancer. If check AWS documentation you will easily able to do this.


Simulating from fitted t-distribution mgcv

Question: My question is related to the following post:
Extracting the degrees of freedom of t distribution of a GAM
I have a dataset of y-values that I am fitting using the gam-function in mgcv. The distribution of y is shown below.

The tailed nature of the data has led me to use scaled t-distribution with a log-link function. The summary of the fit outputs the following result for the fitted t-distribution:
Family: Scaled t(3.615,2476.626)
Link function: log
How would I go about plotting the above scaled t-distribution on top of the density plot above. I am unsure about the significance of the values and how the relate to the degrees of freedom and mean of the distribution.
Answer: A t distribution doesn't look like a good fit for your data. The scaled t distribution has support on the entire real number line, from -infinity to plus infinity, while your data seems to be strictly positive.
If you have 0s in your data, I would try the Tweedie family, tw(). If not, the gamma family with log link would also be a good starting point, Gamma(link = "log").
Also, we don't expect the response to be distributed t, or Tweedie, or Gamma, as a whole when we are modelling with GLMs or GAMs. When you specify the family, what you are saying is that you expect each observation to be a draw from that distribution, with it's own mean $\mu_i$. That mean is determined by the model. It would be entirely wrong to plot a single t (or other) distribution on top of the density plot of the observed response.
What you can do instead is simulate a new data set as large as the observed one, and plot its density along side the density of the response. Usually one might plot the densities of several simulate data (20-100) and look to see if the observations simulated from the model you fitted are a close facsimile of the observed data. If your model is able to recreate features of your observed data then it is one indication that it is well fitted.


What's the recommended method for charting low values?

Question:   I need to chart a number of indicators to evaluate emergency response times for a fire department.  In our case, most values should be around 2 minutes, but the range can be between 0 and 10 minutes.
  I've been working with bar charts (and Few's bullet charts), however, since bar charts work on comparing lengths, and our target values are shorter (around 20% of the bar's potential total length), I'm curious if there's a better way to chart these values.
  I've considered charting the inverse value (bar is 8 minutes, instead of 2), but that seems counter-intuitive to read.
  Any help is appreciated.
I'm trying to show the range in turnout time for each unit (blue bar, min to max) overlayed on excellent, mediocre and poor ranges (gray backgrounds).  I'm working on adding a marker for the 90th percentile (our standard, but not on chart yet).  My problem is as performance improves, the times reduce and consequently, the less length of the bar is used for comparison.  I'm trying to determine if there's a better way to mark their performance indicators, since a lower number is better (as opposed to something like profit, where bigger is better).
Sorry, it won't let me post an image to show you, but consider a basic bar chart with the x-axis as time and y-axis is categorical.  Under each bar are indicators for 3 performance levels and a single marker is applied to each bar indicating the 90th percentile.  Hope that helps.
I was able to upload a picture of the chart.  As values improve, they'll get smaller and move closer to the left edge of the bars, and the bars can shrink if the range decreases.  I just want to make sure there's as much visual info as possible to make the data points legible.
Comment: What exactly are you trying to chart and what are you trying to show? Charting 8 instead of 2 is no improvement, as far as I can see, and would probably just make the chart more confusing.
Comment: I agree with Peter.  And... could you show us what you've got so far?
Answer: I don't think you should underestimate the ability to distinguish between lower values. When placed upon a common scale, it is fairly trivial to distinguish whether one bar is lower than another (can you tell the difference between the length of bars in this example?). One thing that can happen is that bars that are not next to each other are harder to distinguish between, but gridlines and ordering the categories can help (Stephen Few gives an example where gridlines help in this whitepaper on page 2).
Some other notes though in general;

You have some target ranges, which is ok to include in your graph (to show the times all come well below them. But including the higher ranges reduces the resolution between items (which seems to be your main concern). Consider maybe having two charts, one with the full range (left panel image below), and another with a reduced range so it is easier to distinguish between items (right panel image below).

You should consider ordering the categories by the data, obvious choices here would be the range with the longest time or the percentile. Even if the categories have a natural ordering, ordering by data can be a striking way to show differences. If your data don't have a natural ordering you should be doing this anyway. See below for an example.

Finally, maybe consider showing the actual data values (or a sample of data values). I talk about it in the context of showing error bars for experimental data here, but the same logic applies in this situation. This is also a good way to show potential outliers in the data (which the range bars wouldn't really be able to show unless one inferred outliers by seeing a percentile really far away from the top range). If you have many points, consider taking a sample, or using other techniques for scatter plots with a large number of points (make the points smaller and or slightly transparent). This is also a good technique if you want to label outliers.
Comment: Andy, thanks for the answer-you hit upon a number of issues that were in my head, but I couldn't quite articulate.  Addressing the ordering isn't practical in my situation, because of a number of other contstraints (mostly related to the end users).  However, the multiple scales is a great idea, and I'm going to start working on that today.  Also, I really like the dot plot in your third point-did you create that in Excel or R?  Thanks again for your insight.
Comment: It was created in SPSS. In the linked to response on experimental data has all the information necessary to recreate the above chart in either SPSS or R (I can disseminate the code used to create the specific charts above if you want). A workflow in Excel to create jittered dot plots would be, assign groups an integer value, add random noise that is less than the distance between integer values, and then when plotting the jittered points in a scatterplot relabel the integer axis with the correct non-integer labels.
Comment: That worked great, although without enough datapoints the jitter looks a bit anemic, so I'm mostly using a simple dot plot in excel.  I don't have access to SPSS, and I'm pretty rough in R, so I muddle through with simplified excel solutions.
Answer: I think I've answered my own question.  After looking at a lot more examples from my data, pondering what Peter Flom commented, and reading Stephen Few's thoughts on negative values on bullet graphs (which is similar, but not the same as my issue), it appears that having all the values converging on the low end (low values = good in my data set), is not much differenct than having them converge on the high end of a range in other settings (e.g. more profits = good).  Based upon my data explorataion, it looks like having clearly marked axis and comparison data was more valuable then which end (left or right) of the bar the data point was at.  Thanks for all of your help, getting me to think this through.


Retornar array PHP no JSON em AJAX

Question: Tenho o seguinte código:
function atualizaPainelQtdeReservas(){
     var dataFiltro = $(".dataFiltro").val();

     $.ajax({
          url: "crud/painelQuantidadeReservas.php",
          dataType: 'html',
          data: {dataFiltro:dataFiltro},
          type: "POST",

         success: function(data){
              $('#resBusca1').html(data[1]);
         },
     });
};

E
 $dataFiltro = $_POST['dataFiltro'];
 $data = implode("-",array_reverse(explode("/",$dataFiltro)));
 $select = "SELECT SUM(numeroPessoas) as total FROM Reserva
            where data = '$data'
            group by hora
            ";
$conexao = conexao();
$PDO = $conexao -> prepare($select);
$PDO -> execute();

$total = array();
while ($obj = $PDO -> fetch(PDO::FETCH_OBJ)){
    $total[]= $obj->total;
}
echo json_encode($total);

O SELECT retornará os dados: 9, 6, 2
Quero retornar no success o array com os resultados, porém como fiz no $('#resBusca1').html(data[0]) o que me retorna é um [
Caso eu faça:
 success: function(data){
 for(var i in data) {
     document.write(data[i]);
 }
 },

o mesmo retorna ["9","6","2"]
Cada resultado (9,6,2) quero retornar em um id no html.
Alguma sugestão?
Comment: Estás a usar `dataType: 'html',` devias usar `dataType: 'json',`.
Comment: Opa, obrigado, resolveu.
E se eu precisar de um array multiplo, como poderia fazer?
Comment: Podes dar um exemplo desse json?
Answer: Para leitura de array multidimensionais, poderá ler no success do AJAX, estipulando é claro o dataType: 'json', com o $.each:
success:function(resposta){
   $.each(resposta, function(i, resp){
      // agora é colobar resp.indice que obterá o valor do índice correspondente no array json
   })
}

Retornar array PHP no JSON em AJAX


Finding probability of dependent events

Question: An urn initially contains 5 white balls and 7 black balls. If a ball is extracted at random and then returned to the urn with two more balls of the same color. What is the probability that the first two extracted balls are black and the last two are white?
I'm having a lot of trouble with this problem, I have done the following but I'm not convinced that my method is correct...
Let $N_i = \{\text{the $i$ th extraction is a black ball}\}$ and $B_i = \{\text{the $i$ th extraction is a white ball}\}$.
I'm searching for $\mathbf{P}(N_1 \cap N_2 \cap B_3 \cap B_4)$:
\begin{align}
\mathbf{P}(N_1)& = \frac{7}{12} & \mathbf{P}(N_2|N_1)& = \frac{9}{14}\\
\mathbf{P}(B_3|N_2 \cap N_1)& = \frac{5}{16} &  \mathbf{P}(B_4|B_3 \cap N_2 \cap N_1)& = \frac{7}{18}
\end{align}
Then the solution would be: $\frac{(7)(9)(5)(7)}{(12)(18)(14)(16)} = .045$
Any help is appreciated!
Comment: https://en.wikipedia.org/wiki/P%C3%B3lya_urn_model
Answer: You did everything right, i dont see any mistakes
$\mathbf{P}(N_1 \cap N_2 \cap B_3 \cap B_4)$ = $\mathbf{P}(B_4|B_3 \cap N_2 \cap N_1)$$P(B_3 \cap N_2 \cap N_1)$= $\mathbf{P}(B_4|B_3 \cap N_2 \cap N_1)$$\mathbf{P}(B_3|N_2 \cap N_1)$$P(N_2 \cap N_1)$=$\mathbf{P}(B_4|B_3 \cap N_2 \cap N_1)$$\mathbf{P}(B_3|N_2 \cap N_1)$$P(N_2|N_1)*P(N_1)$
Comment: Thanks I guess I'm confused by the fact that that I don't see clearly that when I do the product of all the probabilities the events are independent. Can you give me some input on this?

Finding probability of dependent events


Linguagem para desenvolver um sistema de live

Question: Estou interessado nos sistemas de live ex, facebook;youtube entre outros oferece esses serviços, em qual linguagem isso é feito, por onde eu começo a estudar?
Basicamente quero acessar a camera de um celular especifico e transmitir para quem estiver online no site
Answer: Para isso você precisará de uma comunicação entre os dois você pode teria que criar um servidor que comunica isso ou usar um pronto com API. Como por exemplo o Nexmo que fornece um canal de voz e vídeo. Isso se chama WebRTC.
Quanto a utilização da câmera precisa saber o que seu projeto precisa, existem aplicações para celulares nativas e híbridas. Eu hoje uso híbrida com um projeto que se chama cordova, mas também estou iniciando um projeto em kotlin.
Sabendo disso para conectar os dois pontos você precisará de um WebRTC se usar a nexmo eles tem SDK para conexão com qualquer linguagem como : PHP, JavaScript entre outras.
Estou sendo bem raso no assunto porque são tópicos completamente diferentes que exigem um estudo em profundidade mas vou colocar algumas tecnologias para você dar uma olhada e ir mais  fundo.

WebRTC;
Websocket;
Ionic;
Cordova;
React Native;
Kotlin;
OpenTok;

Vai fundo tenho certeza que vendo todas essas coisas vai começar a conectar os pontos para chegar onde precisa.


comment form custom validation

Question: I am using a custom validation in my Drupal 7 comment form.I want to match the comment_body against a word "example" so if someone just type "example"in the comment body then it will show a error message that only the word "example" is not allowed. After reading drupal api documentation i codded like this:
function mango_form_comment_node_news_form_alter(&$form, &$form_state, $form_id){
    $form['comment_body']['#prefix'] = '
Post your comment now!
';
    $form['actions']['submit']['#value'] = 'Post Your Comment';
    $form['#validate'][] = 'banana';
}

function banana($form, &$form_state) {
  if ($form_state['comment_body'] == "example") {
    form_set_error('comment_body', 'Your comment can not contain example!');
  }
}

Do not working :'( what i'm missing? Thanks
Comment: Have a read of [this](http://drupal.stackexchange.com/questions/27767/why-is-hook-form-alter-so-messy-in-d7/27784#27784), and then inspect the `$form` to find the exact element you should be referring to (probably something like `$form_state['values']['comment_body'][LANGUAGE_NONE][0]['value']`)
Comment: Thank you @Clive your answer on that post really help me to understand the array's.
Answer: The values for comment_body is not stored in $form_state but in something like:
$form_state['values']['comment_body']['und'][0]['value']

function banana($form, &$form_state) {
  if ($form_state['values']['comment_body']['und'][0]['value'] == "example") {
    form_set_error('comment_body', 'Your comment can not contain example!');
  }
}

comment form custom validation


Show that all elements of a group are inversable

Question: Let $E$ be a set , and let $f_a$ and $g_a$ be two functions such that for all $a \in E$ :
$$f_a : E \rightarrow E$$
 defined by  $ f_a(x)=ax$, and
$$g_a : E \rightarrow E$$  defined by
$ g_a(x)=xa$.
The Question is : Suppose that $f_a$ and $g_a$ are surjective  for all  $a \in E$,  and  suppose $e$ is a neutral element in $E$, show that all elements of $E$ are invertible.
I tried starting like this :
Suppose that : $x(x^{-1}) = e$
So : $(x^{-1})x(x^{-1}) = (x^{-1})e$
$e(x^{-1}) = (x^{-1})e$
So that means $f(x^{-1}) = g(x^{-1})$ are both in $E$.
I think that my answer is not logical because I don't think I showed the proper proof.
Can I get some help on how to start this answer or maybe how I can go about solving it please? Thanks in advance.
Comment: Could you write *exactly* what the problem states?  What you've doesn't really make much sense.  If f(x) = ax for all a in E then for a, b in E f(x) = ax = bx => a = axx^-1 = bxx^-1 = b which is impossible.
Comment: Or at least f(x) is not a function in that f(x) can equal both ax and bx which are not equal.  If so I don't know what an "application" is and I don't know what "inversable" means.
Comment: In the questions it has f with a little a at the bottom of it. So it's like f_a(x) if you know what I mean, I didn't know how to write it in Latex sorry.
Comment: Ok, I re-edited the questions with the proper writing.
Comment: Ah, that makes a significant difference!  It's not a single f for all elements but different f's for different elements.
Comment: I'm still not sure what the question is asking.  If E is a group then by definition all elements are invertable.
Answer: We have to show that every element in  $E$ is invertible, So let  $a \in E$, required to show  $a$ is invertible in $E$.
As $e \in E$, and $f_a$is surjective, then there exists  $x \in E$, such that $f_a(x)=e$, so that $ax=e$, hence $a$ is left  invertible.
On the other hand, as $e \in E$, and $g_a $ is surjective, then there exists  $x' \in E$, such that $g_a(x')=e$, so that $x'a=e$, hence $a$ is right invertible.
Hence  $a$ is invertible .
Comment: So in other words, E was not defined to be a group?
Comment: @Nizar Probably misunderstood since $ax = x'a = e$ means that $x'ax = x'x'a$.
Comment: @fleablood I editeed the quetion in a suitable form , however the OP didn't submit by edition yet !
Comment: Also, $x = x'$ in that case, since $(x'a)x = x'(x'a)$ (under the assumption of associativity, but if it's a group...)
Comment: @PaulPicard just let me check my knowledge, should  $x$ and $x'$ be equal to say that  $a$ is invertible ??  and sorry I dont get what did you wrote above.
Comment: @PaulPicard I don't think  $E$ is a group, otherwise every element is invertible .
Comment: @Nizar No, $a$ is invertible in $E$ if it has a left and a right inverse. So what you wrote is right. ($x$ and $x'$ can be different)
Comment: @PaulPicard so in your comment did you mean  $(x'a)x=x'(xa)$, or I misunderstood you ?


datatables formatar campo

Question: Boas, precisava de uma dica: como é que meto o render do datatables para me mostrar apenas a data da linha abaixo, e para formatar o valor seguinte para o €?
   "mrender": function ( data, type, row ) {
                                        //The date value was 2011/04/25, now it's reversed.
                                        //Wed Sep 10 2014 00:00:00 GMT+0700 (SE Asia Standard Time)
                                        var fullDate = row[4].toString();
                                        date = fullDate.substring(8, 10);
                                        month = fullDate.substring(4, 7);
                                        year =fullDate.substring(11, 15);
                                        fixDate = date.concat(" "+month+" "+year);
                                        return fixDate;
                                    },
                                    "targets": 6,
                }

2016-04-29 00:00:00.000
45.4400
Comment: Você já tem algum exemplo de código começado para colocar na sua pergunta?
Answer: Para datas, eu usaria o Moment.js:
var fullDate = moment(row[4].toString()).format('YYYY-MM-DD hh:mm:ss');

Para dinheiro, o Numeral.js:
var grana = numeral(45,4400).format('0.0')

Comment: isso da para datatables?
Comment: É JS, então serve pra qualquer coisa em JS, inclusive o datatables.

datatables formatar campo


Implicit Differentiation in multivariate calculus

Question: Let $y(x)$ be the be given explicitly by the equation :
$xy\left( x\right) -\ln y\left( x\right) = 1$
Determine $\dfrac {dy}{dx}$
I'm unsure of how to go about this problem.
Comment: I think you mean: $\frac{\text{d}y}{\text{d}x}$?
Answer: Deriving with respect to $x$ we have:
$$
\frac{d}{dx}(xy)-\frac{d}{dx}(\ln y)+\frac{d}{dx}(-1)=0
$$
$$
y+x\frac{dy}{dx}-\frac{1}{y}\frac{dy}{dx}=0
$$
$$
\frac{dy}{dx}\left(x-\frac{1}{y} \right)=-y
$$
$$
\frac{dy}{dx}=\frac{y^2}{1-xy}
$$
Answer: I'm going to abbreviate $y(x)$ as $y$ and $\frac{dy}{dx}$ as $y'$. I assume you mean to differentiate with respect to $x$. Please correct me if I'm wrong.
For $xy -\ln y = 1$, we differentiate both sides as $y+xy'-\frac{1}{y}y'=0.$
Then, we write $-y=y'(x-\frac{1}{y})$.
Finally $$y'=\frac{-y}{x-\frac{1}{y}}=\frac{-y^2}{xy-1}.$$
If you want to write the derivative entirely in terms of $x$, you need to use the $W$ Lambert function, as you cannot solve $xy-\ln y=1$ for y using only "elementary functions" (some consider the Lambert function elementary, but I do not).
Comment: It seems that you have a mistake in the derivative of the product $xy$. :)
Answer: NOTE - the original question, before it was changed, was to find $\frac{dy}{dt}$, so that is what this answer is answering.  Even though $t$ is not a part of the original equation, finding the derivative of one variable with respect to another that isn't present is very commonly used in related rates problems.  Since $dt$ is just a value like any other, it can be divided just like any other, just as long as you do it to both sides.
To find the answer, just take a differential and divide by $dt$.  Usually, in Calculus, people try to find whole derivatives, but really, finding the differential first and then dividing is best.
Let's start with your problem:
$$xy - \ln y = 1$$
Now, take the differential:
$$x\cdot dy + y\cdot dx - \frac{dy}{y} = 0$$
Now that you have the differential, divide both sides by $dt$:
$$x\frac{dy}{dt} + y\frac{dx}{dt} - \frac{1}{y}\frac{dy}{dt} = 0$$
Now, solve for $\frac{dy}{dt}$:
$$x\frac{dy}{dt} + y\frac{dx}{dt} - \frac{1}{y}\frac{dy}{dt} = 0$$
$$x\frac{dy}{dt} + y\frac{dx}{dt} = \frac{1}{y}\frac{dy}{dt} $$
$$y\frac{dx}{dt} = \frac{1}{y}\frac{dy}{dt} - x\frac{dy}{dt} $$
$$y\frac{dx}{dt} = (\frac{1}{y} - x)\frac{dy}{dt}$$
$$\frac{y}{\frac{1}{y} - x}\frac{dx}{dt} = \frac{dy}{dt}$$
Answer: I solved $y(x)$ not $y'(x)$, I'm sorry.
$$xy(x)-\ln(y(x))=1\Longleftrightarrow$$
$$\frac{\text{d}}{\text{d}x}\left[xy(x)-\ln(y(x))\right]=\frac{\text{d}}{\text{d}x}\left[1\right]\Longleftrightarrow$$
$$xy'(x)+y(x)-\frac{y'(x)}{y(x)}=0\Longleftrightarrow$$
$$y(x)+y'(x)\left[x-\frac{1}{y(x)}\right]=0\Longleftrightarrow$$

Let $\text{A}(x,y)=y$ and $\text{Q}(x,y)=x-\frac{1}{y}$,
This is an exact equation, because $\frac{\partial\text{A}(x,y)}{\partial y}=1=\frac{\partial\text{Q}(x,y)}{\partial x}$.
Define $f(x,y)$ such that $\frac{\partial f(x,y)}{\partial x}=\text{A}(x,y)$ and $\frac{\partial f(x,y)}{\partial y}=\text{Q}(x,y)$:
Then, the solution will be given by $f(x,y)=\text{C}$, where $\text{C}$ is an arbitrary constant.
Integrate $\frac{\partial f(x,y)}{\partial x}$ with respect to $x$ in order to find $f(x,y)$:
$f(x,y)=\int y\space\text{d}x=yx+g(y)$ where $g(y)$ is an arbitrary function of $y$.
Differentiate $f(x,y)$ with respect to $y$ in order to find $g(y)$:
$\frac{\partial f(x,y)}{\partial y}=\frac{\partial}{\partial y}\left[yx+g(y)\right]=x+\frac{\text{d}g(y)}{\text{d}y}$.
$$x+\frac{\text{d}g(y)}{\text{d}y}=x-\frac{1}{y}\Longleftrightarrow$$
$$\frac{\text{d}g(y)}{\text{d}y}=-\frac{1}{y}\Longleftrightarrow$$
$$g(y)=-\ln|y|\Longleftrightarrow$$
$$f(x,y)=y(x)-\ln|y|\Longleftrightarrow$$
$$f(x,y)=y(x)-\ln|y|$$

$$yx-\ln|y|=f(x,y)\Longleftrightarrow$$
$$yx-\ln|y|=\text{C}\Longleftrightarrow$$
$$y(x)=-\frac{\text{W}\left(\text{C}x\right)}{x}$$