MSE Intuition and Interpretation

Question: I've got a very small question. Say I'm making a linear regression model. When I test the model with a testing set, I get an MSE of 4.31 (arbitrary). What do I interpret from this? As in, what does this '4.31' represent, or rather mean?
Until now, I was thinking of it as the average squared difference between target and predicted values. Thus, I thought it showed that the average prediction differed by sqrt(4.31) from the average actual value, but I'm not sure.
Answer:
what does this '4.31' represent, or rather mean?
Until now, I was thinking of it as the average squared difference between target and predicted values.

This is exactly correct.

Thus, I thought it showed that the average prediction differed by sqrt(4.31) from the average actual value, but I'm not sure.

And this is incorrect.
That the mean squared error (MSE) is $4.31$ does not imply that the mean absolute error (MAE) is $\sqrt{4.31}$. In fact, there is no simple relationship between the MSE and the MAE that always holds.

Here is an example. Suppose your actuals are iid standard normally distributed, $y\sim N(0,1)$. You have two different predictions.

The first prediction is a flat zero, $\hat{y}=0$.

The expected MSE of this is the expectation of a $\chi_1$ distribution, which is $1$.
The expected MAE of this is the expectation of a standard normal distribution left truncated at zero, which is $\frac{2}{\sqrt{2\pi}}\approx 0.80$.

The second prediction is perfect, $\hat{y}=y$, with probability $0.9$, and off by $\sqrt{10}\approx 3.16$, $\hat{y}=y+\sqrt{10}$ with probability $0.1$.

The expected MSE of this is $0.1\times 10=1$, as above.
The expected MAE of this is $0.1\times\sqrt{10}\approx0.32$.

We see that you can have the same MSE but different MAEs.
Comment: Thanks! Can't upvote because of lack of reputation.
Comment: @stephankolassa How would you explain this difference to a non-technical manager? The average squared difference being 4.31 certainly makes it sound like the average difference is $\pm \sqrt{4.31}$!
Comment: @Dave: that's a very good question. Unfortunately, there is no easy answer. I would explain to him that it doesn't work that way *for technical reasons* and be ready with an example like this if the manager wants to dig deeper. Ultimately, I'm afraid the only solution is to demonstrate your competence to your manager to a degree that he trusts you even if what you say sounds unintuitive.
Answer: I'll just formulate some ideas and give leads to free introductory material.
The raw MSE figure in itself doesn't tell you much.
Depending on the quantities in your sample space, sqrt(4.31) could be very small, or very big, which may make you want to use the model or not.
What you can use it for is the comparison of different models, and favor the one with smallest MSE. Within the data you have, your model with MSE = 4.31 could be the worst as well as the best.
From the Wikipedia Mean squared error page:

The MSE is a measure of the quality of an estimator—it is always non-negative, and values closer to zero are better.

The article contains further links about specifics on regression and prediction if you look for more advanced content.
For an accessible video introduction: Khan Academy has a serie on Squared Error
To sum it up: MSE is a relative measure of how well your model fits your sample data.
There is more to it if you know more about the distribution of the different variables, dependent, independent and residuals, and you might be interested in ANOVA and goodness of fit to go further on the topic.
I hope this helps,
All the best,
Mathieu

MSE Intuition and Interpretation


Calculating the parent tile coordinates in google maps

Question: How can I most efficiently calculate a given tile's parent tile coordinates?
Let say I have a tile with coordinates:
x = 2194
y = 1287
z = 12

How can I then calculate its parent tile's coordinates in zoom 11?
Answer: Google Maps is using a quad tree representation to calculate the indizes of their tiles. You can find an example on how the addressing system works here. In this link there is also a class available with many utility methods for conversions.
In general the parent tile should be available if you divide (and optionally round down) both x and y values:
x = 1097
y = 643
z = 11


Understanding why $0 = \lim_{x \to x0} \frac{\sum_{k=0}^{n} a_k (x - x_0)^k}{(x - x_0)^n}$ means $a_k = 0$ in a proof of Taylor's Theorem

Question: I was perusing an answer to this question here, but I'm confused regarding the last line
$0 = \lim_{x \to x0}  \frac{\sum_{k=0}^{n} a_k (x - x_0)^k}{(x - x_0)^n}$
this implies that $a_0 = a_1 = ... = a_n = 0$. I'm not sure why it implies that the coefficients are equal to  zero. I do see that the limit of the numerator must be zero, but that would only imply the first coefficient $a_0$ (when $k = 0$ ) must be zero, but for $k > 0
$, why do the coefficients have to be zero? My understanding is that as $x \to x_0$, $(x - x_0) \to 0$, then the coefficients can be any value?
Comment: See this answer https://math.stackexchange.com/a/1925036/72031
Comment: Also since you can understand why $a_0$ must be zero, just put $a_0=0$ and then first term in sum vanishes and $(x-x_0)$ can be cancelled from numerator and denominator. The resulting limit shows $a_1=0$ and so on. Thus you had almost reached the answer, but somehow did not trust your method.
Answer: It may be easiest to pretend that $n = 1$ for a moment. Then the limit is
$$ \frac{a_0}{(x - x_0)} + a_1.$$As $x \to x_0$, the denominator in the first term blows up, so that if $a_0 \neq 0$ then there is no limit at all. So $a_0 = 0$. The last term is independent of $x$. But as we know the limit is $0$, we find that $a_1$ must also be zero.
It's the same basic reasoning for longer expansions: each denominator would blow up in the limit, forcing the corresponding numerators to be $0$; and thus the constant must also be $0$.
Answer: If
$$L=\lim_{x \to x_0} \sum^{n}_{k=0}\frac{a_k}{(x-x_0)^{n-k}}=0 $$
then every coefficient $a_k=0.$
If the unique non-zero coefficient is $a_n$ then the limit is limit of a constant $a_n$, so $a_n=0$.
Define the set $A=\{k\,|\,a_k \neq 0 \} $, if $A$ is empty then $a_k=0,\; \forall k$. Suppose $A$ is not empty, then it has a minimum $s<n$ (the case $s=n$ it's not possible by our first argument ) such that $a_s \neq 0$.
We have $\lim\limits_{x \to x_0} (x-x_0)^{n-s}=0$, and by the   multiplication of limits,
$$0= \lim_{x \to x_0} (x-x_0)^{n-s} \lim_{x \to x_0} \sum^{n}_{k=s}\frac{a_k}{(x-x_0)^{n-k}} $$
$$=\lim_{x \to x_0} \sum^{n-s}_{k=0}(x-x_0)^{n-s}\frac{a_{k+s}}{(x-x_0)^{n-s-k}}=\lim_{x \to x_0} \sum^{n-s}_{k=0}a_{k+s}(x-x_0)^{k}=a_s $$
so $a_s=0$ a contradiction. Then $a_k=0$ $\forall k.$


Most general $2$-form in $\mathbb R^3$

Question: I'm currently reading "The Geometry Of Physics An Introduction" by Theodore Frankel.
On page 69 in the chapter introducing the "Grassmann Algebra" he writes down this expression of a "most general $2$-form in $\mathbb{R}^3$":
$$\sum_{i<j}  b_{ij} dx^i \land dx^j = b_{12}dx^1 \land dx^2 + b_{13}dx^1 \land dx^3 + b_{23}dx^2 \land dx^3 $$
$$ = b_{23}dx^2 \land dx^3 + b_{31}dx^3 \land dx^1 + b_{12}dx^1 \land dx^2 $$
But as I understood it they're not equal because the tensor in the $b_{31}$ term would be minus the tensor in the $b_{13}$ term due to the antisymmetry? Is this just a definition or have I not understood something ( which is definitely possible since I  only started this chapter today and am not very good at math yet...).
Answer: The matrix of coefficients $(b_{ij})$ is skew-symmetric, so $$b_{13}dx^1\wedge dx^3=-b_{13}dx^3\wedge dx^1=b_{31}dx^3\wedge dx^1.$$ To see this, note the if we call the form $\omega,$ then $\omega\left(\frac{\partial}{\partial x^1},\frac{\partial}{\partial x^3}\right)=b_{13},$ $\omega\left(\frac{\partial}{\partial x^3},\frac{\partial}{\partial x^1}\right)=b_{31},$ and $$\omega\left(\frac{\partial}{\partial x^1},\frac{\partial}{\partial x^3}\right)=-\omega\left(\frac{\partial}{\partial x^3}\frac{\partial}{\partial x^1}\right).$$
Comment: thanks, I reread the chapter and understand now... I just had a brainfart there, it's too hot today.

Most general $2$-form in $\mathbb R^3$


wait for a series of continuous tasks to finish

Question: template<class T>T MainPage::addSubtract(T num1, T num2,boolean add){
T result;
task<T> t( [num1, num2, add,result]()->T{
    if (num1 < 0 || num2 < 0){
        throw ref new Exception(-1, "Invalid Arguments");
    }
    else{
        if (add){
            OutputDebugString(num1.ToString()->Data());
            OutputDebugString(L"\n");
            OutputDebugString(num2.ToString()->Data());
            return num1 + num2;
        }
        else{
            return num1 - num2;
        }
    }
});
t .then([result](task<T> t)mutable->T{
    try{
        //T result;
        OutputDebugString(L"REsult= ");
        result = t.get();
        OutputDebugString(result.ToString()->Data());
        //this->resultTextBlock->Text = result.ToString();
        return result;
    }
    catch (Exception^ e){
        OutputDebugString(L"Exception encountered");
        return -1;
    }
});
return result;

}
I have tried wait() and get() at the end of the second task but it didnt work out(throws an unhandled exceptionAn invalid parameter was passed to a function that considers invalid parameters fatal.). What i want to do is return the result only when both the tasks have finished executing.
Comment: Have you tried when_all? http://msdn.microsoft.com/en-us/library/jj987923.aspx
Answer: The error occurs because you return result, which was never assigned to. A default-constructed task cannot be used.
Here, the error lets you know that you made a mistake. The task doing actual work is t, but you're not returning that.
You've also got a problem in the continuation task. Calling t.then(...) creates a new task that is dependent on t, but you're not assigning the result of that call to anything. The return value is just lost.
So even if you returned t instead of result, the client code would never know you had a continuation there.
Instead, either assign again:
t = t.then(...

Or even nicer, chain the call directly after the first task.
return create_task([=] {
    ...
}).then([=](task<T> result) {
    ...
});

Note that what being returned is the result of the call to then(). That's the end of the task chain, which is probably what you meant to wait for in the client code.
Another note: normally, you can just accept the T value in the continuation rather than task<T>. Exceptions and cancellation will propagate as you'd expect.
return create_task([=] {
    ...
}).then([=](T result) {
    ...
});

Now, if the first task fails or is cancelled, the continuation specified in then() won't be run. And this propagates to the client code of this method as well.
In my experience, taking task<T> as a parameter is mostly useful when you want to observe and differentiate success/failure/cancellation in detail (like printing debug messages for instance.)


Lilypond: How can I put the chord names above the right notes?

Question: it's my first time creating a lead sheet with a melody, lyrics and chords.
I just can't figure out how to place the chord symbols where I want them, they just appear "anywhere". I looked on the Internet and browsed the documentation on the Lilypond homepage, but sadly couldn't find an answer.
I'm grateful for answers.
This is the first part of my score:

And this is my code:
harmonies = \chordmode {\set minorChordModifier = \markup { "-" }
\time 6/8
 des6 es4:min bes6:min as/f bes:min f:min ges des ges des f:min ges bes:min f:min ges es:min des/es | ges:6 des
}

So the D flat Major chord and the second, the e flat minor, are in the right position. But the B flat minor chord should be after the third barline and the A flat major after the fourth...
Answer: I'd like to offer a suggestion, related to your question. Hit "enter" in your music where a measure should end; this will help you visually keep a clear head about where your music is. You can also look into Lilypond's bar checks:
1.2.5 Bar checks
You seem to have written the melody well enough; the chords are just as easy.
For instance, it looks like your melody is this:
melody = \relative c' {
 \key des \major
 \time 6/8
 \partial 4
 des8 ees
 f4 bes8 aes4 f8
 ges4 f8 ees4 ees8
 f4 des8 bes bes des
 % ...continuing...
}

And chords follow most of the same rules as entering melody:
lead = \chordmode {
 \set minorChordModifier = \markup { "-" }
 \partial 4
 des4
 s2.
 ees4.:m bes:m
 aes2./f
 % ...continuing...
}

And then together:
\score {
 <<
  \new ChordNames \lead
  \new Staff \melody
 >>
}

You obviously wrote the melody down with no trouble, so your problem here with the chords is likely that you just missed counting a rhythm value somewhere. By setting up your music in the way I outlined above, you can quickly see what the start of each measure is supposed to be, and you can easily count each measure to see if it adds up.
Just as another short example, if I wrote the following:
\relative c' { \time 3/4 d4 e2 g2 a4 b d8 a g4~ g2 b c2 fis16 g bes a ees4 aes ces ges2 cis4 bis2. ais }

And there is one rhythm error, can you quickly point it out?
Now try it again with the music separated according to measures:
 \relative c' {
  \time 3/4
  d4 e2
  g2 a4
  b d8 a g4~
  g2 b
  c2 fis16 g bes a
  ees4 aes ces
  ges2 cis4
  bis2.
  ais
 }

You can more easily check where a measure has gone wrong: the fourth measure, which is the fourth line of my melody: there's a g2 followed by a b. Since there is no number after the b, it takes whatever the previous rhythmic value was... namely a 2, a half note, and you know you can't fit two of those in a single measure of 3/4 time!
I believe this answers your question of how you can put the chords above the correct notes... but I also hope it helps you to avoid some problems in the future, so you can focus more of your energy on getting that beautiful music written and less time figuring out where the rhythm went wrong. :) I've been there. Oh, I've been there.
Happy Lilyponding!
Answer: Without seeing your full code, there are two possible issues:

Make sure you include a \partial 4 in your harmonies block to match the anacrusis in the melody.
Also make sure you're using correct duration markings in the harmonies block; des6 is unclear, since 6 isn't a real duration. If the Ef-minor chord should last that entire measure, you should input es2.:min to show that it will last a duration of a dotted-half note (that is, 6 eighth notes).
Answer: Your input appears to be chaotic: I cannot blame LilyPond for not knowing what to do with it.  In chordmode, a note is written
<root name> <duration> : <named chord modifiers> <numbered chord modifiers>

Now you start out with des6 which is already nonsensical since 6 is not a valid note duration (by the way: LilyPond's error messages are pretty important for figuring out what happens: you should not just ignore them).  Durations are 1 2 4 8 (for whole, half, quarter, eighth notes), possibly followed by dots, possibly followed by a multiplier like *5 or *5/8: particularly with chords and lyrics it is pretty common to have to work with multipliers in order to get the total length right.
So the first note maybe was intended to be des8*8:6 in order to indicate a D♭6 chord with a duration of 8 eighth notes?  Just guessing.


Evitar chamadas sucessivas de getElementById com o mesmo parâmetro

Question: Possuo o seguinte código:
function valida_form (){

        var filter_nome = /^([a-zA-Zà-úÀ-Ú0-9]|-|_|\s)+$/ ;
        if(!filter_nome.test(document.getElementById("input_nome_cad").value)){
            document.getElementById("input_nome_cad").value='';
            document.getElementById("input_nome_cad").placeholder = "Nome inválido";
            document.getElementById("input_nome_cad").focus();
            document.getElementById("input_nome_cad").style.borderColor = "#ff0000";
            document.getElementById("input_nome_cad").style.outline = "#ff0000";
            return false;
        }
}

No código existem várias interações realizadas em um elemento com o mesmo "ID", existe alguma forma de chamá-lo apenas 1 vez ?
Comment: Por que não salvar o resultado do `getElementById` numa variável?
Comment: @PabloAlmeida Sou totalmente newb em javascript, é possível você utilizando o código acima, expor uma solução via código, pls...
Comment: @MagicHat, experimentou usar `` e definir um css para caso o input seja invalido: `#input_nome_cad:invalid { borderColor: red; outline: red; }`?
Comment: @TobyMosque é pq estou evitando HTML5... Se pode me ajudar nessa dúvida aqui (http://pt.stackoverflow.com/questions/131579/retornar-div-ao-estilo-anterior-ap%C3%B3s-ter-alterado-estilo-somente-com-javascrip) ? Vê se se consegue me ajuda nessa...pls
Answer: Uma solução simples é criar uma variável local à sua função para guardar o resultado e usar essa variável dali em diante:
function valida_form(){

    var filter_nome = /^([a-zA-Zà-úÀ-Ú0-9]|-|_|\s)+$/ ;
    var campoDeNome = document.getElementById("input_nome_cad");

    if(!filter_nome.test(campoDeNome.value)){
        campoDeNome.value='';
        campoDeNome.placeholder = "Nome inválido";
        campoDeNome.focus();
        campoDeNome.style.borderColor = "#ff0000";
        campoDeNome.style.outline = "#ff0000";
        return false;
    }
}

Se você está usando JQuery, você pode aproveitar o fato de que as funções do JQuery costumam retornar o próprio objeto JQuery modificado/requisitado, o que possibilita o encadeamento (chaining) de chamadas.
Um exemplo (incompleto, mas dá pra ter uma ideia) seria:
$('#input_nome_cad').val('')
    .attr('placeholder', 'Nome inválido')
    .focus()
    .css('border-top-color', '#ff0000');

Comment: tá faltando a validação do regex dá uma olhada! `if(!filter_nome.test(document.getElementById("input_nome_cad").value)){`
Comment: Ops. Verdade. Obrigado. :)
Comment: @MagicHat Dê uma olhada na edição.
Comment: @Pablo Almeida Entendi seu ponto de vista, mas nesse caso estou chamando a variável várias vezes, eu busco uma solução para minimizar as chamadas e aplicar somente as ações pretendidas. Nem sempre o que se busca é possível, mas vou dar mais uma fuçada... Vwl
Comment: Não existe "chamar variável". Existe chamar método. O método está sendo chamado apenas uma vez. Acredito que você está tentando otimizar onde não precisa.
Comment: @Pablo Almeida Entendi seu ponto de vista, mas nesse caso estou "reutilizando" a variável , eu busco uma solução para minimizar a "reutilização" e aplicar somente as ações pretendidas. A questão da necessidade é pessoal, agradeço da mesma forma.
Answer: Se pode segmentar as rotinas e utilizar em diversos inputs

function valida_nome(value) {
  var filter_nome = /^([a-zA-Zà-úÀ-Ú0-9]|-|_|\s)+$/;
  return filter_nome.test(value);
};

function layout_error(input) {
  input.value = '';
  input.placeholder = "Nome inválido";
  input.focus();
  input.style.borderColor = "#ff0000";
  input.style.outline = "#ff0000";
};

function layout_ok(input) {
  //input.style.borderColor = "#EFEFEF";
  //input.style.outline = "#EFEFEF";
  input.style = null;
};

function valida_form() {
  var campoDeNome = document.getElementById("input_nome_cad");

  if (!valida_nome(campoDeNome.value)) {
    layout_error(campoDeNome)
    return false;
  }
  layout_ok(campoDeNome);
  return true;
};
<form action="" method="post" onSubmit="return false;">
  <input type="text" name="input_nome_cad" id="input_nome_cad" />
  <button type="button" onclick="valida_form()">Enviar</button>
</form>


Javascript, tratando código unicode

Question: Como posso imprimir o caractere de um código Unicode?
Por exemplo:
var i = "\u0062";

Como converto esse código para o caractere que ele representa?
Answer: Simplesmente imprima-o:

"- Como converto esse código para o caractere que ele representa?"

Essa "conversão" é feita automaticamente. É muito normal você ver códigos escritos assim após serem obfuscados. Já até foi feita uma pergunta sobre obfuscação de códigos JavaScript aqui.

Mas se, por algum bom motivo, você quiser converter "na mão", tem essa pequena função que pode te auxiliar:

function unicodeToChar(text) {
   return text.replace(/\\u[\dA-F]{4}/gi,
          function (match) {
               return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
          });
}

var i = "\u0062";

document.write(unicodeToChar(i));

Fonte: resposta do Bryan Rayner no SOen: Converting unicode character to string format (Ctrl+C > Ctrl+V).
Leitura recomendada: MDN - String.fromCharCode();

Achei que seria interessante compartilhar, também, essa tabela que uso bastante nas minhas consultas: RapidTable - Unicode characters table;
Comment: Como seria em string?
Comment: @LinhadeCódigo Abre essa documentação que postei o link. É só você passar os códigos numéricos de cada caractere separados por vírgula que o método retorna a string convertida. Use a função que postei como modelo.

Javascript, tratando código unicode


Select múltiplas tabelas organizando por data

Question: mysql> SELECT * FROM COLABORADOR;
+----+----------+
| ID | NOME     |
+----+----------+
|  2 | FULANO 2 |
|  3 | FULANO 3 |
+----+----------+
2 rows in set (0.00 sec)

mysql> SELECT * FROM JORNADA;
+----+---------------------+---------------------+----------------+
| ID | ENTRADA             | SAIDA               | COLABORADOR_ID |
+----+---------------------+---------------------+----------------+
|  3 | 2017-10-02 10:00:00 | 2017-10-02 19:00:00 |              2 |
|  4 | 2017-10-03 10:00:00 | 2017-10-03 19:00:00 |              2 |
|  5 | 2017-10-04 10:00:00 | 2017-10-04 19:00:00 |              2 |
|  6 | 2017-10-05 10:00:00 | 2017-10-05 19:00:00 |              2 |
|  7 | 2017-10-06 10:00:00 | 2017-10-06 19:00:00 |              2 |
|  8 | 2017-10-02 09:00:00 | 2017-10-02 18:00:00 |              3 |
|  9 | 2017-10-03 09:00:00 | 2017-10-03 18:00:00 |              3 |
| 10 | 2017-10-04 09:00:00 | 2017-10-04 18:00:00 |              3 |
| 11 | 2017-10-05 09:00:00 | 2017-10-05 18:00:00 |              3 |
| 12 | 2017-10-06 09:00:00 | 2017-10-06 18:00:00 |              3 |
+----+---------------------+---------------------+----------------+
10 rows in set (0.00 sec)

mysql> SELECT * FROM INTERVALO;
+----+---------------------+---------------------+----------------+
| ID | ENTRADA             | SAIDA               | COLABORADOR_ID |
+----+---------------------+---------------------+----------------+
| 11 | 2017-10-02 12:00:00 | 2017-10-02 13:00:00 |              3 |
| 12 | 2017-10-03 12:00:00 | 2017-10-03 13:00:00 |              3 |
| 13 | 2017-10-04 12:00:00 | 2017-10-04 13:00:00 |              3 |
| 14 | 2017-10-05 12:00:00 | 2017-10-05 13:00:00 |              3 |
| 15 | 2017-10-06 12:00:00 | 2017-10-06 13:00:00 |              3 |
| 16 | 2017-10-02 12:00:00 | 2017-10-02 13:00:00 |              2 |
| 17 | 2017-10-03 12:00:00 | 2017-10-03 13:00:00 |              2 |
| 18 | 2017-10-04 12:00:00 | 2017-10-04 13:00:00 |              2 |
| 19 | 2017-10-05 12:00:00 | 2017-10-05 13:00:00 |              2 |
| 20 | 2017-10-06 12:00:00 | 2017-10-06 13:00:00 |              2 |
+----+---------------------+---------------------+----------------+
10 rows in set (0.00 sec)

mysql> SELECT
    -> NOME,
    -> INTERVALO.ENTRADA AS INTERVALO_ENTRADA,
    -> INTERVALO.SAIDA AS INTERVALO_SAIDA
    -> FROM INTERVALO
    -> JOIN COLABORADOR
    -> ON COLABORADOR_ID = COLABORADOR.ID;
+----------+---------------------+---------------------+
| NOME     | INTERVALO_ENTRADA   | INTERVALO_SAIDA     |
+----------+---------------------+---------------------+
| FULANO 2 | 2017-10-02 12:00:00 | 2017-10-02 13:00:00 |
| FULANO 2 | 2017-10-03 12:00:00 | 2017-10-03 13:00:00 |
| FULANO 2 | 2017-10-04 12:00:00 | 2017-10-04 13:00:00 |
| FULANO 2 | 2017-10-05 12:00:00 | 2017-10-05 13:00:00 |
| FULANO 2 | 2017-10-06 12:00:00 | 2017-10-06 13:00:00 |
| FULANO 3 | 2017-10-02 12:00:00 | 2017-10-02 13:00:00 |
| FULANO 3 | 2017-10-03 12:00:00 | 2017-10-03 13:00:00 |
| FULANO 3 | 2017-10-04 12:00:00 | 2017-10-04 13:00:00 |
| FULANO 3 | 2017-10-05 12:00:00 | 2017-10-05 13:00:00 |
| FULANO 3 | 2017-10-06 12:00:00 | 2017-10-06 13:00:00 |
+----------+---------------------+---------------------+
10 rows in set (0.00 sec)

mysql> SELECT
    -> NOME,
    -> JORNADA.ENTRADA AS JORNADA_ENTRADA,
    -> JORNADA.SAIDA AS JORNADA_SAIDA
    -> FROM JORNADA
    -> JOIN COLABORADOR
    -> ON COLABORADOR_ID = COLABORADOR.ID;
+----------+---------------------+---------------------+
| NOME     | JORNADA_ENTRADA     | JORNADA_SAIDA       |
+----------+---------------------+---------------------+
| FULANO 2 | 2017-10-02 10:00:00 | 2017-10-02 19:00:00 |
| FULANO 2 | 2017-10-03 10:00:00 | 2017-10-03 19:00:00 |
| FULANO 2 | 2017-10-04 10:00:00 | 2017-10-04 19:00:00 |
| FULANO 2 | 2017-10-05 10:00:00 | 2017-10-05 19:00:00 |
| FULANO 2 | 2017-10-06 10:00:00 | 2017-10-06 19:00:00 |
| FULANO 3 | 2017-10-02 09:00:00 | 2017-10-02 18:00:00 |
| FULANO 3 | 2017-10-03 09:00:00 | 2017-10-03 18:00:00 |
| FULANO 3 | 2017-10-04 09:00:00 | 2017-10-04 18:00:00 |
| FULANO 3 | 2017-10-05 09:00:00 | 2017-10-05 18:00:00 |
| FULANO 3 | 2017-10-06 09:00:00 | 2017-10-06 18:00:00 |
+----------+---------------------+---------------------+
10 rows in set (0.00 sec)

Como fazer um select mesclando mas mantendo na mesma linha o dia.
Exemplo
+----------+---------------------+---------------------+---------------------+---------------------+
| NOME     | JORNADA_ENTRADA     | INTERVALO_ENTRADA   | INTERVALO_SAIDA     | JORNADA_ENTRADA     |
+----------+---------------------+---------------------+---------------------+---------------------+
| FULANO 2 | 2017-10-02 10:00:00 | 2017-10-02 12:00:00 | 2017-10-02 13:00:00 | 2017-10-02 19:00:00 |
| FULANO 2 | 2017-10-03 10:00:00 | 2017-10-03 12:00:00 | 2017-10-03 13:00:00 | 2017-10-03 19:00:00 |
| FULANO 2 | 2017-10-04 10:00:00 | 2017-10-04 12:00:00 | 2017-10-04 13:00:00 | 2017-10-04 19:00:00 |
| FULANO 2 | 2017-10-05 10:00:00 | 2017-10-05 12:00:00 | 2017-10-05 13:00:00 | 2017-10-05 19:00:00 |
| FULANO 2 | 2017-10-06 10:00:00 | 2017-10-06 12:00:00 | 2017-10-06 13:00:00 | 2017-10-06 19:00:00 |
| FULANO 3 | 2017-10-02 09:00:00 | 2017-10-02 12:00:00 | 2017-10-02 13:00:00 | 2017-10-02 18:00:00 |
| FULANO 3 | 2017-10-03 09:00:00 | 2017-10-03 12:00:00 | 2017-10-03 13:00:00 | 2017-10-03 18:00:00 |
| FULANO 3 | 2017-10-04 09:00:00 | 2017-10-04 12:00:00 | 2017-10-04 13:00:00 | 2017-10-04 18:00:00 |
| FULANO 3 | 2017-10-05 09:00:00 | 2017-10-05 12:00:00 | 2017-10-05 13:00:00 | 2017-10-05 18:00:00 |
| FULANO 3 | 2017-10-06 09:00:00 | 2017-10-06 12:00:00 | 2017-10-06 13:00:00 | 2017-10-06 18:00:00 |
+----------+---------------------+---------------------+---------------------+---------------------+

Answer: Tente usar isso;
SELECT
 T0.NOME,
 T1.ENTRADA AS JORNADA_ENTRADA,
 T2.ENTRADA AS INTERVALO_ENTRADA,
 T2.SAIDA AS INTERVALO_SAIDA,
 T1.SAIDA AS JORNADA_SAIDA
FROM COLABORADOR AS T0
 INNER JOIN JORNADA AS T1
 ON T1.COLABORADOR_ID = T0.ID
 INNER JOIN INTERVALO AS T2
 ON T2.COLABORADOR_ID = T0.ID;

Comment: Eu acabei adicionando uma coluna da tabela JORNADA pois do modo como estava eu não teria referência entre elas. Não sei se por conta disso teu select não trouxe como o exemplo. Mas foi válido pois estava com duvida em por dois JOINs e com base no seu exemplo ajudou a entender. Obrigado de qq forma
Answer: Adicionei uma coluna na tabela JORNADA colocando ela como chave estrangeira para o id da tabela INTERVALO.
mysql> SELECT * FROM JORNADA;
+----+---------------------+---------------------+----------------+--------------+
| ID | ENTRADA             | SAIDA               | COLABORADOR_ID | INTERVALO_ID |
+----+---------------------+---------------------+----------------+--------------+
|  3 | 2017-10-02 10:00:00 | 2017-10-02 19:00:00 |              2 |           11 |
|  4 | 2017-10-03 10:00:00 | 2017-10-03 19:00:00 |              2 |           12 |
|  5 | 2017-10-04 10:00:00 | 2017-10-04 19:00:00 |              2 |           13 |
|  6 | 2017-10-05 10:00:00 | 2017-10-05 19:00:00 |              2 |           14 |
|  7 | 2017-10-06 10:00:00 | 2017-10-06 19:00:00 |              2 |           15 |
|  8 | 2017-10-02 09:00:00 | 2017-10-02 18:00:00 |              3 |           16 |
|  9 | 2017-10-03 09:00:00 | 2017-10-03 18:00:00 |              3 |           17 |
| 10 | 2017-10-04 09:00:00 | 2017-10-04 18:00:00 |              3 |           18 |
| 11 | 2017-10-05 09:00:00 | 2017-10-05 18:00:00 |              3 |           19 |
| 12 | 2017-10-06 09:00:00 | 2017-10-06 18:00:00 |              3 |           20 |
+----+---------------------+---------------------+----------------+--------------+
10 rows in set (0.00 sec)

Depois no select adicionei os dois JOINs seguindo o exemplo do amigo Anderson.
mysql> SELECT
    -> T2.NOME, T0.ENTRADA, T1.ENTRADA, T1.SAIDA, T0.SAIDA
    -> FROM JORNADA AS T0
    -> INNER JOIN INTERVALO AS T1
    -> ON T0.INTERVALO_ID = T1.ID
    -> INNER JOIN COLABORADOR AS T2
    -> ON T0.COLABORADOR_ID = T2.ID;
+----------+---------------------+---------------------+---------------------+---------------------+
| NOME     | ENTRADA             | ENTRADA             | SAIDA               | SAIDA               |
+----------+---------------------+---------------------+---------------------+---------------------+
| FULANO 2 | 2017-10-02 10:00:00 | 2017-10-02 12:00:00 | 2017-10-02 13:00:00 | 2017-10-02 19:00:00 |
| FULANO 2 | 2017-10-03 10:00:00 | 2017-10-03 12:00:00 | 2017-10-03 13:00:00 | 2017-10-03 19:00:00 |
| FULANO 2 | 2017-10-04 10:00:00 | 2017-10-04 12:00:00 | 2017-10-04 13:00:00 | 2017-10-04 19:00:00 |
| FULANO 2 | 2017-10-05 10:00:00 | 2017-10-05 12:00:00 | 2017-10-05 13:00:00 | 2017-10-05 19:00:00 |
| FULANO 2 | 2017-10-06 10:00:00 | 2017-10-06 12:00:00 | 2017-10-06 13:00:00 | 2017-10-06 19:00:00 |
| FULANO 3 | 2017-10-02 09:00:00 | 2017-10-02 12:00:00 | 2017-10-02 13:00:00 | 2017-10-02 18:00:00 |
| FULANO 3 | 2017-10-03 09:00:00 | 2017-10-03 12:00:00 | 2017-10-03 13:00:00 | 2017-10-03 18:00:00 |
| FULANO 3 | 2017-10-04 09:00:00 | 2017-10-04 12:00:00 | 2017-10-04 13:00:00 | 2017-10-04 18:00:00 |
| FULANO 3 | 2017-10-05 09:00:00 | 2017-10-05 12:00:00 | 2017-10-05 13:00:00 | 2017-10-05 18:00:00 |
| FULANO 3 | 2017-10-06 09:00:00 | 2017-10-06 12:00:00 | 2017-10-06 13:00:00 | 2017-10-06 18:00:00 |
+----------+---------------------+---------------------+---------------------+---------------------+
10 rows in set (0.00 sec)

e deu certo ;)


Can I put nylon strings on a guitar designed for steel strings?

Question:
This is the guitar. It has no pins on the bridge. Does that mean it will work if I put nylon strings on it instead of steel strings?
Comment: @Aq145 You should rewrite the question to be more specific, as questions about specific equipment recommendations are not within this stack exchange as noted by Todd Wilcox. Just to put you at ease, [these](https://www.cordobaguitars.com/guitars/s/eyJwYWdlIjowLCJwZXJfcGFnZSI6MCwib3JkZXJieSI6IiIsIm9yZGVyIjoiIiwibGFiZWwiOltdLCJmYW1pbHkiOltdLCJzdHlsZSI6WzMxXSwiY29uc3RydWN0aW9uIjpbXSwiaGFzLWVsZWN0cm9uaWNzIjpbXSwic2l6ZXMiOltdLCJzZXJpZXMiOlsyMDFdfQ==) are generally okay for beginners.
Answer: Guitars that are made to use steel core strings (bronze or nickel wound) are made differently than guitars made for nylon (or gut) strings. The steel string guitars have a different and stiffer bracing made to hold the higher tension of the steel strings.
If you try to put nylon strings on a steel string guitar, your action will likely be too low and the strings will not play well. The nut slots of your guitar will also not match the gauges of the nylon strings and you may have an issue with the thick high nylon strings not sitting in the slots for thin steel strings.
If you want a softer playing action closer to nylon strings, there are a few manufacturers that make a "nylon like" string made for steel string guitars. One example is the "Silk and Steel" set from D'Addario, which has a softer feel and a warmer sound than standard steel sets.
If you do want to try the nylon strings, you can tie a barrel knot or other thick knot in the end of the strings in the place of the ball.
Because of the construction of the guitar for higher tension steel strings, your tone and volume will be lesser with the nylon strings if you do get the action and nut gauge difference sorted out.
Answer: You need to do knots. My personal preference is two knots on the lower strings and three on the higher strings

Besides that, are you really trying to put nylon strings on a steel stringed guitar? Different instruments are designed for different neck tension, and you might even damage your guitar.
Comment: I am not sure if that's your own instrument, but as a matter of instrument health I would not tuck the string ends under each other (e string under a string, etc.) This makes destringing take longer, and also means that you have to remove all of the tension on the neck.
Comment: That's assuming it has an adjustable truss-rod, otherwise the neck will pull the strings flat to the fingerboard in a week :/
Comment: @AndreMesquita it releases all of the tension on the neck which means that it will take much longer for the strings to "normalize" and hold tune. You would also only want to remove one string at a time on a violin/cello/viola, but that is because their sound post or possibly their bridge  would collapse
Answer: You probably wont seriously damage the guitar and you probably wont be happy either, that's why folks don't do it very often.


KNN value of K based on labels

Question: I have two questions regarding KNN.
Q1. If training data have 7 classes should I consider higher K (for example I start with k=14?).
Q2. Since half of my training data is not labeled I will be using self training.
Self training Algorithm works as follows:
<code>•Let L be the set of labeled data, U be the set of unlabeled data.

•Repeat

– Train a classifier h with training data L

 – Classify data in U with h

 – Find a subset U' of U with the most confident scores.

 – L + U' -> L

 – U – U' -> U
</code>
What is considered confident scores here? For each training data, is it the percent of the chosen class's occurrence compared to to other classes in the k neighbor of that training data?
Answer:
Q1. If training data have 7 classes should I consider higher K (for
  example I start with k=14?).

The parameter $k$ in nearest neighbours is usually picked via $n
$-fold cross-validation. See this question for further details.

Q2. Since half of my training data is not labeled I will be using self
  training, what is considered a confident scores here?

Although kNN predicts the label for a new datapoint $x$ by simple majority vote, as outlined here the majority vote also approximates the probability for each posterior label $l$ as given by
$$
P(l \mid x) = \frac{\text{number of k-nearest neighbour labelled } l }{k}.
$$
You can use this as your confidence score.

KNN value of K based on labels


Make sense of norm notations and why is $\int_\Omega \nabla\theta\cdot\nabla\theta_t \ d\mathbf{x} = \frac{1}{2}\frac{d}{dt}|\theta|_1^2$?

Question: I have the heat equation
\begin{align}
\dot{u}(x,t) -\Delta u(x,t) = f(x,t),& \quad x\in\Omega\subset\mathbb{R}^2 \\
u(x,t) = 0, & \quad x\in\Gamma = \partial\Omega, 0<t\leq T \\
u(x,0) = u_0(x),& \quad x\in\Omega
\end{align}
In my book there is a proof about a stability estimate. In one of the lines they state that
$$a(u,u_t)=\int_\Omega \nabla u\cdot\nabla u_t \ d\mathbf{x} = \frac{1}{2}\frac{d}{dt}|u|_1^2.$$
How does the last equality follow? Need help getting through the arithmetic there.
What does the sub-index $1$ mean in the absolute value?

EDIT: Adding an attempt.
Attempt:
$$\int_\Omega \nabla\theta\cdot\nabla\theta_t \ dx =  \int_\Omega\nabla\theta\cdot \nabla\left(\frac{d}{dt}\theta\right) \ dx$$
$$=\int_\Omega \nabla\theta\cdot\frac{d}{dt}\nabla\theta \ dx =\frac{1}{2}\frac{d}{dt}\int_\Omega(\nabla\theta)^2 \ dx =\frac{1}{2}\frac{d}{dt}||\nabla\theta||^2.$$
But why does the book have $\frac{1}{2}\frac{d}{dt}|\theta|_1^2$ instead?
Comment: Which book is this from?
Answer: Hint: Try proving the following using just the properties of the scalar product, Cauchy-Schwartz and the definition of the derivative

Lemma. Let $(\mathscr{H}, \langle \cdot, \cdot \rangle, \| \cdot \|)$ be a Hilbert space. Then $$\langle u'(x), u(x) \rangle = \frac{1}{2} \| u(x) \|^2$$ holds for all continuously differentiable $u$ with values in $\mathscr{H}$.

Proof

 Let $\tau_h u := u(t + h)$. Then \begin{align} | \tau_h u |^2 - | u |^2 & = \langle \tau_h u - u, \tau_h u \rangle - \langle u, u - \tau_h u \rangle \\ & = \langle \tau_h u - u, \tau_h u \rangle + \langle \tau_h u - u, u \rangle. \end{align} holds. On one hand $$ \left| \langle u', u \rangle - \frac{\langle \tau_h u - u, u \rangle}{h} \right| = \left| \langle u' - \frac{\tau_h u - u}{h}, u \rangle \right|  \le \left| u' - \frac{\tau_h u - u}{h} \right| \left| u \right| \xrightarrow{h \to 0} 0 $$ and therefore $$ \frac{\langle \tau_h u - u, u \rangle}{h} \xrightarrow{h \to 0} \langle u', u \rangle.$$ On the other hand\begin{align*} \left| \langle u', u \rangle - \frac{\langle \tau_h u - u, \tau_h u \rangle}{h} \right| & \le \left| \langle u', u - \tau_h u \rangle \right| + \left| \langle u' - \frac{\langle \tau_h u - u \rangle}{h}, \tau_h u \rangle \right| \\ & \le | u' | | u - \tau_h u | + \left| u' - \frac{\tau_h u - u}{h} \right| \left| \tau_h u \right|  \xrightarrow{h \to 0} 0 \end{align*} and therefore $$ \frac{\langle \tau_h u - u, \tau_h u \rangle}{h} \xrightarrow{h \to 0} \langle u', u \rangle. $$

Edit This question is highly related and may answer your question.
Comment: I had this in mind:

$$\langle u',u \rangle = \int_I u'u \ dx = \int_I(\frac{d}{dx}u)u \ dx = \int_I\frac{1}{2}\frac{d}{dx}u^2 \ dx = \frac{1}{2}||u||^2.$$
Comment: @Parseval This is indeed the easiest solution when given the concrete Hilbert space, $L^2$. The general case is not that simple as I show in the proof. Feel free to post this as an answer.
Comment: Why would it be an answer? My question is totally different. There I'm dealing with gradients since I'm in 2D. Also, I need to have $d/dt$ before $||u||^2$. In your example you give $\langle u',u\rangle$ but I need $\langle \nabla u, \nabla v \rangle$ where $v=\frac{d}{dt}u.$ Maybe I'm missing the point you tried to convey.
Comment: I thought my lemma could easily be modified to be come your statement. I'll have another look at it later.
Comment: Thanks a lot. I'll think throught this meanwhile and se how I can modify it.
Comment: I added a possible attempt. Still not the exact same answer as in the book though.


Multiple Different AJAX Enabled Forms on the Same Page

Question: I currently have a form that is being loaded by AJAX and is working perfectly. I now need to add a second form (Add Single Stat) to the same page via AJAX as well. The Add Single Stat form is being loaded to the page perfectly but when the AJAX callback is fired for the db_selection select list, I get "An AJAX HTTP error occurred. HTTP Result Code: 200" AJAX error. I'm really not sure where this error being caused from and would like to find a fix to this issue.
The Add Single Stat Form is being built with the following code:
public function buildForm(array $form, FormStateInterface $form_state) {

   $form['db_selection'] = array(
    '#title' => t('Data Location'),
    '#title_display' => 'invisible',
    '#type' => 'select',
    '#options' => array("" => "Select", "enrollmentdata" => "Student Enrollment Data", "summerenrollmentdata" => "Summer Enrollment Data"),
    '#prefix' => '
',
    '#suffix' => '
',
    '#ajax' => array(
        'callback' => 'Drupal\dashboard\Controller\DashboardController::SingleStatOnDBSelection',
        'effect' => 'fade',
        'event' => 'change',
        'progress' => array(
            'type' => NULL,
            'message' => NULL,
            ),
        ),
   );
   $form['term_selection'] = array(
    '#title' => t('Select Term'),
    '#title_display' => 'invisible',
    '#type' => 'select',
    '#prefix' => '
',
    '#suffix' => '
'
   );
   $form['ss_id'] = array(
    '#title' => t('Single Stat ID'),
    '#type' => 'hidden',
    '#prefix' => '
',
    '#suffix' => '
',

   );
   return $form;
}

I am then loading The Add Single Stat Form to the page via this ajax callback:
public static function AddSingleStatToPanel(array &$form, FormStateInterface $form_state){
    $ajax_response = new AjaxResponse();

    //Generate a Unique ID for the single stat
    $SingleStatID = self::GenerateRandomID(15, 'single_stat_info', 'single_stat_id');

    //Add The "Add Single Stat" To the correct DIV
    $AddSingleStat = \Drupal::formBuilder()->getForm('Drupal\dashboard\Form\AddSingleStat');
    self::SetUniqueAddSingleStatFormDivIDs($AddSingleStat, $SingleStatID, TRUE);
    $ajax_response->addCommand(new AppendCommand('#AddSingleStatForm_'.$SingleStatID, $AddSingleStat));

    return $ajax_response;
}

I handle updating the form to contain unique element id values as well as unique ids for the divs surrounding the form elements in this function:
private function SetUniqueAddSingleStatFormDivIDs(&$FormRenderArray, $SingleStatID, $HideFields = TRUE){
    $FormFields = array('term_selection', 'ss_id');

    $FormRenderArray['db_selection']['#prefix'] = '
';

    foreach($FormFields as $FormField){
        //Set Each DIV's ID to the Form Field ID_SingleStatID
        if($HideFields || $FormField == 'chart_type'){
            $FormRenderArray[$FormField]['#prefix'] = '
';
        } else {
            $FormRenderArray[$FormField]['#prefix'] = '
';
        }
    }

    $FormRenderArray['ss_id']['#value'] = $SingleStatID;
    $FormRenderArray['#attributes'] = array('id' => array('ss_'.$SingleStatID));

}

Inside of the dashboard controller I have the AJAX callback that I would like to be called when the user changes an option in the db_selection select list.I have reduced the code here to just a simple JS alert.
public static function SingleStatOnDBSelection(array &$form, FormStateInterface $form_state){

    $ajax_response = new AjaxResponse();

    $ajax_response->addCommand(new AlertCommand('It Works!'));

    return $ajax_response;
}

Update: I have done a little more debugging and the only way I can make this form work correctly is if I pass the form's render array to twig file and load it that way. The form doesn't seem work at when using AJAX to loads the form's HTML.
Answer: I believe your problem is here:
$SingleStatID = self::GenerateRandomID(15, 'single_stat_info', 'single_stat_id');

//Add The "Add Single Stat" To the correct DIV
$AddSingleStat = \Drupal::formBuilder()->getForm('Drupal\dashboard\Form\AddSingleStat');
self::SetUniqueAddSingleStatFormDivIDs($AddSingleStat, $SingleStatID, TRUE);

You are altering the form in SetUniqueAddSingleStatFormDivIDs(), after it has already been generated by the formbuilder. You cannot alter forms in Drupal after they have been generated. If you want to make alterations to the form, it needs to happen in hook_form_alter() or one of its variants.
Comment: Interesting. I have been using this system on the other form being load on this page without any problems. I will take a look at using the form_alter and see if that has any affect on the errors I'm getting.
Comment: I went ahead removed the SetUnique function and I'm still having the same issue as before. I'm only adding this form once on the page (currently) so there shouldn't be any need to set unique ids.


When does Service Fabric update the list of available service partition endpoints?

Question: I am working on a service (let's call it ServiceA) that exposes an endpoint.  The service will be hosted in Service Fabric and will run on (for example) three of five available nodes.  Another service (ServiceB) needs to be able to contact all three running instances of ServiceA.  In order to do that, I am using the ServicePartitionResolver from ServiceB to find all of the endpoints exposed by the (single) ServiceA service partition.  This works just fine until I kill one of the nodes on which ServiceA is running.  I would expect that another instance of ServiceA is created on one of the other nodes and the list of endpoints returned by ServicePartitionResolver.Resolve is updated to reflect the change.  This doesn't seem to happen, though.  In fact even if I query the REST API directly (using Postman to hit: http://[cluster-ip]:19080/Services/ApplicationA~ServiceA/$/ResolvePartition?api-version=6.0) I continue to see a 'stale' result.  I have also tried using FabricClient rather than ServicePartitionResolver to check that it's not a locally cached result that I am seeing.
Have I missed something obvious?
Answer: Having done a bit more experimentation, I think I know what is going on.  Service Fabric does do what I expected it to but in my case the cluster I am using for testing is not big enough.  I think that when I remove one of three nodes, the naming service can't operate effectively any more and so the results are not consistent.  If I use a four node cluster and remove one, I get the result I am expecting.


Array of dict to dict

Question: I have arrays
first = [{'x': 'name1', 'a': '333'}, {'x': 'name2', 'a': '234'}, {'x': 'name3', 'a': '432'}, {'x': 'name4', 'a': '943'}, {'x': 'name5', 'a': '643'}]
second = [{'x': 'name1', 'b': '1333'}, {'x': 'name2', 'b': '1234'}, {'x': 'name3', 'b': '1432'}, {'x': 'name4', 'b': '1943'}]

What function can i use to get this result:
[{'x': 'name1', 'b': '1333', 'a': '333'}, {'x': 'name2', 'b': '1234', 'a': '234'}, {'x': 'name3', 'b': '1432', 'a': '432'}, {'x': 'name4', 'b': '1943', 'a': '943'}, {'x': 'name5', 'b': None, 'a': '643'}]

Comment: u re right, selected answer in not correct
Comment: Are list items matched positionally, or on the value of the dictionary key `x`? Have you tried something yet yourself that we might use as a stepping stone?
Comment: @JonSG on the value of the dictionary key x
Comment: Does this answer your question? [join two lists of dictionaries on a single key](https://stackoverflow.com/questions/5501810/join-two-lists-of-dictionaries-on-a-single-key)
Answer: You can simply combine the dictionaries using | like so:
result = [f | s for f, s in zip(first, second)]

Based on your edited question, matching on x:
from collections import defaultdict
from functools import partial
from itertools import chain
# Each dict starts with defaults a, b == None
merged = defaultdict(partial(dict.fromkeys, ("a", "b")))

# Merge all dictionaries
for dict_ in chain(first, second):
    merged[dict_["x"]].update(dict_)

# Get the merged dicts
result = list(merged.values())

Comment: @groutch according to updated question, fixed.
Comment: @Bharel Looks good to me now :-)
Comment: In Python 3.9.0 or greater (released 17 October 2020, PEP-584) you can do the union of dicts using: `z = x | y`
Comment: @Kins yup, that is correct :-)
Comment: thanks a lot! one more question, if in the first array i will have name5, but the second one doesn't contain that value, how can i add null there
Comment: @JonSG according to specs.

Array of dict to dict


When implementing threads, is it better to use immutable objects over mutable ones?

Question: I'm currently learning about threads in java, and from what I've read, implementing them isn't the problem so much as making your code thread safe. Which brings me to my question: should I be using immutable objects whenever possible to ensure that I prevent concurrency bugs?
I've read differing opinions about when to use mutable objects, including:

If immutable objects are good, why do people keep creating mutable objects? (Programmers.SE)
for large and/or complex objects, creating a new copy of the object for every single change can be very costly and/or tedious. And for objects with a distinct identity, changing an existing objects is much more simple and intuitive than creating a new, modified copy of it.

Immutable Objects (Java Tutorials)
The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects. These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption.

So, is there a best practice when implementing threads? Should I always try to use immutable objects when possible?
Comment: Unfortunately, this question is mostly opinion based and certainly a judgement call depending on the specifics of your application.  There are times you want to use immutable objects and other times this is not possible.
Comment: Yes, but thread-safety will still be hard.  See my blog, http://blog.slaks.net/2013-07-22/thread-safe-data-structures/
Comment: Do you trust yourself?  Who else will be monkeying in the code?
Answer: Using truly immutable objects (no fields that contain references to mutable classes) is thread-safe, and it's a good habit to employ them when it's practical, but whether immutability is feasible depends on the specifics of the situation; some toolkits, for example, require setter or field injection and thus can't be used with immutable objects. Immutability is typically the most practical with the Value Object pattern, where the object doesn't have any especially complex behavior and basically encapsulates a clearly-describable value (String, the primitive wrappers, Guava's Immutable* collections).
Generally, I try to make objects with simple fields immutable whenever practical, and I find it helpful to start from the default that immutable objects are safest and only use mutators if there's a particular reason why they're needed.
Similarly, if you're going to rely on the immutability of a class for something like thread safety, you should usually declare the class final to avoid all manner of headaches. I don't go so far as to insist that all classes must be either abstract or final, but final instantiable classes are a good default.
Answer: Yes, immutable objects are often your friend when multi-threading.
There are a few big pluses:

Threadsafe.  If you can't change it's state, then there's no way that two threads can update it at the same time or see separate versions of it.
No locking.  Because nothing changes, there's no need to use the synchronized keyword.  This gives you performance bonuses and simplicity.
Can be singleton.  Since the object is thread-safe, there's no need to give separate threads their own version of it.  You can pass it around to several threads knowing that the state won't change, preventing you from having to possibly spend more memory creating copies.
Answer: I think it really depends on the context where you will be using them.  Is it an object that will be accessed in multiple threads constantly?  What are the hardware constraints on the system?
It's not so much about whether the objects are immutable or mutable, it's more about how they will be accessed.  Even an immutable object can cause thread safety issues if it's being copied at the same time that the copy is being accessed...
You should probably look into ACID:
http://en.wikipedia.org/wiki/ACID
Also Java has solid and easy to implement methods for synchronizing code so that mutable objects can be accessed safely from multiple threads.  For a system that needs to be highly performant in terms of memory consumption this is likely the way to go.  But again it's a trade off based on your constraints - what's more important memory or speed?
Answer: The problem with threaded access to an object is always one of changing the object safely; reading an object's state is inherently safe if you can guarantee that the state is not being changed at the same time.  (Obviously my answer assumes you are changing objects in threaded code.)
Immutable objects simply mask this complexity - I now have to guarantee that the object I hold a reference to is not stale. In addition, I now have to determine where the most current version of that object is if the version I have is indeed stale.


How to change timeout in Pyserial?

Question: How to change timeout in Pyserial after initialize serial?
Like:
ser=serial.Serial("COM4", baudrate=19200,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS,timeout=0.5)
After that, I want to change timeout.
Any examples?
Thanks
B.R.
Answer: Looking at the docs (https://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.timeout) it seems as though you should simply have to set the attribute on the object:
ser.timeout = 1.0

How to change timeout in Pyserial?


How to save a specific name of generated xls file

Question: I use this vb.net tutorial provided my Microsoft to create a xls file:
All is working good, but I want to save the file with a specific name instead of Cartel1.xls, is it possible?
Answer: You could add this code to the example.
<code>    Dim file = oXL.GetSaveAsFilename()
    If file IsNot Nothing _
       AndAlso file.ToString().Length > 0 _
       AndAlso file.ToString() <> "False" Then
        oWB.SaveAs(file)
    End If
</code>
This code opens the Save As dialog of Excel, if you press Cancel then you get as result a boolean object with value FALSE. Instead if you type a file name you get, as result the full filename typed (path included). This file could be passed to the Worksheet method SaveAs to complete the save.
Using the code in the example I have added it at the end of the button_click method before the dispose of the Excel Application and the Excel Worksheet, but, of course you could call it wherever makes sense for you.


What does $\mathbb Q[\sqrt 2][x]$ mean?

Question: What does $\mathbb Q[\sqrt 2][x]$ mean?
I know this has something to do with split fields, but what does this notation mean?
Answer: It means the ring of polynomials with coeffiencients in $\mathbb Q[\sqrt{2}]$.
Comment: Yeah, not good to call those "polynomials," just to avoid the error of confusing polynomials with polynomial functions. You could rephrase your comment, however, as $\mathbb Q[x,y]/\left$ . @Arthur
Comment: Alternatively, the ring of polynomials in the two variables $\sqrt 2$ and $x$, remembering that $(\sqrt 2)^2 = 2$, and coefficients in $\Bbb Q$.

What does $\mathbb Q[\sqrt 2][x]$ mean?


Bootstrap 4 form not sending contents of select box

Question: I've written a simple bootstrap 4 form with a GET method, and it only sends the values in the Submit button, not in the  tag above it.
This is eventually to be handled in a POST request, but I've changed it to GET to more easily see what data the form is sending.
Here is the form code:
<form action="/picknumbers" method="GET">

        Select one or more numbers
        <select multiple class="form-control mb-3" id="numberselect" size="6">
            <option>1</option>
            <option selected>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
            <option>6</option>
        </select>

<button name="submission" value="numberspicked" type="submit" class="btn btn-primary btn-block">Choose numbers</button>
</form>

The output in the browser address bar is simply: /picknumbers?submission=numberspicked, without including the numbers picked by the user. How do I get the submitted form to include them?
Comment: Doesn't your select element need a name attribute?
Answer: Your select options appear to be missing value attribute tags. It should look like the below:

        Select one or more numbers
        <select multiple class="form-control mb-3" id="numberselect" size="6">
            <option value="1">1</option>
            <option value="2" selected>2</option>
           ...
        </select>

<button name="submission" value="numberspicked" type="submit" class="btn btn-primary btn-block">Choose numbers</button>
</form>

Answer: You need to give a value on the options also you need to give a name to the select.  To clarify, see the code below:
 <select multiple class="form-control mb-3" name="select-name" id="numberselect" size="6">
        <option value="1">1</option>
        <option value="2" selected>2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
    </select>


Generating sorted pseudo-random numbers in Stata

Question: Today I opened two STATA windows and ran the following command in both:
set obs 100
gen x = rnormal()
sort x

(the difference is that on the second window I generated a variable called y).  Summing up: I asked STATA to give me 100 pseudo-random numbers taken from a standard normal distribution, then I sorted it.  To my surprise, the numbers of the x and y vectors are the same!  I did this at home, and then at work, and my impression is that all of these vectors are the same.  Is there an explanation for this, to me, strange behavior?
If this is a problem in STATA, does R have a better pseudo-random number generator procedure?
A side question.  I came up to this "problem" because I was trying to generate two pseudo-random columns in Stata (x and y, say), and then sort then separately.  But the two commands I know for sorting (sort and gsort) sort the whole database, not separate columns.  Would you know of a Stata command that allows me to sort a column while keeping the other columns fixed?
Comment: Just to add that I tried the same thing in R and got the same behavior.  Namely, I opened two R windows, ran the command
x <- rnorm(50)
and got the same vector of 50 random numbers in both windows.
Comment: According to the manual for version 8, Stata uses the "KISS" generator by G. Marsaglia of period approximately 2^126.  The only reason to need something better is for cryptographic applications.
Answer: The help for set_seed states

The sequences these functions produce are determined by the seed, which is just a number and which is set to 123456789 every time Stata is launched.

Stata's philosophy emphasizes reproducibility, so this consistency is not surprising.  Of course you can set the seed yourself.  See the help page for more information.
One way to sort a column separately from all others is to preserve your data, keep only the column to sort, sort it, save the results in a temporary file, restore your data, and merge the temporary file:
gen y = rnormal()
preserve
keep y
sort y
tempfile out
save `out'
restore
merge 1:1 _n using `out', nogen

Comment: If you actually want the random numbers to change every time you start Stata: one idea would be to base you "seed" on your clock using your profile.do file. Try ``set seed `=clock("$S_DATE $S_TIME","DMYhms" )-162e10'``
Comment: Thanks Whuber - I read about the seed - I still have to digest the idea of how Stata treats randomness, but at least I now know that they are doing something right which is worth my time to understand.  About the second part, I thought about the same approach (doing a merge), but it was great to see your code, as mine wouldn´t be so good!  Cheers, and thanks a lot again.


PHP comments news only one news

Question: Please link me any tutorial or simply inform me how to do so that it showed comments only on news which had recently been added. How I select only one?
<?php
                echo "<form action='".setComments($conn)."' method='post'>
                    <input type='hidden' name='username'>

                    <input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>

                    Comment:
 <textarea cols='50' rows='6' name='message' ></textarea>

                    <button type='submit' name='commentSubmit' class='btn btn-default'>Comment</button>
                    </form>";
                getComments($conn);
                ?>

                    <?php
                    $query = "SELECT * FROM comment order by date desc";
                    mysqli_query($conn,$query) or die("Error queryng db");
                    $result = mysqli_query($conn,$query);
                    while ($row = mysqli_fetch_array($result)){
                        $name = $row['name'];
                        $com = $row['comment'];
                        $date = $row['date'];
                        echo "

სახელი: $name ; თარიღი: $date

კომენტარი:
 $com

                            ";
                    }
                    ?>

in comments.php :
<?php
function setComments($conn) {
    if (isset($_POST['commentSubmit'])) {
        $uid = $_POST['username'];
        $date = $_POST['date'];
        $message = $_POST['message'];

        $sql = "INSERT INTO comments (username,date,message) VALUES ('$uid','$date', '$message')";
        $result = mysqli_query($conn,$sql);
    }
}

function getComments ($conn) {
    $sql = "SELECT * FROM comments";
    $result = mysqli_query($conn,$sql);
    while ($row = mysqli_fetch_array($result)) {
        echo $row['username']."
";
        echo $row['date']."
";
        echo $row['message']."

";
    };
    echo "
        <form method='post' action'editcomment.php'>
            <input type='hidden' name='id' value='".$row['id']."'>
            <input type='hidden' name='username' value='".$row['username']."'>
            <input type='hidden' name='date' value='".$row['date']."'>
            <input type='hidden' name='message' value='".$row['message']."'>
            <button>შესწორება</button>
    ";

}

I want to show only news posted comment an I have to all news comments other news.
Comment: you want to get only last comment entered after submit button is pressed right??
Comment: no, i want to where i added something news and someone make comment show only this news comment not all other comment. sorry for my bad english
Comment: Note, you are vulnerable to SQL Injections right now. You need to start using prepared statements
Answer: You need to use LIMIT and ORDER BY tags in your query, so it would look something like this:
$sql = "SELECT * FROM comments ORDER BY id DESC LIMIT 1";

This query has two new parameters, we need to order it by ID so we can get the descending (that's what DESC is used for) and we limit the number to 1; if you need more you can change the number.
If you have a specific item you want to pull you can use WHERE clause in your query: WHERE id = #call for id#

To make sure the comment only comes up in the article you need to create some sort of identifier row for your comments and compare it in your posts:
// get the post ID from the database
$post_id = $row['id'];

// now that you have the post id, and assuming you have an identifier add the WHERE clause
$sql = "SELECT * FROM comments WHERE comment_post_id = " . $post_id;

To add the comment_post_id add that when they enter the comment, from the the current post they are in.
So if you are post id is 12, the comments made in the that post should have their comment_post_id equals to 12.
Comment: try evrything but dont work :S my mistake. if you are not buys an have time can you show me ?
Comment: maybe i have wrong in mysql relationships dont have and its necessary?
Comment: What are you asking? I am sorry I don't understand
Comment: i think i have a mistake in mysql, there's no relationship between news id and comments id and is it needed ? To be more certain, when i add one article e.g. and somebody leaves a comment, i want that comment to stick to that article only and does not apply to other articles.
Comment: @levanrostoshvili I updated my answer, hope it helps
Comment: The `comment_post_id` is the relationship; that's how you determine to pull the comment or not. `if (comment_post_id == post_id) { show comment }`
Comment: @levanrostoshvili does that make sense, mate?
Comment: @levanrostoshvili let me know how I can help, where are you having an issue?
Comment: where i can upload ?
Comment: full projet it is just for me and i have not proble for see you
Comment: What do you mean?
Comment: I'll look though the project and let you know man... We should move to the chat, shouldn't really be having a conversation in the comments
Comment: i  dont know this site rules sorry
Comment: can  you help me ?
Comment: Meet me in the chat @levanrostoshvili
Comment: where? i can chat with you?
Comment: Actually; explain to me what the problem you are having here... I don't know if you would have access to the chat yet. Try to explain exactly where the problem is.
Comment: When I add some news and somebody writes a comment, I want that comment to appear only on that certain news not on other news as well
Comment: I am looking through your code right now, which file is the one where the user will see the post and comment? I am having a bit of trouble since the file is in a different language
Comment: check fullstory section this is where i have code for comments
Comment: hello. did you se?
Answer: Your select query is missing where clause. It should look like.
$sql ="select  * from comments where news_id='".$news_id."';

Comment: maybe i have wrong in mysql relationships dont have and its necessary?
Comment: Yes. If you want to get comments of that particular news only than your comments table must have news_id field.

PHP comments news only one news


Do we need a global test before post hoc tests?

Question: I often hear that post hoc tests after an ANOVA can only be used if the ANOVA itself was significant.

However, post hoc tests adjust $p$-values to keep the global type I error rate at 5%, don't they?
So why do we need the global test first?
If we don't need a global test is the terminology "post hoc" correct?
Or are there multiple kinds of post hoc tests, some assuming a significant global test result and others without that assumption?
Answer: Since multiple comparison tests are often called 'post tests', you'd think they logically follow the one-way ANOVA. In fact, this isn't so.

"An unfortunate common practice is to pursue multiple comparisons only when the hull hypothesis of homogeneity is rejected." (Hsu, page 177)

Will the results of post tests be valid if the overall P value for the ANOVA is greater than 0.05?
Surprisingly, the answer is yes. With one exception, post tests are valid even if the overall ANOVA did not find a significant difference among means.
The exception is the first multiple comparison test invented, the protected Fisher Least Significant Difference (LSD) test. The first step of the protected LSD test is to check if the overall ANOVA rejects the null hypothesis of identical means. If it doesn't, individual comparisons should not be made.  But this protected LSD test is outmoded, and no longer recommended.
Is it possible to get a 'significant' result from a multiple comparisons test even when the overall ANOVA was not significant?
Yes it is possible. The exception is Scheffe's test. It is intertwined with the overall F test. If the overall ANOVA has a P value greater than 0.05, then the Scheffe's test won't find any significant post tests. In this case, performing post tests following an overall nonsignificant ANOVA is a waste of time but won't lead to invalid conclusions. But other multiple comparison tests can find significant differences (sometimes) even when the overall ANOVA showed no significant differences among groups.
How can I understand the apparent contradiction between an ANOVA saying, in effect, that all group means are identical and a post test finding differences?
The overall one-way ANOVA tests the null hypothesis that all the treatment groups have identical mean values, so any difference you happened to observe is due to random sampling. Each post test tests the null hypothesis that two particular groups have identical means.
The post tests are more focused, so have power to find differences between groups even when the overall ANOVA reports that the differences among the means are not statistically significant.
Are the results of the overall ANOVA useful at all?
ANOVA tests the overall null hypothesis that all the data come from groups that have identical means. If that is your experimental question -- does the data provide convincing evidence that the means are not all identical -- then ANOVA is exactly what you want. More often, your experimental questions are more focused and answered by multiple comparison tests (post tests). In these cases, you can safely ignore the overall ANOVA results and jump right to the post test results.
Note that the multiple comparison calculations all use the mean-square result from the ANOVA table. So even if you don't care about the value of F or the P value, the post tests still require that the ANOVA table be computed.
Comment: Excellent answer and I'll add some quotes from Maxwell and Delaney (2004): "...these methods [e.g., Bonferroni, Tukey, Dunnet, etc.] should be viewed as substitutes for the omnibus test because they control alphaEW at thee desired level all by themselves. Requiring a significant omnibus test before proceeding to perform any of these analyses, as is sometimes done, only serves to lower alphaEW below the desired level (Bernhardson, 1975) and hence inappropriately decreases power" (p. 236).
Comment: (+1) The final two paragraphs provide a good context for understanding and appreciating the entire answer.
Comment: While not in the question, I think I should mention - since it may not be obvious - that the reverse situation is also possible in some situations (that an omnibus test rejects but no pairwise comparisons do)
Comment: This is a great answer Harvey - thanks for writing it!
Comment: The lesson in the excellent answer here is to consider carefully what it is you're trying to find out, and then tailor your testing specifically to that end, rather than blindly go "ANOVA test, then test all possible comparisons".
Comment: I like "so have power to find differences between groups..."
Answer: (1) Post hoc tests might or might not achieve the nominal global Type I error rate, depending on (a) whether the analyst is adjusting for the number of tests and (b) to what extent the post-hoc tests are independent of one another.  Applying a global test first is pretty solid protection against the risk of (even inadvertently) uncovering spurious "significant" results from post-hoc data snooping.
(2) There is a problem of power. It is well known that a global ANOVA F test can detect a difference of means even in cases where no individual t-test of any of the pairs of means will yield a significant result.  In other words, in some cases the data can reveal that the true means likely differ but it cannot identify with sufficient confidence which pairs of means differ.
Comment: @amoba and @whuber: You probably know this, but I'd like to clarify it anyway. Note that it's possible for the ANOVA test to be significant even if none of the Tukey's HSD tests are. Simple R example with a balanced data set with three groups: `set.seed(249);
group = rep(1:3, each=2);
y = group + rnorm(6);
mod = aov(y~factor(group));
summary(mod);
TukeyHSD(mod);
plot(y~group)`
Comment: Well, couldn't you at least surmise that there was a difference between the two means with the largest difference between them, since the null hypothesis of the ANOVA is that at least one pair of means differs from each other?
Comment: @Bonferroni If you have a significant global p-value, you have evidence that there is an effect whatsoever. I think this legitimates further analysis. I think the suspect of data snooping is rather natural instead, in case of non-significance of an "omnibus" test. If  one person is interested in a specific association, considered as the primary goal of the analysis, then I think such association should be left out from such global test.
Comment: Re (2): when you say that a one-way ANOVA can report a significant difference when none of the pairwise t-tests does, do you refer to simple non-adjusted ("non post", e.g. not Tukey's procedure or anything) t-tests? I thought this would never be possible, was I wrong?
Comment: @amoeba That's right; I am referring to unadjusted pairwise tests.  Thank you for clarifying this point.
Comment: Thank you, @whuber. I tried to find a discussion of this point here on CrossValidated, but to no avail. So I posted my own question about how is such a situation possible: http://stats.stackexchange.com/questions/83030/how-can-anova-be-significant-when-none-of-the-pairwise-t-tests-is. I would be very grateful indeed if you could elaborate there!
Comment: @Speldosa interesting point, I would be curious about that too
Comment: @whuber Actually, you said "Applying a global test first is pretty solid protection against the risk of (even inadvertently) uncovering spurious 'significant' results from post-hoc data snooping." Given that you referred to applying the global test "first" to protect against Type I errors, it sure seems like you were implying that the global test protects the individual tests that follow (a common misconception). And given that you called the global test "pretty solid protection," that seems to suggest additional protection isn't necessary. Maybe you should clarify these points in your answer.
Comment: Whuber is incorrect that "Applying a global test first is pretty solid protection against the risk of (even inadvertently) uncovering spurious "significant" results from post-hoc data snooping." If there are many hypotheses and one null is false, the other tests aren't protected.
Comment: @Bonferroni This sounds like a fair warning, but the logic of your statement is elusive. If one null is false, then the concept of a *global* "false positive" doesn't even apply: we're into false negative territory at that point. It sounds like you might be concerned with the *individual* false positive rate (which is good) but are assuming that any *post-hoc* tests are not corrected for interdependence and multiple comparisons.  I did not mean to say--nor did I say--that you *only* need to perform a global test.


Who is the oldest player who was drafted in the NBA?

Question: I would like to know who the oldest player was that ever got drafted into the NBA?
Answer: Bernard James was 27 years of age when he was drafted as the 33rd overall pick in the 2012 NBA draft by the Cleveland Cavaliers(1). He is credited for being the "oldest collegian selected in the past 20 years" since Dikembe Mutombo(2).


Gostaria que um usuário cadastrasse um limite único de markers no mapa

Question: Bom dia pessoal, gostaria de saber, se tem como eu determinar um limite máximo de cadastros de markers há um usuário, dependendo do seu nível de acesso no banco de dados. Exemplo:
CREATE TABLE tb_users (
id_users int(11) NOT NULL AUTO_INCREMENT,
email varchar(50) NOT NULL,
usuario varchar(20) NOT NULL,
senha varchar(15) NOT NULL,
nome varchar(35) NOT NULL,
telefone varchar(15) NOT NULL,
status varchar(10) NOT NULL,
pagseguro varchar(20) DEFAULT NULL,
PRIMARY KEY (id_users)
)
Na tabela acima, caso o usuário estivesse com nível 2 de acesso na coluna pagseguro, ele poderia então cadastrar 4 markers no mapa.
Enfim, quero saber como eu coloco esse limite ao usuário??
Comment: Essa regra tem de ser tratada na aplicação e não no banco.
Answer: A princípio como seria um limite único de marcadores. a relação seria 1 para 1 para uma outra tabela com referencia a pague seguro; única dependência q notei para a indicação da quantidade, normalizando.

contudo, observe que é um varchar como chave primária; eu recomendaria uma outra tabla pague seguro, contendo id_pagseguro, um campo com descrição, e a quantidade de marcadores ...; Dessa forma referenciaria um integer.


Convert String to Date format, to insert it into MySQL

Question: Good afternoon,
I'm trying to get a String from a JTextField. Then convert it to Date for afterwards sending that into a MYSQL statement.
        String nom = jTextField_Name.getText().toUpperCase();
        int temp = Integer.parseInt(jTextField_Temp.getText());
        String d = jTextField_Date.getText();
        System.out.println("Inputs taken");

        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Date parsed = (Date) format.parse(d);
        java.sql.Date sql = new java.sql.Date(parsed.getTime());
        System.out.println("Converted to proper Date for MYSQL");

        int retorn = db.insertTemperatura(nom, sql, temp);
        if (retorn == 1){
            jTextArea_Result.setText("S'ha inserit "+nom+" amb la seva temperatura correctament!");
        } else{
            jTextArea_Result.setText("-----Hi ha hagut un ERROR a l'hora d'inserir "+nom+" amb la seva temperatura.\nIntenta-ho de nou sisplau.");
        }
        } catch (ParseException ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        }

The thing is, that i'm not doing the conversion right, i've tried diferent ways and I always came up with that error:
run:
Llegides entrades
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date

I've used other types of format but I don't know what I'm doing wrong.
Thanks in advance!
The method I call for that insertion into the DDBB is:
 public int insertTemperatura(String nom, Date data, int temperatura){
    try {
        Statement s = c.createStatement();
        String query = "INSERT INTO TaulaTemp VALUES ('"+nom+"',"+temperatura+","+data+")";

        int numRows = s.executeUpdate(query);
        if (numRows > 0){
            return 1;
        }
        return 0;
    } catch (SQLException ex) {
        Logger.getLogger(DDBB.class.getName()).log(Level.SEVERE, null, ex);
        return -1;
    }
}

Comment: You can't simply cast a ``java.util.Date`` to a ``java.sql.Date``...
Comment: Do not build your SQL like that, use a `PreparedStatement` with placeholders instead. Your code is wide open to SQL-Injection attacks.
Comment: You can pass directly a java.util.Date to mySQL... is not necesary Parse it to java.sql.Date
Comment: Possible duplicate of [How to convert java.util.Date to java.sql.Date?](http://stackoverflow.com/questions/530012/how-to-convert-java-util-date-to-java-sql-date)
Comment: You have not shown the important code, i.e. the definition of `insertTemperatura`.  Please [edit] you post and include that code.
Comment: As @JimGarrison said... use a `PreparedStatement`... I updated my answer so you can see it.
Comment: You are using the wrong Date class.
Answer: You can pass directly a java.util.Date to mySQL... is not necessary Cast it to java.sql.Date
Just delete this line:
java.sql.Date sql = new java.sql.Date(parsed.getTime());

and pass in this line the variable casted
int retorn = db.insertTemperatura(nom, parsed, temp);

UPDATE:
You should use a preparedStatement clause instead of put all your query in a String, like this:
String query = "INSERT INTO TaulaTemp VALUES (?,?,?)";

PreparedStatement preparedStatement = dbConnection.prepareStatement(query);
preparedStatement.setString(1, nom);
preparedStatement.setDate(2, data);
preparedStatement.setInt(3, temperatura);
// execute insert SQL stetement
preparedStatement .executeUpdate();

Remember to use PreparedStatement add the necesary import statement:
import java.sql.PreparedStatement;

Comment: Hello Dazak, thanks for the answer. I've just tried and it keeps me saying the same. Can it be an error from the input type I get from my method **insertTemperatura**?
I've just updated the question with it's code, maybe it's there where I should change it :S
Comment: As @JimGarrison said... use a PreparedStatement... I update my answer so you can see it
Comment: Now I've changed the code with the prepared statement but the error seems to be in the same part. As I've put system.out.prints, it seems that it's not passing the line:
     Date parsed = (Date) format.parse(d);


Show that $|\hat{f_n}| \leq \frac{C}{|n|}$ for all $n \in \mathbb{Z} \backslash \{0\}$ for a Lipschitz-continuous $f$

Question: I want to show that for a Lipshitz-continuous function $f$, there is some constant $C$ such that $|\hat{f_n}| \leq \frac{C}{|n|}$ for all $n \in \mathbb{Z} \backslash \{0\}$, where $\hat{f}_n$ is the n-th Fourier coefficient of $f$.
I tried to utilize a "typical" estimate of $\hat{f_n}$, i.e.
\begin{equation}
|\hat{f_n}| = |\frac{1}{2\pi} \int_0^{2\pi}f(x) e^{-inx}dx| \leq \frac{1}{2\pi} \int_0^{2\pi} |f(x) e^{-inx} dx| \leq ||f||
\end{equation}
so it doesn't seem to work. This result seems to be similar to the standard result that if $f \in C^k$, $\hat{f_n} \leq \frac{C}{|n|^k}$, which I know how to prove via integration by parts and Riemann-Lebesgue lemma, and I thought that we could do something similar here - however, I am not sure how to do it.
Comment: This is true for any $f$ of bounded variation (hence for Lipschitz $f$). See p. 34 of Fourier Series by Edwards.
Comment: Hint:  $\sin(nx) \approx nx$ near $x = 0$.  What conditions must you have for $f$ to be Lipschitz at $0$?
Answer: 1. Integration by parts still works if you know that any Lipschitz function $f$ on $[0, 2\pi]$ is absolutely continuous with the derivative $f'$ that is bounded a.e. by the Lipschitz constant of $f$:
$$\|f\|_{\text{Lip}} := \sup_{\substack{x, y \in [0, 2\pi] \\ x \neq y}} \frac{|f(x) - f(y)|}{|x - y|} $$
Then, as in the case of $C^1$ function, integration by parts yields
\begin{align*}
\hat{f_n}
&= \frac{1}{2\pi} \int_{0}^{2\pi} f(x) e^{-inx} \, \mathrm{d}x \\
&= \frac{1}{2\pi} \left[ -\frac{1}{in} f(x) e^{-inx} \right]_{0}^{2\pi} + \frac{1}{2\pi i n} \int_{0}^{2\pi} f'(x) e^{-inx} \, \mathrm{d}x.
\end{align*}
From this, we get the desired bound:
$$ |\hat{f_n}| \leq \frac{1}{\pi n} \|f\|_{\sup} + \frac{1}{n}\|f\|_{\text{Lip}} $$
(Remark. This idea readily extends to the functions of bounded variation.)
2. Alternatively, using the well-known trick,
\begin{align*}
|\hat{f_n}|
&= \frac{1}{2\pi} \left| \int_{0}^{2\pi} f(x) e^{-inx} \, \mathrm{d}x \right| \\
&= \frac{1}{4\pi} \left| \int_{0}^{2\pi} f(x) e^{-inx} \, \mathrm{d}x + \int_{-\frac{\pi}{n}}^{2\pi-\frac{\pi}{n}} f\left(x+\frac{\pi}{n}\right) e^{-in\left(x+\frac{\pi}{n}\right)} \, \mathrm{d}x \right| \\
&\leq \frac{1}{4\pi} \left(\int_{2\pi-\frac{\pi}{n}}^{2\pi} |f(x)| \, \mathrm{d}x + \int_{-\frac{\pi}{n}}^{0} \left| f\left(x+\frac{\pi}{n}\right) \right| \, \mathrm{d}x + \int_{0}^{2\pi-\frac{\pi}{n}} \left|f\left(x+\frac{\pi}{n}\right) - f(x) \right| \, \mathrm{d}x \right) \\
&\leq \frac{1}{4\pi} \left( \frac{\pi}{n}\|f\|_{\sup} + \frac{\pi}{n}\|f\|_{\sup} + \frac{2\pi^2}{n} \|f\|_{\text{Lip}} \right).
\end{align*}
So the desired claim follows.


Float  element on top of table?

Question: When the
 is expanded, the table gets expanded too. I intend to expand only the
, floating it over the table. How can I do this?

$(document).ready(function() {
  $("div").click(function() {
    $("div").css({
      "height": "100px"
    });
  });
});
div {
  background-color: grey;
}

click

Comment: You could use `position: absolute;`, but be aware this will remove the `div` from the size calculation of the containing `td`, so it will have no height unless it contains other data.
Answer: All you need is to set position:absolute for your div.
See CSS Layout - The position Property reference.

$(document).ready(function(){
  $("div").click(function(){
    $("div").css({"height":"100px"});
   });
 });
div{
     background-color:grey;
   }
table tr td{
  height:20px;
  width:20px;
}
div{
  position:absolute;
  top:15px;
}

click

    2

    click

    2

    click

    2

    click

    2

Float  element on top of table?


Entity Print Module: Create PDF from HTML

Question: I´m trying to use the entity_print module for generating a PDF in Drupal 8.
I want to print out HTML. My module has no entities it gets data from a solr server and generates HTML output.
My first thing is to make a route and a sort of flag to fire the pdf generation:
mymodule.page_detail:
path: '/detail/{Title}/{ObjIdentifier}'
defaults:
_controller: '\Drupal\mymodule\Controller\myController::detailpage'
Title: ''
ObjIdentifier: ''
ViewPdf: '0'
...

mymodule.page_detail_pdf:
path: '/detail/pdf/{Title}/{ObjIdentifier}'
defaults:
_controller: '\Drupal\mymodule\Controller\myController::detailpage'
Title: ''
ObjIdentifier: ''
ViewPdf: '1'

...
Then in my Controller I check for
if (isset($myModuleViewPdf) && $myModuleViewPdf == "1") {
  ...

Now the entity Print magic should come into play.
I use the services and make a print engine and a print builder:
$print_engine = \Drupal::service('plugin.manager.entity_print.print_engine')->createSelectedInstance('pdf');
$print_builder = \Drupal::service('entity_print.print_builder');

Now I´m struggeling somehow. When I look over the functions docroot/modules/entity_print/src/PrintBuilder.php
I see that they are using entities for the output but I want to use HTML.
How can I do this?
Greetings
Lars
Answer: If you want to send the PDF directly to the user then you can do something like this:
// Get your HTML from Solr.
$html = $this->getHtmlFromSolr();

$print_engine = \Drupal::service('plugin.manager.entity_print.print_engine')->createSelectedInstance('pdf');

$print_engine->addPage($html);
$print_engine->send('mydocument.pdf');

Comment: I used this in my controller and it´s working. But can I use this also at a place where I can use the twig template? in the mymodule.module or in a process function?
The reason is, we seperate code from design and the Frontend-Developer should be able to handle the twig Templates. When i now begin managing output via PHP I will mess things up.
Comment: Well you said your data was coming from Solr, you're only using Entity Print to convert HTML to PDF, whether you can use twig templates for your frontend developer would depend on whatever process you use to get  your data into HTML.
Comment: Worked for me. Saved my day. Keep posting such useful answers. Best of luck.
Comment: This has saved my day also!! with so many other developer-chaos trying to destroy/frustrate my day, this is really really useful!!! THANK YOU!! THANK YOU!!
Answer: The previos code works the first time you load the page but will throw errors in your watchdog, and you will give a WSOD when you reload the page.
You need a new Strem Response for the PDF, you cannot reuse the controller stream.
$html = $this->getHtmlFromSolr();

$print_engine = \Drupal::service('plugin.manager.entity_print.print_engine')->createSelectedInstance('pdf');
$print_engine->addPage($html);

return (new StreamedResponse(function () use ($print_engine) {
  $print_engine->send('youdocument.pdf');
}))->send();


Specifying the Error() term in repeated measures ANOVA in R

Question: I am having problems with defining the error terms for a two way repeated measures ANOVA in R. My data consists of wood density estimates for three radial positions (inner, middle, and outer) along a core extracted from a tree. There are a total of 20 tree species, 6 individuals of each species, and two cores from each tree.
To test the effect of radial position on wood density, I use the following two way ANOVA model with an error term that accounts for variability across individuals:
radpos.aov <- aov(WD ~ Species*Radialposition + Error(Individual), data=Radpos)

However, I am not sure if my specification of the error term is adequate. Am I also supposed to account for the variability within a core? To me this variability is the same as that due to radial position which is the main factor I am interested in.
Although I have devoted some time to reading about specifying the error term in Repeated measures ANOVA, I still have problems with practically specifying the error term. I will appreciate some help with this.
Answer: It would be
 radpos.aov <- aov(WD ~ Species*Radialposition + Error(Individual/(Radialposition)), data=Radpos)
 summary(radpos.aov, type=3)

That accounts for the within subject error of Radialposition. If you have other within-subject factors, throw them in (in an interaction) with Radialposition in the Error denominator, like + Error(Individual/(Radialpostion*wiFactorA)). That's my understanding of it. That matches up with SPSS's repeated measures GLM if you have no missing data.
Comment: +1. See the detailed cheat sheet here: http://dwoll.de/rexrepos/posts/anovaMixed.html. And also here: http://personality-project.org/r/r.guide/r.anova.html


Redirecionar usuário para aplicativo do Google Maps

Question: Estou desenvolvendo um site site responsivo e usando a API do Google Maps para gerar o mapa de localização da empresa.
Gostaria de quando o usurário estivesse acessando o site por um dispositivo móvel e o mesmo clicasse sobre o mapa ou até mesmo um link, fosse redirecionado para o aplicativo do Google Maps e trassasse a rota, dessa forma ele não precisaria digitar o endereço e pesquisar.
var myCenter = new google.maps.LatLng(-7.0995734, -34.8410316);
 function initialize()
    {
      var mapProp = {
      center: myCenter,
      zoom: 16,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
   var marker = new google.maps.Marker({
                position: myCenter,
            });
           marker.setMap(map);
        }
google.maps.event.addDomListener(window, 'load', initialize);

Answer: Acho que este código resolveria seu problema:
javascript:window.open("geo:"+latitude+","+longitude+"" , "_system");

O mesmo oferece a opção nativa e a do google maps para o usuário, e caso queira que seja aberto no iOS:
 javascript:window.open("maps://maps.apple.com/?q=:"+latitude+","+longitude+"");

Você pode por exemplo criar uma  que recebe os valores em lat long caso seja dinâmico, mas pelo que vi seus dados são estáticos, então é mais simples, vá até seu html e insira este código de exemplo:

   Clique aqui para abrir seu mapa

Ou simplesmente você chama uma função em seu onclick onde a mesma verifica o tipo do device, por exemplo:
var devicePlatform = (navigator.userAgent.match(/iPad/i))  == "iPad" ? "iPad" : (navigator.userAgent.match(/iPhone/i))  == "iPhone" ? "iPhone" : (navigator.userAgent.match(/Android/i)) == "Android" ? "Android" : (navigator.userAgent.match(/BlackBerry/i)) == "BlackBerry" ? "BlackBerry" : "null";
if((devicePlatform == iPhone) || (devicePlatform == iPad))
{
   /*sua chamada de função*/
}

Comment: Marcos, da uma olhada na minha pergunta, eu acrescentei meu código, por favor veja onde eu posso colocar esta linha de código que você mencionou
Comment: editei a resposta @SérgioMachado da uma olhada ai
Comment: eu u sei o código, abria o mapa mas abria sem coordenadas, então fiz mais uma pesquisa na internet e achei a solução:
  $("#googleMap").on('click', function() {
            window.location = "http://maps.google.com/?q=Implantare+Soluções+em+Odontologia/";
        });
Comment: se funcionou ta tranquilo


Kafka How to not move offset until message processing is succeeded

Question: We are reading messages from a Kafka-topic. I was under the (false) impression that by setting the EnableAutoOffsetStore/enable.auto.offset.store = false you, as a consumer could choose when you wanted to move the offset.
We were using this like so
while (!cancellationToken.IsCancellationRequested)
{
    try{
         var consumeResult = kafkaConsumer.Consume(cancellationToken);
         // process consumeResult.Message
         kafkaConsumer.StoreOffset(consumeResult);
    }
    catch
    {
      // delay and re-try
    }
}

In this way we could re-read the message if we got an exception.
We have 1 producer, 1 consumer,1 topic, 1 partition (and 1 group)
How should this behavior be achieved?
Answer: If you catch an exception in process, then the commit will never happen.
You can store the partition+offset for the record that failed and Seek back to that offset.
Alternatively, you can skip over the offset in your main processing loop and write that record to a dead-letter topic and write a different consumer to "process again/differently"
Comment: This is how any Kafka client works. You would need to kill the application on any exception, then let some external process restart it (supervisor, Docker/Kubernetes, etc). Only then would it pickup at the last failed offset. The only problem there is that it'll not be able to track how many times it restarted, so might restart forever (until message retention happens), and the whole consumer group will keep pausing to rebalance. Saving the offset in-memory isn't the best approach either because it assumes your consumer won't rebalance between polls
Comment: Thanks for your response. First of all, your suggestion about saving offset and seeking it for a retry works, thanks! But I cant help feeling that its a workaround for something that should be simpler or more built in [newline]

Im new to Kafka and want to learn to do it correctly. One thing that confuses me: I don't do commit and still the offset is increased on next Consume(). I was hoping to, when I dont Commit and read again I would get the same message on next read. Is this not the expected behaviour from not commiting (having both AutoCommit=false, AutoOffsetStore=false)
Comment: Ok, good to know. I guess I have to
Im guessing rebalancing is not an issue since we only have 1 partition (and 1 consumer).


How to add navigation to backing bean

Question: A simple issue, but can't remember how to do it best. What I want is to automatically send the user to another page "/lecturer/marking/marking-section-two" after a code section is run.
Is there a way of doing this in the backing bean that won't effect the ajax message displayed before it ?
This is the code i am running
public void markSectionOne() {
    //supposing the data in markSectionOne is filled...
    this.markingFacade.create(markSectionOne);
    this.setMessage("Mark Saved");
    //after saving...
    markSectionOne = new Marking();
    // now navigating to the next page
}

and once it's run I want to navigate automatically to a new page.
Thanks guys
Comment: Change method signature to `public String markSectionOne()` and return redirection outcome. Outcome can be registered in **faces-config.xml** in section ``
Answer: You can change your method to return a String which will be interpreted as the next navigation outcome.
public String markSectionOne() {
    // ... unrelevant code
    return "/lecturer/marking/marking-section-two";
}

If the method returns null, then JSF will stay on the same page.
Comment: Thanks :) i wasn't sure if changing the method to return a string would effect the functionality of it, thanks a lot :)

How to add navigation to backing bean