atualizar atributo mysql de acordo com um dia (12/12/2019) cakephp, mysql

Question: Estou com o seguinte problema:
Caso um cliente não pague uma determinada parcela gostaria que o sistema (mysql+cakephp) colocasse o cliente com o status devedor. teria alguma forma de automatizar isso, sem que o funcionário altere manualmente o status do cliente?
Gostaria que o proprio mysql diariamente fizesse uma consulta no banco e trocasse o status dos clientes que não pagaram até aquele determinado dia para (atrasado) ai quando o funcionario entrasse no sistema ja viria os clientes que estão em atraso. a parte da aplicação é tranquilo pra mim a minha duvida é como que faço para automatizar essa logica do banco
Answer: Você pode criar um evento.
Um evento é uma tarefa executada com base em um agendamento predefinido, portanto, às vezes, é referido como um evento agendado.
Um procedimento é executado apenas quando é chamado diretamente, um gatilho é executado quando ocorre um evento associado a uma tabela, como um evento de inserção, atualização ou exclusão. Já um evento pode ser executado em intervalos temporais regulares, uma ou mais vezes. O evento também é conhecido como "gatilho temporal" porque é acionado pelo tempo.
Um evento é semelhante a uma atividade cron no UNIX ou a um agendador de tarefas no Windows.
Você pode usar eventos em muitos casos, como otimizar tabelas de banco de dados, limpar logs, arquivar dados ou gerar relatórios complexos fora do horário de pico.
Iniciando o agendador de eventos no MySQL.
Por padrão, o agendador de eventos não está ativado. Para habilitar e iniciar o agendamento de eventos, é necessário executar o seguinte comando:
SET GLOBAL event_scheduler = ON;

Para desativar o agendador de eventos execute o comando:
SET GLOBAL event_scheduler = OFF;

Criando novos eventos MySQL
A criação de um evento é semelhante à criação de outros objetos de banco de dados, como procedimentos ou gatilhos.
Um evento é um objeto nomeado que contém instruções SQL.
Syntaxe.
CREATE
    [DEFINER = user]
    EVENT
    [IF NOT EXISTS]
    nome_do_evento
    ON SCHEDULE schedule
    [ON COMPLETION [NOT] PRESERVE]
    [ENABLE | DISABLE | DISABLE ON SLAVE]
    [COMMENT 'string']
    DO corpo_do_event;

schedule:
    AT timestamp [+ INTERVAL intervalo] ...
  | EVERY intervalo
    [STARTS timestamp [+ INTERVAL intervalo] ...]
    [ENDS timestamp [+ INTERVAL intervalo] ...]

intervalo:
    quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE |
              WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE |
              DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}

CREATE EVENT requer o privilégio EVENT para o esquema no qual o evento deve ser criado.
A cláusula ON SCHEDULE determina quando e  com que frequência e por quanto tempo a ação definida em  corpo_do_event definido se repete. Esta cláusula assume uma das duas formas:

AT timestamp que é usado para um evento único. Ele especifica que o evento
é executado apenas uma vez na data e hora fornecidas por timestamp ou deve ser uma expressão que seja resolvida para um valor de data e hora. Você pode usar um valor do tipo DATETIME ou TIMESTAMPpara esse propósito.
EVERY que é usado para repetir ações em um intervalo regular. A cláusula EVERY pode conter uma cláusula `STARTS seguida por um timestamp que indica quando a ação deve começar a se repetir.Também pode conter uma cláusula ENDS seguida por um timestamp que informa ao MySQL quando o evento deve parar de se repetir.

Os requisitos mínimos para realizar uma declaração CREATE EVENT válida são os seguintes:

As palavras-chave CREATE EVENT mais um nome único de evento, que
identifica exclusivamente o evento em um esquema de banco de dados.
Uma cláusula ON SCHEDULE que determina quando e com que frequência
o evento é executado.
Uma cláusula DO que contém a instrução SQL a ser executada pelo
evento.

Para descartar o evento use a declaração DROP EVENT:
DROP EVENT [IF EXISTS] nome_do_evento

Para mais detalhes sobre a sintaxe de CREATE EVENT https://dev.mysql.com/doc/refman/8.0/en/create-event.html
Para mais detalhes sobre a sintaxe de DROP EVENT
https://dev.mysql.com/doc/refman/8.0/en/drop-event.html
Resposta
Aplicando a sua questão o que posso oferecer é um exemplo superficial de um evento que todos os dias verifica a tabela de clientes e se o pagamento é 0 ele muda o status do cliente para devedor, pois não foram apresentados dados específicos sobre o formato dos dados em sua pergunta:
CREATE EVENT verificarEstatus
    ON SCHEDULE EVERY DAY STARTS CURRENT_TIMESTAMP
    DO
      UPDATE alugueis.clientes SET status = "DEVEDOR" WHERE pagamento = 0;

Esse evento inicia a verificação no dia 12/12/2019:
CREATE EVENT verificarEstatus
    ON SCHEDULE EVERY DAY STARTS TIMESTAMP('2019-12-12')
    DO
      UPDATE alugueis.clientes SET status = "DEVEDOR" WHERE pagamento = 0;

Esse evento inicializa hoje a verificação e termina no dia 12/12/2019:
CREATE EVENT verificarEstatus
    ON SCHEDULE EVERY DAY STARTS CURRENT_TIMESTAMP
                ENDS TIMESTAMP('2019-12-12')
    DO
      UPDATE alugueis.clientes SET status = "DEVEDOR" WHERE pagamento = 0;

Comment: Muitíssimo obrigado meu querido, super ajudou!


How to add additional url parameters?

Question: I would like to know how I can include additional URL parameters to a given link? ie: 'news?pid=3'
<?php
print $path='news?pid=3';
?>

This returns page not found error as the '?' is getting printed as %3F.
Answer: If you are using l(), you would do something like this to create news?pid=3.
l('Link Text', 'news', array('query' => array('pid' => '3')));

If you have other query parameters, you can add them in like this:
l('Link Text', 'news', array('query' => array('pid' => '3', 'foo' => 'bar')));

and that would create news?pid=3&foo=bar.
More information on l() here and url() here.

How to add additional url parameters?


openvdb resampleToMatch()

Question: I want to decrease the voxel density of an openvdb grid. Inspired by this answer, I tried the following code:
const auto dim = grid->evalActiveVoxelDim().asVec3i();
std::cout << dim.x() << " " << dim.y() << " " << dim.z() << std::endl;

T::Ptr dest = T::create();
dest->setTransform(openvdb::math::Transform::createLinearTransform(1.0f));
openvdb::tools::resampleToMatch<openvdb::tools::BoxSampler>(*grid, *dest);

const auto dd = dest->evalActiveVoxelDim().asVec3i();

std::cout << dd.x() << " " << dd.y() << " " << dd.z() << std::endl;

The printed output with the grid I tried is the following:
86 93 82
8 8 6

I don't understand what this means. With scaling 1.0 I expected the same voxel density. Does the original grid include some scaling that I need to consider?
Also, is there a way to do this operation multi-threaded?
Answer: I realized that scaling 1.0 is not neutral, because the grid can start out with an arbitrary voxel scale, that can be queried with voxelSize().
So resampling the grid so the voxels are twice as large could look something like this:
T::Ptr dest = T::create();
dest->setTransform(openvdb::math::Transform::createLinearTransform(grid->voxelSize().x() * 2));
openvdb::tools::resampleToMatch<openvdb::tools::BoxSampler>(*grid, *dest);

I believe it is multi-threaded by default, but has a long single-threaded passage at the end of the operation.

openvdb resampleToMatch()


Formatação de números com jQuery

Question: Olá,
Tenho um array que é retornado por meio de uma requisição AJAX e pretendo formatar os números de cada uma dessas chaves da seguinte forma:

Exemplo:

Valores padrões
-> 2569
-> 192544694

Como gostaria que fossem formatados
-> 2.569
-> 192.544.694

Claro que essa formatação seria por meio de uma função por se tratar de valores variáveis. Cheguei a criar uma função mas não obtive total flexibilidade em sua efetividade, além de tentar alguns frameworks, como number.js, por exemplo.
Alguma solução? Seja um script ou framework alternativo?
Comment: Esses numeros são numeros, ou dinheiro? (Sobre formatar dinheiro: http://pt.stackoverflow.com/q/11018/129)
Comment: @Sergio, são números!
Comment: Ok, então a minha resposta deve fazer o que precisas. Dá uma olhada.
Answer: Podes fazer isso assim:

function formatar(nr) {
  return String(nr)
    .split('').reverse().join('').split(/(\d{3})/).filter(Boolean)
    .join('.').split('').reverse().join('');
}

var numeros = [2569, 192544694];
var formatados = numeros.map(formatar);
console.log(JSON.stringify(formatados)); // ["2.569","192.544.694"]

A ideia é usar uma expressão regular para agrupar de 3 em 3, mas como queremos agrupar de trás para a frente, daí a lógica do reverse().
Comment: Sem espinhas, muito bom
Answer: function format(nStr)
{
    nStr += '';
    x = nStr.split(',');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2;
}

Créditos para Abe Miessler em https://stackoverflow.com/questions/7327046/jquery-number-formatting
Comment: +1 muito bom...
Answer: Recomendo a biblioteca jQuery mask. Seu código poderá ficar dessa forma:
HTML
<input class="money" />

jQuery
 $('.money').mask('0000.000,00', {reverse: true});

JSFiddle: https://jsfiddle.net/lbclucascosta/aoc6o0qa/1/
Comment: é impressão minha ou nessa biblioteca não tem formatação para números? Apesar disso, muito interessante, obrigado pela sugestão!

Formatação de números com jQuery


Fourier transform of $L^1$ function square summable?

Question: It is known that for a $L^1$ function $f: \mathbb{R} \rightarrow \mathbb{C}$ the Fourier transform vanishes at infinity and is continuous. Does this even mean that $(\hat{f}(n))_{n \in \mathbb{Z}}$ is square-summable?
Answer: At least it does not mean that $\hat{f} \in L^2(\mathbb{R})$, because then by the Plancherel theorem $f$ itself would have to be $L^2$. But this can fail; for instance $f(x)=x^{-2/3} \chi_{(0,1]}(x)$ is $L^1$ but not $L^2$. I would imagine that $\hat{f}(n)$ is not summable on $\mathbb{Z}$ either (at least with an example like mine which is quite far from being $L^2$, rather than $x^{-1/2} \chi_{(0,1]}(x)$ which is "almost" $L^2$).
Answer: Let
$$
f_a(x)=\frac{1}{\sqrt{|x|}} \chi_{[-a,a]}
$$
Observe that $f_a \in L^1$ but not in $L^2$.
Now just compute the fourier transform and play with $a$.
\begin{align}
\hat{f_a}(y) &= \int_{-a}^a \frac{1}{\sqrt{|x|}}e^{-iyx} \, dx \\
 &=\int_0^a\frac{1}{\sqrt{x}}e^{-iyx}+\frac{1}{\sqrt{x}}e^{iyx} \,dx \\
& =2 \int_0^{\sqrt{a}}e^{-iys^2} + e^{iys^2} \, ds.
\end{align}
Ok now compute the first term with this trick:
\begin{align}
 \left( \int_0^{\sqrt{a}}e^{-iys^2} \, ds \right)^2 &=\left( \int_0^{\sqrt{a}}e^{-iys^2} \, ds \right)\left( \int_0^{\sqrt{a}}e^{-iyt^2} \, dt \right) \\
&=\int_0^{\sqrt{a}}\int_0^{\sqrt{a}}e^{-iy(s^2+t^2)} \, dt \,ds \\
&=\int_0^{2\pi} \int_0^\sqrt{a}re^{-iyr^2} \, dr \, d\theta \\
& =2 \pi \frac{1}{-2iy}\int_0^{\sqrt{a}}-2iyre^{-iyr^2} \, dr \\
&=\frac{i\pi}{y}\left(e^{-iy\sqrt{a}} -1\right).
\end{align}
In the same way one can compute the second term and we obtain:
$$
\hat{f_a}(y)=2\sqrt{\frac{\pi i}{y}}\left( \sqrt{e^{-iya}-1} + \sqrt{1-e^{iya}} \right).
$$
If you choose $a=2 \pi$ you obtain that $\hat{f_{2 \pi}}(n)=0$, i.e. $(\hat{f_{2 \pi}}(n))_n$ is square summable.
But if you choose $a=\frac{\pi}{2}$ than you obtain that $\hat{f_{\frac{\pi}{2}}}(n) \sim \frac{1}{\sqrt{n}}$ wich is not square summable.
This means that you can not says anything about $\hat{f}(n)$ if you now only that $f \in L^1$. I think that the problem is namely that the Fourier coefficients describe in an unique way a function if it is in $L^2$. But this is not true in $L^1$.


Global Minimum solution for the Generator step in the original GAN formulation

Question: I am going through the proof in Goodfellow's original GAN paper. Specifically, I'm at the stage where he did the discriminator step (solve a maximization problem) and now he is doing the generator step, that is $\min_{G} C(G)$ which is $\min_GV(G,D^{*})$.
He nicely shows that $p_g=p_{data}$ achieves the minimal value, $-\log(4)$. I get the proof. But then for fun I try to evaluate $C(G)$ with choosing $p_g := 0.5 \cdot p_{data} $.
So, plugging that into $$ \mathbb{E}_{x\sim p_{data}} \lbrack \log{
\frac{p_{data}}{p_{data}+p_g}}\rbrack +
\mathbb{E}_{x\sim p_{g}} \lbrack \log{
\frac{p_{g}}{p_{data}+p_g}}\rbrack
$$
we get
$$ \mathbb{E}_{x\sim p_{data}} \lbrack \log{
\frac{p_{data}}{p_{data}+0.5\cdot p_{data}}}\rbrack +
\mathbb{E}_{x\sim p_{g}} \lbrack \log{
\frac{0.5\cdot p_{data}}{p_{data}+0.5\cdot p_{data}}}\rbrack =
$$
$$ \mathbb{E}_{x\sim p_{data}} \lbrack \log{
\frac{1}{1.5}}\rbrack +
\mathbb{E}_{x\sim p_{g}} \lbrack \log{
\frac{0.5}{1.5}}\rbrack = \log{\frac{2}{3}}+\log{\frac{1}{3}} =
$$
$$= -1.5041 (< -\log4= -1.3863)
$$
So it seems to me that if the generator optimizes for $p_g =0.5 \cdot p_{data} $ it actually achieves a better minimum for the target of the minimization problem.
To add further to my confusion, I ran the numbers in MATLAB (ignoring the expectation since I assume I'm taking it in a way such that $p_{data}$ cancels out, like before) and got the $-\log4$ is actually the maximum and not the minimum.

[x,y] = meshgrid(0.01:0.001:1);
f = log(x./(x+y))+log(y./(x+y));
max(max(f))

ans =   -1.3863

min(min(f))

ans =   -4.6251

I'll add that in my numerical experiment, the minimum was indeed achieved along the axis $x=y$. The minimum there collapses to the boundaries.
Why is this problem somehow minus-flipped in my head? I mean, we are trying to minimize it and not maximize it. I follow the proof that it is a global minima, so I don't see why am I getting lower values. is my choice somehow not permitted?
Thanks.
Answer: For your first question, $p_g(x)=0.5p_{data}(x)$ is not a probability distribution, because $\sum_{x}p_g(x)=1$ must hold when summing over the latent space, whereas you will get $0.5$. So while $p_g(x)=0.5p_{data}(x)$ might hold for some set of $x\in X$, there must also be a set $Y$ such that $p_g(y)>0.5p_{data}(y)$ for all $y\in Y$.
For your second question, you're looking for the minimum of the expectations, which is not-at-all equivalent to minimizing the fixed function $\log(xy/(x+y)^2)$. Hence you need to consider the KL divergence between your generator and data distributions.


How can I show quantity field in Ubercart on Drupal site

Question: I have module Ubercart for Drupal.
I would like to have showed box for QUANTITY, but I can't find it in view setting for fields or in administration for cart "admin/store/settings/cart" or in section manage display for product content type.
Is it possible? thanks
Answer: Try this:
Administer » Store administration » Configuration » Product settings where it has a check box "Display an optional quantity field in the Add to Cart form."
Comment: AAAAHHH I see it right now under PRODUCT SETTING. Sorry and thanks,


Violin intonation base note

Question: I read that the violin can be tuned to perfect fifths so I was thinking of tuning my violin to G3=195.55Hz, D4=293.33Hz, A4=440Hz, E5=660Hz.
But I don't understand what it means to play single stops with pythagorean intonation and double stops with just intonation, since they seem to be functions of a reference tone. How do I choose the reference tone? I got unsure because I saw a video where they said one avoids open strings in flat keys (and I thought I just tuned the open strings in pythagorean temperament? perhaps there is some conflation of terms I have missed.)
I have seen amongst others

I have read amongst others
https://en.m.wikipedia.org/wiki/Just_intonation
https://en.m.wikipedia.org/wiki/Pythagorean_interval
https://en.m.wikipedia.org/wiki/Wolf_interval
It is probably some kind of rule of thumb I have missed...
Comment: Oof; I'm a violinist (and a baroque violinist at that, so I have to talk about temperaments!) and am already confused. But let's problematize one assumption right off the bat: *"I read that the violin resonates more if tuned to perfect fifths..."* 1) But does it? and 2) what is meant by "perfect"? In the music theory sense, "perfect fifth" just means a fifth as we know it, and in that sense, any other tuning would be non-standard. But if we're talking about nudging that fifth narrower or wider by a few cents, then "resonance" is not going to be the primary aim. ...
Comment: The resonance of the instrument is affected much more profoundly by many other things. The placement of the sound post most of all—if you want the instrument to resonate more at a specific pitch, you can monkey around with the sound post positioning. The gauge and material of the strings, the height and shape of the bridge, the relative humidity of the room all play more of a role in "resonance" than a temperament. Add to that the fact that the violin is a fretless instrument, so we adjust (or misadjust) the temperament of all non-open notes manually.
Comment: And one footnote to any discussion of temperament and tuning: If you're playing one instrument, solo, you can of course do anything you want. If you're playing with others, you have to ask yourself what works best overall. A string quartet can take principles that work well for violin and spread them over 5 fifths. If you're playing with an equal-tempered piano, you better get on board the ET train. If you're playing with a harpsichord... then they spend 15 minutes explaining the temperament, 2 hours tuning, 30 seconds playing in tune, and the rest of the concert being out of tune.
Comment: I think I mean sympathetic vibrations on open strings but not sure. I can remove that word since it doesn't matter for my question.
Comment: It would be very helpful if you would post specifically what you read and/or link(s) to the videos you watched.
Comment: @AndyBonner I think the underlying phenomenon here is that of acoustical reinforcement.  The closer the two pitches are to a 3:2 ratio, the more they reinforce each other and the more resonant the resulting sound.  This is true even if the pitches are produced by different instruments or by wind instruments or voices where there isn't much resonance in the instrument itself but only in the air.
Comment: @AndyBonner I thought baroque violinists just dealt with temperament by tuning each string to the keyboard instead of to the adjacent string.  (This is a joke: early-in-the-semester baroque orchestra rehearsals in grad school were extremely painful to overhear as they spent what seemed like hours retraining the modern-instrument players who had just taken up baroque instruments how various harmonies should be tuned.)
Answer:
How do I choose the reference tone?

The reference tone can be the previous note, the tonic pitch, or a note that someone else is playing, such as your cellist.
One fact about just intonation that many people miss is that it isn't a fixed scale.  Suppose you're playing in G major.  Your E can have two different frequencies depending on the context.  If the harmony is G-C-Am, the frequency of that E will be 5/3 times the frequency of G (4:3 times 5:6 times 3:2), but if the harmony is G-D-Am, the frequency of the E will be 27/16 times the frequency of the G (3:2 raised to the third power, divided by 2).

I saw a video where they said one avoids open strings in flat keys (and I thought I just tuned the open strings in pythagorean temperament? perhaps there is some conflation of terms I have missed.)

Yes, you just tuned your strings in Pythagorean fifths (which, it must be noted, are also just intonation fifths).  But that advice is useful when you want to play in just intonation, where the thirds are critical.
The open strings are more likely to be major thirds in flat keys, and major thirds are the pitches that one lowers to achieve just intonation.  For example, in B♭ major, the G string is the major third of the subdominant chord, D is the major third of the tonic, and A is the major third of the dominant.  By contrast, in keys with no flats, the open strings are going to be more stable: they are likely to be the root of the subdominant, dominant, or tonic chord.
If you're truly playing in Pythagorean tuning, it shouldn't make a difference whether you use the open string or not, but people rarely use pure Pythagorean tuning because people rarely play a melody by itself with no harmony, and, if there's harmony, you want to tune the major thirds a bit lower.
In general, the thirds have more room for flexibility, and open strings are rather less flexible with respect to tuning.  Therefore, in the keys where the open strings tend to be the thirds, you'll want to avoid the open strings.
In a comment, you ask

In the first part, do I understand you correct that in one case two chords contain E so you use the just E (major sixth of G), and in the other case one chord contains E so you use the pythagorean E (major sixth of G)?

I responded:

@Emil the A and the E will both be lower by a syntonic comma in the first progression as compared to the second. The reason for this is not because of the number of chords containing E but because of the identity of the first chord that contains either A or E. The G-C progression in the first example causes the first A or E that appears to be E as the major third of the C chord. This in turn pushes the A down in the next chord. By contrast, in the second progression, G-D gives us A as the fifth of the D chord, which pushes the E up in the next chord.

Since the question is expressed in terms of specific frequencies, it might be helpful to perform this analysis with specific frequencies.  We'll start with G as 195 5⁄9 Hz or 195.56 Hz.
To find D, which is the fifth of the initial G chord, we multiply that frequency by 3:2, giving 293 1⁄3 Hz or 293.33 Hz, the open D string.
Starting with the second progression, G-D-Am, we take the same D as the root of the second chord.  The fifth of that chord is A, and, no surprise, multiplying 293 1⁄3 Hz by 3:2 yields 440 Hz for the frequency of A, the open A string.
As we did before, we use that A as the root of the succeeding chord, and, again, to nobody's surprise, the frequency of E works out to 660 Hz.
The first progression, G-C-Am, starts with the same root, G at 195 5⁄9 Hz.  Using that G as the fifth of the following C chord, we can find C through multiplication by 2:3, which gives the frequency of the viola's open C string.  To keep this in violin range, however, we'll go up a perfect fourth, using 4:3, which gives us a frequency of 260 20⁄27 Hz or 260.74 Hz.  The E that is a just major third above it is 325 25⁄27 Hz or 325.93 Hz.  Going up a perfect fourth from that E to find the root of the following chord, we get an A of 434 46⁄81 Hz or 434.57 Hz.
To put this in tabular form, including additional pitches for each chord:

Frequencies in Hz
G
D
Am

G
C
Am

E5

660
E5

651 23⁄27
651 23⁄27

C5

528
C5

521 13⁄27
521 13⁄27

A4

440
440
A4

434 46⁄81

G4
391 1⁄9

G4
391 1⁄9
391 1⁄9

F♯4

366 2⁄3

F♯4

E4

E4

325 25⁄27

D4
293 1⁄3
293 1⁄3

D4
293 1⁄3

C4

C4

260 20⁄27

B3
244 4⁄9

B3
244 4⁄9

G3
195 5⁄9

G3
195 5⁄9

Within each half of the table, left and right, the values in any given row are the same.  Between the left half and the right half of the table, however, the values for A, C, and E differ by a factor of 81:80, the syntonic comma.
Comment: @Emil I expanded the answer to put some concrete numbers into the analysis.
Comment: In the first part, do I understand you correct that in one case two chords contain E so you use the just E (major sixth of G), and in the other case one chord contains E so you use the pythagorean E (major sixth of G)?
Comment: @Emil the A and the E will both be lower by a syntonic comma in the first progression as compared to the second.  The reason for this is not because of the number of chords containing E but because of the identity of the first chord that contains either A or E.   The G-C progression in the first example causes the first A or E that appears to be E as the major third of the C chord.  This in turn pushes the A down in the next chord.  By contrast, in the second progression, G-D gives us A as the fifth of the D chord, which pushes the E up in the next chord.
Answer:
But I don't understand what it means to play single stops with pythagorean intonation and double stops with just intonation, since they seem to be functions of a reference tone.

It basically means that when playing single-note melodies, you should focus on getting the tuning of all whole steps close to 9:8, and any two notes related by a fourth or fifth should be at a ratio of 3:4 or 2:3, respectively. This way, sequential notes will sound consistent and steps are clear, all whole steps are much larger than the semitones.
The flip side is that intervals such as major thirds and sixths come out with complex ratios (81:64, 27:16). That isn't such a noticeable problem when an agile solo melody plays over a background accompaniment, but it's quite notable when two equally-prominent voices are harmonizing, in particular if they're both played on the same instrument. In that case, you'll hear a strong beat between the lower overtones of each tone. E.g. in two voices playing the 81:64 Pythagorean major third of A3 against C♯4, the A3 has its fifth overtone at 1100 Hz, whereas the C♯4 has its fourth overtone at 1114 Hz. The difference of 14 Hz is neither high enough to be really heard as a clear resultant, nor low enough to be a smooth sound-modulation – it just sounds rough.
That can be addressed by tuning the major third narrower, namely to Ptolemaic just intonation. Which sounds great for held chords, but it introduces its own problem: now you have two whole steps of different size, namely 9:8 and 10:9. And that sounds weird in a melody: both steps are similar enough to be classed as the same interval, yet just different enough to seem like something's wrong.
Of course, this issue is resolved by meantone temperaments, including 12-edo, by putting the whole step right in the middle of the major third. Now all whole steps are the same again... but none of them have the wide, confident character of Pythagorean steps!
What your source is suggesting is that you should watch out for all these problems and choose the tuning accordingly, to fix whatever doesn't work in a given piece/segment.

A double stop sounds rough? Tune it to JI. This mainly entails making major thirds and sixths a bit narrow.
A melodic line sounds uneven or feeble? Widen all the whole steps to Pythagorean.

they said one avoids open strings in flat keys

The reason for this would be: e.g. in the key of F major, the open A is the major third of the tonic. If you're going to have that major third as a JI double stop, the only way to do it with an open A is to raise the F up. But that won't work if e.g. the piano accompaniment already contains a low F bass note: your F would be notably out of tune relative to that.
Instead, the suggestion is to play the A fingered and slightly flat compared to the open string. This way, both your F and your A will sound good over the piano bass note. That A will be 15 ct flatter than an A the piano might play, but (probably not coincidentally) classical counterpoint avoids giving two different voices the third of a chord at the same time, so this isn't a big deal.
Comment: "yet just different enough to seem like something's wrong": it never sounded wrong to me.  "Probably not coincidentally": indeed.  But I suspect that this is less about tuning with other instruments (piano accompaniments of solo parts rarely have open fifths when the solo part is on the third) than it is about how raising the F would also imply raising most of the other pitches in the F major scale.  Though as a bass I have to say that judicious raising of bass notes can be very effective.
Answer: FWIW, I think most of us bowed string players tune in mathematically true fifths (or fourths for the bass viol), if for no other reason than to do otherwise leads to out-of-tune open string double stops.
As everyone is pointing out, you can adjust the tuning of every fingered note -- and to some extent even the harmonics -- to match the temperament selected for the music you are playing.  We do avoid single-stop open string notes more often in quiet passages; when the music is forte the pitch differences become pretty much undetectable by the human neuroaudiologics.
Comment: Also perfect fifths are very close to equal temperament.  String players playing with harpsichord or organ in an unequal temperament often do tune open strings separately to the keyboard, because the fifths are often rather farther from perfect than are equal-tempered fifths.  In fact, in at least one unequal temperament, the open string fifths are the _only_ fifths that are tempered; the others are tuned pure.  I never quite understood why that would be desirable.

Violin intonation base note


sites.php setup

Question: I am trying to do multi-site the following way:
http://domain.com/site1
http://domain.com/site2
sites.php:
 $sites['domain.com.site1'] = 'default';
 $sites['domain.com.site2'] = 'site2';

I then went into my drupal root and did:
ln -s . site1
ln -s . site2

Is this the correct way of doing this? It appears to work, but I am not sure if symlinking is the proper way.
Comment: Shouldn't that be: `$sites['domain.com.site1'] = 'site1';` (not `default`)
`$sites['domain.com.site2'] = 'site2';` ?
Comment: Check out: https://www.drupal.org/documentation/install/multi-site which answers your question. From # 5:  "Make symbolic links if you are using a subdirectory such as example.com/subdir and not a subdomain such as subd.example.com (see the subdirectory multi-site section below for details). "
Answer: Yes- you did this right :)
cp example.sites.php as sites.php, set the sites array, set the symlink, and you're set!
Comment: Are there are security issues with the fact that you can so /site1/site1/site1...?
Comment: I'm not quite sure what you mean- all sites should be located in the /sites/ directory and have a unique settings.php... This shouldn't pose a security risk.
Comment: I mean I can do http://domain.com/site1/site1/site1 because of the symlink to its parent directory.
Comment: You're still only accessing the parent directory- how would this pose a risk?
Comment: @ChrisMuench security is what I was thinking too when I saw this.  I haven't spent time on it, but I expect there very likely are implications here.  Check rewrite rules for things like protecting private file directories carefully, and post any worrying findings.  Circular symlinks are almost always a bad idea.
Answer: You can set the sites array in sites.php as:
$sites['multi.devs'] = 'multi.dev';
$sites['sub1.multi.devs'] = 'multi.devs';
$sites['sub2.multi.devs'] = 'multi.devs';

and in your hosts file you can set the hostname as
127.0.0.1       multi.devs
127.0.0.1       sub1.multi.devs
127.0.0.1       sub2.multi.devs

Also need to entry them in httpd-vhost.conf file. Like:
<VirtualHost *:80>
    DocumentRoot "projects/drupal_multi/"
    ServerName   multi.devs
    ErrorLog    "logs/error.log"
    CustomLog   "logs/access.log" common
</VirtualHost>

You need to do this for each of sub site. DocumentRoot will be the same the server name will be change for each of them.

sites.php setup


Concatenating vue API URL

Question: I'm trying to connect an API to my Vue app, but can't seem to get it to work properly.
Checking dev tools, it looks like the app is making the request using only "https://api.scryfall.com/cards/search?q=!" and not including the part of the string that was concatenated.
Any ideas? The URL should include some kind of card name at the end.
App.vue
<template>

    <deckBuilder @addCard="addCard" @clearDeck="clearDeck" @requestData="requestData"
      :title="title" :card="card" :deck="deck" :received="received" />

</template>

deckBuilder.vue
<template>

{{ title }}

    <input @keyup.enter="addCard" v-model="card" placeholder="Type a Card Name" />
    <button @click="addCard">Add!</button>
    <button @click="clearDeck">Clear Deck</button>
    <button @click="requestData">Request</button>

Deck: {{ deck.length }} Cards

{{ item }}

</template>

Comment: I guess that `this.card` is empty, and it's why you are getting this problem.
Comment: In your `addCard` method why are you initialising this.card
Comment: I was clearing the data in addCard. I removed that line and it still has this.card as undefined.
Comment: Don't remove that line just change `this.card = cardName;`
Comment: I added that and it's still setting the url as "https://api.scryfall.com/cards/search?q=!undefined" instead of "https://api.scryfall.com/cards/search?q=!opt" for example.
Comment: You shouldn't use v-model on a prop, you should use an event to emit updates to the card and your url should be a computed property so that it tracks changes of the card value.
Comment: Well, you initialize `this.card` to be an empty string and nowhere in the code shown do you set it to any other value. Why would you expect the URL to have any value other than an empty string?
Answer: According to your demo code,
addCard: function(cardName) {
      this.deck.push(cardName);
      this.card = '';
    },

I think you get confused, the cardName was inserted to deck by event rather than card,
and you set an empty string with this.card which means the card is empty on next line, so you can't get any string once you apply addCard.
please try to use url: apiLink + this.deck[0], to replace url: apiLink + this.card,

Concatenating vue API URL


How can I be sure that I am singing effortlessly in my natural voice?

Question: I have years of vocalization practice, but I still start straining while singing—especially if I am not vigilant. It happens imperceptibly and is a hard habit to break.
Is there a reliable technique to make sure that I don't lose my effortless natural voice while quickly going from chest to head voice and back during a practice session?
Answer: I often start my warming up like this:

Take a deep breath and sigh/hum softly and gently. Repeat this a few times.
Repeat the exercise with the mouth opened, but not with more effort, for a few times
After a while, you should have found your "ground tone", which is the tone you can sing without straining. This tone is the basis of healthy singing. Take a deep breath and sing this tone without getting louder, but firmer. Be careful staying totally relaxed!
Now you are sure about your ground tone. The idea of the following is to carry this tone to all registers. For this, begin with a slow, lazy glissando up a second, and back. Repeat.
Go on to thirds, fourths, and so on. If you feel the straining coming back, take smaller intervals. Repeat until you come to the border of your chest register.
Take a break of a minute or more.
Find the ground tone of your head voice! This might be harder for women than for men, I don't know. Carry your ground tone down slowly. If you do it slow enough and silent enough, you can connect head voice and chest voice. Repeat this connection a few times, but always starting with the head voice!
If you are feeling the slightest exhaustion, take a break of a few minutes immediately.
Repeat the whole procedure every morning.

I did this a few years ago and my head register connects smoothly to my chest register, while the feeling stays perfectly natural and without great exhaustion.
Comment: A video would really help
Comment: This is pretty much to the point.
Comment: interesting. One point I did not think about is to exercice from the head voice to the chest, because I am usually focused on succeeding in going the other way. It also means that I am not familiar enough with my head voice -- and I should.
Comment: Going down from head voice to chest voice is much easier, for me at least. Having practised that, it is easier to go the other direction.
Comment: Sorry, I don't have a cam. But feel free to add a video yourself.
Answer: I have trouble with this too; here are some things that have helped me.

Sing through the phrases. Think of each phrase as a long line instead of thinking of each note as something to achieve. This makes your singing less forced.
When you notice yourself getting too tense, pay attention to the specific parts of your body where you carry the excessive tension. Consciously relax them, and deliberately practice singing without that tension, possibly touching the tense area with your hands to help keep you relaxed.
Answer: I'm an instrumentalist who only recently (in my mid-50's!) began to work with an amazing voice teacher, and am beginning to get a handle on my singing "instrument". So I'm not a "natural", and have been paying very close attention to the physical sensations of singing, and your question brought up a number of things.
"Effortless"? I've been taught that I should be tired after singing well for a while - it's very physical, after all - but I know what you mean - when things are flowing you're not fighting yourself, and there is no tension (muscles working against each other unnecessarily). Maybe it helps to talk about the difference between "tension" and "support" (as in "supporting the tone" in another answer here) - But since support in singing inevitably involves fantastically complex interactions of little muscles all through your body, often working "against" each other, it can be hard to tell the difference!
But it sounds like your are looking for concepts, so much as very specific, reliable techniques. One way I've learned to distinguish between "tension" and "support" is that I can voluntarily give up support, but tension takes some touching, etc. to shed. For a lot of singers, tension tends to collect in the throat and jaw. A nice trick is to run your hands down either side of your face while singing an "ah" - is your jaw hanging loose? Can you let your tongue hang out while doing the same thing? I was taught to sing "the...uhhhh" up the scale, feeling my tongue relaxed.
I was singing in a strenuous concert just two nights ago, and found that purposely clenching and releasing my butt was a great way to relax my legs - and teachers will tell you never to lock your knees, so there you go, there's a lot you can do from the waist down as well. But you probably knew about that...
One very specific thing I'll leave you with, from my life as a professional instrumentalist, is to find an Alexander Technique teacher you like (http://en.wikipedia.org/wiki/Alexander_technique). They can help you acquire an exquisite sense of your body and the way it carries itself through the slings and arrows of life - and there's some solid research behind why it works! Good luck to you, and in spite of all of this, never forget that, when you're performing, "you are the music, while the music lasts...".
Answer: Try vocalizing ascending scales, until you find when is it that you start getting too tense.
When you find this, try vocalizing slowly through the notes, emitting prolonged sounds on each of them and breathing properly between each note.
Practice this exercise several times a week, and you should get used to gliding through the notes pleasantly :)


Android Custom Array Adapter to read CSV files

Question: I am a newbie to android application development. I am currently working on a project which deals with the import of csv files which consists of only one column and many rows , onto my android project. I am able to read those csv files onto my project using csv adapters and array adapters and I didn't use any string arrays. Only used csvadapter and array adapters. Now in the list view where all the csv datas are presented, I am having a concern where when clicked on an item in the list I wanted to toast the item name. I tried out all possible combinations but it displays me only a toast saying string@somerandomvalue. Request someone to help me on this. Thanks in advance.
The following is my csvadapter class. The .csv files are in placed in assets folder..
public class CSVAdapter extends ArrayAdapter<clock>{
    Context ctx;
    public CSVAdapter(Context context,int textViewResourceId)
    {
        super (context,textViewResourceId);
        this.ctx = context;
        loadArrayFromFile();
    }
    @Override
public View getView(final int pos,View convertView,final ViewGroup parent){
    TextView mView=(TextView)convertView;
    if(null == mView){
        mView = new TextView(parent.getContext());
        mView.setTextSize(28);
    }
    mView.setText(getItem(pos).getTime());
    return mView;
}

And this is my class to read that .csv array into GUI
public class mrvtoparanur extends Activity {
CSVAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.mrvtoparanur);
      final ListView mList = (ListView)findViewById(R.id.mrvtoparanurlist);
      mAdapter=new CSVAdapter(this,-1);
      mList.setAdapter(mAdapter);
      mList.setOnItemClickListener(new OnItemClickListener()
      {
          @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            Toast.makeText(getApplicationContext(), "you selected item number"+arg2, Toast.LENGTH_SHORT).show();

          }});
}

Request someone to help on the Toast in the second class java file. In the msg "YOU SELECTED ITEM NUMBER" the arg2 gives the item id.. In a similar way i want to display or toast the item name instead of item ID. Pls help me someone
This is clock.java file... Please refer below.
 public class clock {
    private String t;

    public String getTime() {
        return t;
    }

    public void setTime(String t) {
        this.t = t;
    }
}

Answer: Use the data from the adapter:
clock clicked = mAdapter.getItem(arg2);

(Then I don't know the structure of the clock object)
Comment: hi..thanks for your immediate reply. But your code is giving me the following toast message  your selected item number com.mrvshuttle.clock@43e5b588 ..
Comment: According to your edit, you probably want to toast `clicked.getTime()`, basically like you did in the adapter.getView.
Comment: marvellous brother  ! Works like charm! A million thanks ! :D
Comment: now i have a small doubt. will i be able to split one single item from the array ? and also if i want to split that one item to each letter or number. Say the item has 11:23 .. i want to split 11 and 23 and save them in two different integer variables...can we do that ?
Comment: you can use `String.split()`: `String[] res = "11:23".split(":");` res[0] is "11" res[1] is "23". Then you need to use `Integer.parseInt(String)` on each value. `int hours = Integer.parseInt(res[0]); int minutes = Integer.parseInt(res[1]);`


PhpStorm - CSS files link to root of server and not project root

Question: Basically I'm trying to run a HTML file in PhpStorm on localhost.
My issue is the fact that my CSS file have paths relative to the root of the server (as they should) but in PhpStorm another folder is automatically added for the project.
In short, my CSS files link to:
localhost:port/css/style.css

While PhpStorm makes the location be:
localhost:port/projectname/css/style.css

How do I fix this?
Thanks!
-Jamie
Comment: @LazyOne
I'm fine with using the built in server. However obviously I want my CSS files to point relatively to the root of the server and not to the project folder (since the project folder is not gonna be on the real web server)
Comment: This `localhost:port/projectname` means that PhpStorm's own built-in simple web server is used. If you want to use your own server -- configure Deployment entry (`Settings | Deployment`) and mark it as Default for this project.
Comment: http://stackoverflow.com/a/24908091/783119
Answer: If you like to change the default web path on built-in web server, you have to re-configure the server by editing your system hosts file accordingly - see http://youtrack.jetbrains.com/issue/WEB-8988#comment=27-577559.


Making a button that creates an object and displays it when clicked

Question: I have a program that handles song objects with some fields and playlist objects that are arrays of the songs. I have a perfectly functioning java programming that does what I need it to do but I'm trying to convert it into an Android app and it's making me want to throw my computer out the window. I don't really know XML but I've gotten the basics such as creating buttons etc.
I have a button in the layout file that I implemented as follows:
<Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:text="@string/Button"
    android:onClick="newPlaylist"/>
<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button1"
    android:layout_below="@+id/button1" />

In my main file I have:
public void newPlaylist(View view){
    Playlist list1 = new Playlist("First Playlist");
    TextView first = (TextView) findViewById(R.id.textView1);
    first.setText(list1.getName());
}

Edit: I was able to add a little to the newPlaylist method. Now when I click the button it displays the name of the playlist, but I still want to edit it and be able to have multiple playlists on the screen to manipulate.
All I want to do is display the playlist name as either a text or label that is clickable so that the name can be changed and I can move on from here.
Answer: The Android documentation on the button component might help you with your problem.
I assume that your Playlist class looks something like this
public class Playlist {
    private String name;

    public Playlist(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

If it does, then your method for handling the button click should look like this.
public void newPlaylist(View view) {
    Playlist playlist = new Playlist("My First Playlist!"); // Create our playlist object
    // Since button is the only component that uses 'newPlaylist' as a click listener, the view will always be the button
    Button button = (Button) view; // We cast the view to button
    button.setText(playlist.getName()); // This edits the button text, might want to create a TextView for this
}


How to create an Array without knowing the length it will have

Question: I've got a problem to solve as follows:

Create a method that returns an array that contains only the positive values of another int[] a

I've kinda solved it by writing this method:
public static int[] soloPositivi(int[] a) {
    int[] pos = new int[a.length];
    int j=0;

    for (int i=0; i0) {
            pos[j] = a[i];
            j++;
        }
    }
    return pos;
}

of course when I test it using for example:
int[] a = new int[] {2,-3,0,7,11};

I get [2,7,11,0,0], because I set:
int[] pos = new int[a.length];

The question is, how do I get the pos array to have a modular length so that I can get [2,7,11], without having to use lists? I have to solve this problem by only using Arrays methods.
Comment: don't use an array and use a list?
Comment: This problem is meant to be solved only by using arrays and their methods... If I could have used lists I would have done it
Comment: Use `ArrayList` to add valid value, and then use `toArray()` method to `return` an array. https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Comment: You can look at the linked question - although some answers do mention using a list, others also suggests first computing the size of the array, and then creating it with this size.
Comment: There is also the possibility to improve the code with `Java8`:
 `int[] arr = new int[] {2,-3,0,7,11};`
 `int[] newArr = Arrays.stream(arr).filter(x -> x > 0).toArray();`

maybe this solution can also be added?
Answer: First, loop through and count the number of positive elements to know the length, then loop through again to copy.
public static int[] copyPositiveVals(int[] arr) {
    int count = 0;
    for(int x : arr) {
        if (x > 0) count++;
    }

    int[] arr2 = new int[count];
    int i = 0;
    for(int x : arr) {
        if (x > 0) {
             arr2[i] = x;
             i++;
        }
    }
    return arr2;
}

Comment: This should solve it, I didn't think about using two loops. Thanks
Comment: I think for the given problem using `Java 8` is much easier:
`int[] arr = new int[] {2,-3,0,7,11};`
`int[] newArr = Arrays.stream(arr).filter(x -> x > 0).toArray();`
Comment: @KevinWallis I'm sure yours is a good method too, but I'm quite new to java and I was looking for a moe beginner-friendly approach
Comment: @Daniele okay but maybe you also make yourself friendly with `java 8` lambda expressions they are quite cool and easy to use. Much more readable (fluent) than working with the default way :)


Enviar imagem em formulário com AJAX / PHP / MySQL

Question: Estou refazendo um formulário para um site do qual é necessário que eu envie uma imagem, porém não estou conseguindo fazer o upload e preciso da ajuda de vocês.
Já pesquisei e não consegui achar a resposta...
Função:
function fBlog_Send(){
$.ajax({
    type:"GET",
    url:"ad_BL_Include2.php",
    data:{
        nCategoryID:$('#nCategoryID-Include-Blog').val(),
        sTitle:$('#sTitle-Include-Blog').val(),
        sKeywords:$('#sKeywords-Include-Blog').val(),
        sDescription:$('#sDescription-Include-Blog').val(),
        sPicture:$('#sPicture-Include-Blog').val()
    },
    success:function(data){
        $('#blog-include').html(data);
    }
});

HTML:
<?php include "include_Connection.php" ?>

    <form id="adm-form">
        <fieldset>

                <select id="nCategoryID-Include-Blog">
                    <?php
                    $sQuery = "SELECT * FROM tcategory";
                    $rRecord = mysqli_query($sConn, $sQuery);
                    while($rRow = mysqli_fetch_assoc($rRecord)){
                        ?><option value="<?php echo $rRow["nID"];?>"><?php echo $rRow["sDescription"];?></option><?php
                    };
                    ?>
                </select>

                <input type="text" id="sTitle-Include-Blog" placeholder="Título">

                <input type="text" id="sKeywords-Include-Blog" placeholder="Referência">

                <textarea id="sDescription-Include-Blog" placeholder="Descrição"></textarea>

                <input type="file" id="sPicture-Include-Blog" placeholder="Imagem" class="image" />

        </fieldset>
    </form>

PHP:
<?php include "include_Connection.php" ?>
<?php
session_start();
$nUserID_                               = $_SESSION["SS_nUserID"];
if(isset($_GET['nCategoryID'])){
    $nCategoryID_                       = strtolower($_GET['nCategoryID']);
}else{
    $nCategoryID_                       = "";
}
if(isset($_GET['sTitle'])){
    $sTitle_                            = strtoupper($_GET['sTitle']);
}else{
    $sTitle_                            = "";
}
if(isset($_GET['sKeywords'])){
    $sKeywords_                         = strtoupper($_GET['sKeywords']);
}else{
    $sKeywords_                         = "";
}
if(isset($_GET['sDescription'])){
    $sDescription_                      = strtoupper($_GET['sDescription']);
}else{
    $sDescription_                      = "";
}
if(isset($_FILES['sPicture']['name'])){
    $sPicture_                          = $_FILES['sPicture']['name'];
}else{
    $sPicture_                          = "";
}
$dDate_                                 = date("Y-m-d");
if($_FILES['sPicture']['name'] <> ''){
    if(move_uploaded_file($_FILES['sPicture']['tmp_name'], $sPath.'Original/'.$_FILES['lURL1']['name'])){
        $sImg = imagecreatefromjpeg($sPath.'Original/'.$_FILES['sPicture']['name']);
        $nWidth = imagesx($sImg);
        $nHeight = imagesy($sImg);
        $nWidth_tmp = 480;
        $nHeight_tmp = 360;
        if($nWidth > $nWidth_tmp || $nHeight > $nHeight_tmp){
            if($nWidth < $nHeight){
                $nImageWidth = round(($nWidth * $nHeight_tmp) / $nHeight);
                $nImageHeight = $nHeight_tmp;
            }elseif($nWidth > $nHeight){
                $nImageWidth = $nWidth_tmp;
                $nImageHeight = round(($nHeight * $nWidth_tmp) / $nWidth);
            }else{
                $nImageWidth = $nWidth_tmp;
                $nImageHeight = $nHeight_tmp;
            }
        }else{
            $nImageWidth = $nWidth;
            $nImageHeight = $nHeight;
        }
        $nImg_ = imagecreatetruecolor($nImageWidth, $nImageHeight);
        imagecopyresampled($nImg_, $sImg, 0, 0, 0, 0, $nImageWidth, $nImageHeight, $nWidth, $nHeight);
        $sPath_ = $sPath."Zoom/".$_FILES['sPicture']['name'];
        imagejpeg($nImg_, $sPath_);

        $sImg = imagecreatefromjpeg($sPath.'Original/'.$_FILES['sPicture']['name']);
        $nWidth = imagesx($sImg);
        $nHeight = imagesy($sImg);
        $nWidth_tmp = 120;
        $nHeight_tmp = 90;
        if($nWidth > $nWidth_tmp || $nHeight > $nHeight_tmp){
            if($nWidth < $nHeight){
                $nImageWidth = round(($nWidth * $nHeight_tmp) / $nHeight);
                $nImageHeight = $nHeight_tmp;
            }elseif($nWidth > $nHeight){
                $nImageWidth = $nWidth_tmp;
                $nImageHeight = round(($nHeight * $nWidth_tmp) / $nWidth);
            }else{
                $nImageWidth = $nWidth_tmp;
                $nImageHeight = $nHeight_tmp;
            }
        }else{
            $nImageWidth = $nWidth;
            $nImageHeight = $nHeight;
        }
        $nImg_ = imagecreatetruecolor($nImageWidth, $nImageHeight);
        imagecopyresampled($nImg_, $sImg, 0, 0, 0, 0, $nImageWidth, $nImageHeight, $nWidth, $nHeight);
        $sPath_ = $sPath."Thumb/".$_FILES['sPicture']['name'];
        imagejpeg($nImg_, $sPath_);

        $sInsert = "INSERT INTO tpicture(nPhotoID, lURL, sDescription) VALUES ('$nPhotoID', '$lURL1', '$sDescription1')";
        mysql_query($sInsert);
    }
}
mysqli_query($sConn,"INSERT INTO tblog(nUserID,nCategoryID,sTitle,sKeywords,sDescription,dDate,sPicture) VALUES('$nUserID_','$nCategoryID_','$sTitle_','$sKeywords_','$sDescription_','$dDate_','$sPicture_')");
?>

Comment: Qual é o erro que você está tendo ? É na hora de salvar a imagem ? A imagem chega até o servidor ?
Comment: Creio que [este link](http://pt.stackoverflow.com/questions/9704/fazer-upload-de-arquivo-com-ajax) possa te ajudar.
Comment: Marabesi, a imagem não chega no servidor... O erro diz que que a variavel sPicture está indefinida na linha 31, que é a linha: **if($_FILES['sPicture']['name'] <> ''){** do arquivo PHP, ou seja, no meu entendimento ele não está passando as veriaveis como arquivo pelo ajax!
Comment: Daniel, nada disso que você mencionou dá erro, fiz todos os testes e estão funcionando corretamente.
Answer: PRIMEIRO: O erro em session_start();, acontece por que o cabeçalho já foi chamado antes, ponha essa função antes do cabeçalho.
SEGUNDO: Todo formulário que realiza upload de imagens deve vir com o seu enctype especificado para: enctype="multipart/form-data" e ponha o method="get".
TERCEIRO: sobre o erro Undefined Variable, o que pode está acontecendo que nenhuma das suas condições está definindo um valor para $_FILES['sPicture']['name']. Uma solução cabível seria tratar melhor as informações, algo parecido com isso:
<?php

if(isset($_POST['submit'])){ //ponha um name para seu submit
   $name = $_FILES["sPicture"]["name"];  //ponha um name para seu type="file"
   $tmp_name = $_FILES['sPicture']['tmp_name'];

    if (isset ($name)) { //Caso não seja null
        if (!empty($name)) { //Caso não seja vazio

           //Aqui ficaria seu código para a o upload

        } //fim do empty
    } //fim do isset
} //fim do submit
?>

Pronto! faça tudo isso e retorne uma resposta aqui.
Comment: Ok, alterei o Session (Porém não havia msg de erro no Session!)... Mas o seu exemplo acima daria exemplo se eu não estivesse utilizando AJAX, quando eu uso AJAX e passo as variaveis primeiro para uma função AJAX e depois para um PHP, o PHP não está identificando que a variavel sPicture contém um arquivo!
Comment: O meu exemplo foi somente um complemento ao seu formulário e condições, somente com isso você não fará nada. `Só fiz identificar pequenas falhas no seu código que podem está gerando os erros. Você acrescentou o `enctype` e `method` ao form? Nem um `name` o seu `input file` tinha
Comment: Na realidade eu mudei um pouco o foco, acabei utilizando um iframe no local!
Comment: De qq forma obrigado pela ajuda!


Drupal 7 - Profiles 2 Module - Share profile data or migration

Question: I'm making a platform for 2 types of users:free and paid.
The issue I encounter is the data of the users when updating from one profile to another.
If the user has "free" profile he gets some fields, but when updating the "paid" profile has the same fields+extra.
I first thought of showing the "paid" fields as an extra to the "free" (so the users with "paid" profile have both "free" and "paid" profiles assigned to them), but the issue appears when the user wants to create the profile directly paid as he has no option completing the "free" ones only after he has registered.
Is there any way to make the fields autopopulate (when completing the "field_1" in "free" the data to apear in "field_1" in paid)?
Or to make the data viewable cross multiple profile types?
Conclusion:I need a way for the data to ve visible cross profiles
Answer: I think you can use a hook_form_alter() to add visibility conditions on your user_profile_form elements :
Add these kind of attributes on field you want to hide for free users :
'#states' => array(
   'visible' => array(
      ':input[name="field_1"]' => array(
         array('value' => 'paid'),
     ),
   ),
),


Google Sheets API extreme latency

Question: I am experiencing a median latency of over 40s on google.apps.sheets.v4.SpreadsheetsService.GetValues function. I am reading single sheet of data with 250,000 cells (14 cols x 18,000 rows). I am well under the rate limits rarely doing more than a single call in 100s and more than 200 a day.
When downloaded as CSV, the file size is ~3MB (440KB zipped).
Now, I understand that reading 3MB of data might not be instant, but 40s is order of magnitude slower than I would expect. Especially given that simple manual download as CSV takes ~1s to complete.
Am I doing something wrong? Is there a way to get data through API faster?
Example of the code I am using
  async function load(id, range) {
    await sheetsApi.spreadsheets.values.get({
      spreadsheetId: id,
      range,
      valueRenderOption: 'UNFORMATTED_VALUE',
    })
  }

  await Promise.all([
    load(id1, 'Big'), // big 250k cells sheet
    load(id1, 'Small'), // small 1000 cells sheet
    load(id2, 'Big'), // another big 250k cells sheet
  ])

Playing further with profiling I am seeing following data:
[0] Loading id2:Big took 1644ms.    // Notice how this big sheet loaded really fast.
[0] Loading id1:Small took 26345ms. // Notice that this small sheet took 26 seconds.
[0] Loading id1:Big took 27274ms.
[0] Loading id1:Small took 859ms.
[0] Loading id2:Big took 1493ms.
[0] Loading id1:Big took 1610ms.
[0] Loading id1:Small took 865ms.
[0] Loading id2:Big took 1689ms.
[0] Loading id1:Big took 1835ms.

So it seems like some kind of undisclosed rate limiting or whatever. Sometimes it's really fast, sometimes it's extremely slow.
Comment: In your script, it seems that 3 API calls are done by the method of spreadsheets.values.get, so how about doing them by one API call using the method of spreadsheets.values.batchGet?
Comment: @Tanaike thanks for suggestion, it's only 2 API calls (the third is to different spreadsheet). Frankly, it's a natural optimisation, but I don't really see it having big impact. The second sheet is pretty small.
Comment: Thank you for replying. I apologize that my comment was not useful for your situation.
Answer: If it's feasible for your situation, could you download the entire sheet as a CSV file, or 3 of them, 1 per sheet.  It's probably a lot slower for the API to filter the data rows individually out into API call results and serialize them, rather than export the whole sheet(s) to a file.
Comment: Is there a way to download sheet to CSV using API?
Comment: @SamuelHapak I don't think so, I think you need to use the Google Drive API.

Google Sheets API extreme latency


"WARNING, putname undefined" when complie my kernel module

Question: I was writing a kernel module that will check some thing in VFS . In this module, I need to use the kernel API "putname" which is defined as:
<code>#ifdef CONFIG_AUDITSYSCALL
void putname(const char *name)
{
if (unlikely(!audit_dummy_context()))
    audit_putname(name);
else
    __putname(name);
}
EXPORT_SYMBOL(putname);
</code>
When I complied it in Fedora 18 with kernel 3.6.10, Everything is OK, the module works fine, but when I switch it to kernel 3.11.4. The complier gave me a warnning "putname is undefined", When I replace "putname" with "__putname", the kernel module can be complied but when it was running, something will go wrong. the backtrace shows that it was in __putname. Is there anybody can help me on this issue?
Thanks
Answer: See the commit #91a27b2a756784714e924e5e854b919273082d26 from Jeff:

This patchset converts the getname()/putname() interfaces to return a struct instead of a string. For now, the struct just tracks the string in kernel space and the original userland pointer for it.

The interface was changed right after the v3.6. So you have to rework your code taking this change into account.
Comment: I understand that the interface was changed, however I am trying to get a ``struct filename *`` by using ``getname()``, but the compiler throws the same error as the original question poses.


Showing that $(2^a - 1)\bmod (2^b - 1) = 2^{a \; \bmod \; b} - 1 $

Question: I've been thinking on this proof for two days. I'm stuck.

Show that,
  $$ (2^a - 1)\bmod (2^b - 1) = 2^{a \! \! \mod b} - 1 $$
  where $a,b \in \mathbb{Z}^+$.

I would be happy if someone can help me.
Thanks.
Answer: If you are working modulo $2^b-1$, you have $$2^b \equiv 1 \pmod{2^b-1}.$$
Suppose that $a=nb+c$.  (That is, $a \equiv c \pmod{b}$.)  Then you can simplify
$$2^a = 2^{nb+c} = (2^b)^n\cdot 2^c \equiv 1^n\cdot 2^c \pmod{2^b-1}.$$
The result you are looking for follows by subtracting 1 from both sides.
Answer: Divide $a$ by $b$ with remainder, $a = kb + r$ with $0\leq r\lt b$. Then
dividing $x^a-1$ by $x^b-1$ gives
$$x^a-1 = (x^b-1)(x^{a-b} + x^{a-2b} + \cdots + x^{a-kb}) + (x^{a-kb} - 1).$$
Notice that $r=a\bmod b$ and that $a-kb = r$.
Now evaluate at $x=2$, and check to make sure that everything still works out over the integers.
Comment: Sincere thanks to the downvoter for the insightful comments that help me understand what is not useful about this answer.
Answer: Since $0\leq 2^{a\mod b} - 1 < 2^b - 1$, your question is equivalent to proving that
$$2^a - 1 \equiv 2^{a\!\!\mod  b} - 1$$
where the $\equiv$ symbol means that both sides have the same remainder when divided by $2^b-1$. This can easily be show using the properties of modulus:
$$2^a -1 = 2^{a\mod b}2^{b\lfloor a/b\rfloor} - 1\equiv 2^{a\mod b}(2^{b\lfloor a/b\rfloor}\bmod (2^b-1))  - 1\equiv 2^{a\mod b}  - 1$$
which works because the integers $\bmod (2^b-1)$ form what is called a "ring", allowing addition and multiplication to be performed on them. The last $\equiv$ is because $2^{b}\equiv 1$ so $2^{b\lfloor a/b\rfloor}\equiv 1^{\lfloor a/b\rfloor} \equiv 1$.
Answer: I have another approach which I think it should be easier.
We must prove that $2^a-1 \equiv 2^{a mod b}-1 \pmod{2^b-1}$
Thus, We should prove
$$2^a \equiv 2^{a mod b} \pmod{2^b-1}$$
Proof: Using dividing algorithm, we have:
$a = bq + r$ then $r = a - bq$
Thus we have: $2^a \equiv 2^r \pmod{2^b-1}$ then $2^a \equiv 2^{a - bq} \pmod{2^b-1}$
Now if multiply both sides of the congruence to $2^{br}$ we have:
$$2^a * 2^{bq} \equiv 2^a \pmod{2^b-1}$$
We know that $gcd(2^a, 2^b-1)=1$ (because $2^a$ is even and $2^b-1$ is odd), so we can divide both sides of the congruence by $2^a$, so we have:
$$2^{bq} \equiv 1 \pmod{2^b-1}$$
From the definition of congruence we have:
$$2^b-1 | 2^{bq}-1$$
We know that $2^{bq}-1 = (2^b-1)(2^{b(q-1)} + 2^{b(q-2)} + ... + 2^b + 1)$
Thus we have:
$$2^b-1 | (2^b-1)(2^{b(q-1)} + 2^{b(q-2)} + ... + 2^b + 1)$$
Which is trivial.
So we reached a trivial and thus all of the conclusions are reversible, then the proof is done.


mod_rewrite for WAMP alias?

Question: I am using WAMPServer2 for my php framework Nette.
I first copied its folder directly into www folder of WAMP. I enabled mod_rewrite module, and I have set every AllowOverride All. Everything functioned perfectly.
My problme is, than, becouse multiple project, I created alias for same project. Now, routing inside Nette framework doesent work, becouse mod_rewrite doesent. I believe there is some extra setting for Aliases. I tried to found something, but unsuccesfully. I have only little experience with modyfying apache settings. Is there a way to get it working? Thanks.
Answer: I had trouble with this mod_rewrite and an alias directory in WAMP today. The solution was to set RewriteBase in the .htaccess of the alias directory.
The solution is to set
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /aliasdirectory/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Comment: Thank you! I was using an alias for a Yii project and was stuck on the rewrite forever.  RewriteBase was just what I needed!
Comment: what should I put instead of 'aliasdirectory' ?
Comment: @user1406269 the actual directory name from your filesystem.
Answer: This might be an old question, but my solution was as follows:
I didn't want to mange with .htaccess RewriteBase since the same file was used in production environment, where RewriteBase would need to be changed.
Instead of creating Apache alias I created a Windows symbolic link.
Instead of Apache directive
Alias /<alias> /<path>/<to>/<alias>/<dir>

I went to current webroot dir and createad
mklink /d <alias> /<path>/<to>/<alias>/<dir>

And don't need to change any other configuration (I am not sure in which directory path fall permissions).

mod_rewrite for WAMP alias?


Homeomorphism from $P^2\mathbb{R}$ onto the image of $\mathbb{S}^2$ through the Veronese map

Question: Consider the map $v \colon \mathbb{S}^2 \to \mathbb{R}^6$ defined by
$$ v(x, y, z) = (x^2, y^2, z^2, \sqrt{2}xy, \sqrt{2}yz, \sqrt{2}zx) $$
Furthermore, let $ M := v(\mathbb{S}^2) $ and $P^2\mathbb{R}$ denote the projective plane.
I want to show that the map $v$ defines a homeomorphism $V$ from $P^2\mathbb{R}$ onto $M$.
Well, I know that $P^2\mathbb{R} \cong {\mathbb{S}^2}/{\sim}$ where $(x, y, z) \sim (-x, -y, -z)$. If I somehow manage to prove that $M \cong {\mathbb{S}^2}/{\sim}$, it'd be neat.
Comment: What if you write $$v: \mathbb{S}^2/\pm 1 \to \mathbb{R}^6$$
Comment: I managed to reduce the problem.
By the universal property of the quotient space, $v$ naturally induces a continuous map $V$ on $M$. This is because for any $p \in \mathbb{S}^2$, we note that $p \sim -p \Rightarrow v(p) = v(-p)$. Furthermore if I manage to prove (i) that V is injective, then by noting that $P^2\mathbb{R}$ is compact, as is the image under the continuous canonical projection of a compact, and (ii) $M$ is submanifold of $\mathbb{R}^6$ and hence Hausdorff, I conclude that V is a homeomorphism.
So right now I'm left with proving (i) and (ii), which I'm struggling at doing so.
Comment: @LefebvreLea You do not need to know that $M$ is a submanifold of $\mathbb R^6$ (it is one, but is irrelevant here). In fact **each topological subspace** of $\mathbb R^6$ is Hausdorff.
Answer: No idea why you are complicating this way. $v$ is continuous bijective $\Bbb{S^2/\pm 1}\to v(\Bbb{S}^2)$ and $w:[x:y:z]\to \pm (\frac{x}{\sqrt{x^2+y^2+z^2}},\frac{y}{\sqrt{x^2+y^2+z^2}},\frac{z}{\sqrt{x^2+y^2+z^2}})$ is continuous bijective $\Bbb{P^2(R)\to S^2/\pm 1}$. The composition of both is your homeomorphism:
The inverse of $w$ is obviously continuous, for the inverse of $v$ I would say that $v^{-1}$ gives a continuous function $v(\Bbb{S}^2)\to \Bbb{S^2}/(\pm 1,\pm 1,\pm 1), (a,b,c,d,e,f)\to (\pm\sqrt{a},\pm\sqrt{b},\pm\sqrt{c})$ which implies that $v^{-1}$ is itself continuous.
Comment: I wouldn't say I'm complicating whatsoever. I just wanted to provide a topological argument instead of constructing tedious inverses. Thanks though
Answer: Obviously $v(x,y,z) = v(-x,-y,-z)$. Thus $v$ induces $V : P^2\mathbb R\to \mathbb R^6$  such that $V(P^2\mathbb R ) = M$. Now let us explore what $v(x,y,z) = v(x',y',z')$ means. The first three coordinates show that $x' = (-1)^a x, y' = (-1)^b y, z'= (-1)^c z$ with $a, b, c \in \{0,1\}$. Coordinate no. 4 shows $a = b$, coordinate no. 5 shows $b = c$ and coordinate no. 6 shows $a = c$. Thus $(x,y,z) = \pm (x',y',z')$, i.e. $V$ is injective. Hence $V : P^2\mathbb R \to M$ is a continuous bijection. Since $P^2\mathbb R$ is compact and $M$ is Hausdorff, the map $V$ is a homeomorphism.
Comment: That makes complete sense, thank you. I wasn't sure what the injectivity of $V$ meant.
How do you know beforehand that $M$ is Hausdorff though? I actually have to prove it is a submanifold of $\mathbb{R}^6$, because then I could assume it is Hausdorff, since in my class we're treating smooth manifolds as Hausdorff spaces (although not all smooth manifolds are Hausdorff).
Comment: @LefebvreLea $M$ is a subspace of $\mathbb R^6$ which is Hausdorff.


Complex numbers and quadratic

Question:
If $\alpha,\beta$ are roots of $t^2-2t+5=0,(a+1)/2=\cot\phi$ then show
$$((a+\alpha)^n-(a+\beta)^n)/(\alpha-\beta)=
2^{n-1}\operatorname{cosec}^n(\phi)\sin(n\phi)$$

My try was to put values of sum, difference and $a$.
I got
$$2^n\operatorname{cosec}^n(\phi)(\cos(n\phi) \pm i\sin (n\phi)-\sin^n(\phi))/(\pm4i)$$
I can't go any further, can anyone help please?
I found $\alpha,\beta$ and $a$ from the relation substituted it and used De Moivre
Comment: You have been around for seven months. Haven't you yet noticed that you are supposed to use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) around here?
Comment: I'm afraid I downvoted this post for the reason that José describes. If you edit your post, then please let me know, and I will remove the downvote. You should also include more detail about what you have tried.
Comment: I am trying but unable to understand math jax.i have tried to edit sorry for breaking rules
Comment: Thanks a lot , thank i ll learn mathjax straight away
Answer: $$t=1\pm2i$$
WLOG $\alpha=1+2i,\beta=?\implies\alpha-\beta=?$
$$a+\alpha=2\cot\phi-1+1+2i=\dfrac{2(\cos\phi+i\sin\phi)}{\sin\phi}$$
Using Review of a proof for De Moivre's theorem using mathematical induction to find $$(a+\alpha)^n$$
Similarly find $$(a+\beta)^n$$
Comment: (b+α)  should actually be (a+β).
Comment: @Guji2203, Thanks

Complex numbers and quadratic


The level of knowledge needed for graduate study

Question: I was in class, and I saw a grad student reel off a proof of a theorem in real analysis, one I found quite hard and never really tried to understand thoroughly, with no effort.
This led me to ask the question: at what level should I know the material I learn in my math classes?
In particular, if I want to go to graduate school, what standard should I hold myself up to? Should I be able to reproduce proofs of all of the main theorems from scratch on a whiteboard, completely understanding the all of the techniques used?
This is not really a standard enforced by the coursework, which requires knowledge of the statements of the theorems and some problem solving ability.
So the question really is: should I come out of undergrad understanding not just the statements of the results in class, but also the proofs?
Also, from personal experience, does taking this approach to studying help one solve mathematical problems?
Comment: I think that you must take a look at your past... I mean, in my short and non-professional experience with math, through time, Im able to understand things that some time ago it seems to me very complicated.
Comment: I don't want to write a whole answer for this, but the just answer your questions:

No, you don't have to memorize proofs of major theorems to go to grad school, nor would it really be recommended. Being able to prove those things comes from practice of proving things in general, which should be part of the curriculum for undergrads and graduates alike. Most mathematicians that don't teach/research in real analysis can't rattle off a proof to many theorems in real analysis, though they may be able to construct a proof for it with some thought.
Answer: There are lots of ways to partition one's mathematical ability into stages to gauge your progress and readiness for something deeper. The stages are not strictly partitioned, so it is possible to kind of move back and forth between different stages, and you may be at different stages with different areas of study. Here is one such way that applies in this context.
In the first stage, one learns how to compute. There is no theory, no generalities. There are numbers, equations, matrixes, etc, and at this point, the student's sole job is to get good at moving them around. This is the portion of your mathematics upbringing from when you were a small child learning to count, up through whenever you started doing serious mathematics.
In the second stage, you learn what proof is and how to construct them. You learn how to prove standard theorems, and every class you take will prove every theorem, except possible for some very difficult ones that are outside the class. You are expected to learn how these proofs go and how they relate to one another, and maybe even are asked to reproduce them. Most people do this for pretty much all of undergraduate.
In the third stage, instead of learning proofs, you now learn proof techniques. By having a large swath of ideas at your disposal, you no longer need to see every detail of a proof to know how it works (unless it's really technical). When you see a theorem, you don't just rattle off the steps of the proof you have memorized. You think about what kinds of ingredients go into the proof, and you stitch them together. This is not to say that you will be able to reproduce every theorem you ever learned flawlessly - of course people forget things all the time - but it means that knowing what you know about the subject, you can rediscover and reassemble the proof on the fly, even if it means you trip from time to time.
I would say that in all probability from your question, you are in the second stage, and asking about what it means to go into the third stage. Do you have to know every single argument to every theorem to be a good mathematician? No, of course not. Learning every proof to every theorem would take years, and you would never get to advance. On the other hand, the only way to get from the second stage to the third stage is to learn as many proofs as you can, and to analyze them thoroughly. Find their crucial steps, the fundamental things that hold them together, and reflect on them. Then, advancing to the third stage is all about looking for ways to use those fundamental observations for other problems.
Hope this helps!
Answer: I believe so. Also, understanding the proofs is essential to really understanding the material. I would look at Calvin Newport's blog post on how he got the highest grade in his discrete math course. It was essentially this: understanding each and every proof.
Answer: As a first pass answer, what grade do you think you'll be receiving in the course you mentioned? If you're on track for an A, then presumably the professor thinks you are learning the material at a required level. Similarly, a graduate school would look at the grades you have received as one indicator of your ability to graduate-level mathematics.
As another consideration, you are probably equally fantastical to a Calc I student---How did you take the derivative that fast?! How did you possibly memorize the Mean Value Theorem?! The graduate student you mention has had the benefit of studying this material for much longer and has been better able internalize theorems and proofs that seem dense to you.
Beating the example of the Mean Value Theorem into the ground using the lens of Terry Tao's excellent article, a progression of understanding might go like:

Calc I student: No idea what this means, it's a "totally obvious fact." Use it to get the answer in the back of the text, maybe some analogies with speedometers or something?
First analysis course student: Can produce an $\epsilon$ - $\delta$ proof given the exact statement, can (laboriously) construct counter-examples when various hypotheses are removed.
Grad student: Something about average rate of change and derivatives; remembers that it's a consequence of Rolle's Theorem and has a relationship to Lipschitz continuity. Draw a convincing picture and reverse engineer the hypotheses. Turn the convincing picture into a rigorous proof if desired.

As a closing thought, memorizing difficult proofs verbatim is a terrible use of time. Instead, study them to learn how the proof is structured, why each of the hypotheses is necessary, and how the theorem fits into the general mathematical landscape. For my own studies, I would rarely memorize exact statement of a  theorem and proof. Instead, I focus on learning what makes that theorem tick---what other theorems/lemmas/definitions does it rely on? What other theorems depend on it? What's the structure of the "standard" proof---induction / contradiction / split into cases / ... ? Can I build simple counter-examples if any of the hypotheses are removed?
Comment: Haha nice progression. Here's another grad student 'way' to prove the MVT: A continuous function on a closed bounded interval has a graph which is a compact set, so there is a point on the graph that is furthest from the secant line between the two endpoints, because a continuous function on a compact set has a maximum. Translating the secant line to that point gives a tangent, so that's the desired point **even if** we discard the condition of differentiability but ask for just a tangent. =)
Comment: What I meant was less "memorize verbatim" and more "understand every aspect of the proof" - I imagine questions my professor might ask me if he were trying to see if I understood, and if I can answer, then I consider myself to have understood it. The question was (a). Should I consider this type of understanding neccesary (b). Is this type of understanding useful? Thank you for the link to the article, I found it useful, and of course, your response.
Comment: Sounds like you're on the right track---being able to ask yourself questions about a theorem is a huge skill. Rattling off a proof to a theorem you have only recently been exposed to is probably unrealistic (unless it is a particularly easy proof that flows from previous theorems / definitions). That being said, this sort of ability will come as you gain experience.
Comment: @user21820 =) And why stop there? Might as well get some Heine-Borel and Hausdorff distance in there as well, maybe even a casual mention of Baire Categories in case the thesis advisor is nearby =)


Simulate random variables with "inner" and "outer" correlation

Question: Let us say we have data grouped in $m$ different classes, each of size $n_j$ for $j = 1,...,m$. We denote as $X_k^{(j)}$ the $k$-th member of group $j$. We want to simulate unit-variance random variables with a structure such that the "inner" correlation in group $j$ is $\rho_j$, and the "outer" correlation between groups $j$ and $i$ is $\rho_{ij}$, with the $\rho$'s as parameters. This is,
$$
\begin{aligned}
Var(X_k^{(j)}) &= 1 \quad \forall k,j \\
Cov(X_k^{(j)}, X_r^{(j)}) &= \rho_j \quad \forall k \neq r, j = 1,...,m\\
Cov(X_k^{(j)}, X_r^{(i)}) &=\rho_{ij} \quad \forall i\neq j, k\neq r
\end{aligned}
$$
Basically, I have grouped data and want to create a relationship structure both inside the groups and between the groups. I have tried approaching the problem by using the Gaussian copula and establishing
$$
X_k^{(j)} = \sqrt{\beta_j}\, Z + \sqrt{\rho_j - \beta_j} \, Z_j + \sqrt{1-\rho_j} \, e_k^{(j)}
$$
assuming both inner and outer correlations are positive, with $Z, Z_j, e_k^{(j)}$ i.i.d. $N(0,1)$. However, one finds that
$$
\beta_i \beta_j = \rho_{ij}^2
$$
which I believe is not generally solvable, given there are more equations than variables. I even used non-linear optimization techniques to try and find an approximate solution, without luck (cannot approximate each $\rho_{ij}$ appropriately).
I would like to know if there is any literature regarding this kind of problems or models, or if it is even possible. Even though $\rho_j$ seem to be always positive in my data, I would like the model to be as flexible as possible.
Comment: This would be easier to answer with more description of the variables. Maybe the groups are teams and you're looking at the correlation of offensive and defensive contributions? Right now I just see a jumble of subscripts and superscripts.
Comment: Yes this will most likely not work and you will have to deal with positive definiteness as well. You should search for "hierarchical copulas" there is quite a literature on this topic.
Comment: I am trying to simulate loss distributions for credit portfolios of different size. Each portfolio $j$ has $n_j$ credits, and each credit has an inner correlation (inside the portfolio) and outer correlation (with the rest of the portfolios). The final goal is to simulate the loss distributions with given inner and outer correlations. Hence, generate r.v.'s with such structure.
Answer: I found an answer, which was easier than expected, using factor models for credit risk. Given $m$ groups each with $n_j$ members, for $j=1,...,m$, we define
$$
X_k^{(j)} = \sqrt{\rho_j}Z_j + \sqrt{1-\rho_j}e_k^{(j)}
$$
for $k=1,...,n_j$, where $e_k^{(j)}$ are i.i.d. for each and all $k$ and $j$, and independent of $Z_j$ (idiosyncratic noise). Moreover, $\pmb{Z}= (Z_1,...,Z_m)\sim N(0, \Sigma)$ where the entries of $\Sigma$ are given by
$$
(\Sigma)_{ij} = \frac{\rho_{ij}}{\sqrt{\rho_i \rho_j}}.
$$
Thus, note that $E[X_k^{(j)}] = 0$ and $Var(X_k^{(j)}) = 1$, given the independence of $Z_j$ and $e_k^{(j)}$. Moreover, given the linearity of the normal distribution, $X_k^{(j)} \sim N(0,1)$.
For the correlations, note that (we obviate subindexes for they are not necesarry)
$$
\begin{aligned}
Corr(X^{(i)}, X^{(j)}) &= Cov(X^{(i)}, X^{(j)}) \quad \text{(Unitary variance)} \\
&= Cov(\sqrt{\rho_i}Z_i + \sqrt{1-\rho_i}e^{(i)},\sqrt{\rho_j}Z_j + \sqrt{1-\rho_j}e^{(j)}) \\
&= \sqrt{\rho_i}\sqrt{\rho_j}Cov(Z_i, Z_j) \quad \text{(Linearity of $Cov$ and ind.)} \\
&= \sqrt{\rho_i}\sqrt{\rho_j}(\Sigma)_{ij} \\
&= \sqrt{\rho_i}\sqrt{\rho_j}\frac{\rho_{ij}}{\sqrt{\rho_i \rho_j}} \\
&= \rho_{ij}
\end{aligned}
$$
as required. When both the variables are from the same group, we just get $Corr(X^{(j)}, X^{(j)}) = \rho_{jj}$ so we can establish $\rho_{jj} = \rho_j$ w.l.o.g.. In fact, one can prove that $\pmb{X} = (X_1^{(1)},X_2^{(1)},...,X_{n_1}^{(1)},X_1^{(2)},..,X_{n_m}^{(m)})$ the whole vector of $n = \sum_j n_j$ variables is multivariate normal.
Therefore, to simulate such a $\pmb{X}$ one can just construct the whole covariance matrix of size $n$ and simulate a multivariate normal from that (which is cumbersome given that $n$ is large in our application), or you could use the approach above and simulate an $m$ sized vector for $\pmb{Z}$ with covariance matrix $\Omega$, and $n$ i.i.d. $N(0,1)$. We have found that, for our application, the later approach is much faster given that $n$ is in the millions and $m$ around 10.


Trouble with backslash characters and rsyslog writing to postgres

Question: I have rsyslog 4.6.4 configured to write mail logs to a PostgreSQL database.  It all works fine, until the log message contains a backslash, as in this example:

Jun 12 11:37:46 dc5 postfix/smtp[26475]: Vk0nYDKdH3sI: to=<-----@----.--->, relay=----.---[---.---.---.---]:25, delay=1.5, delays=0.77/0.07/0.3/0.35, dsn=4.3.0, status=deferred (host ----.---[---.---.---.---] said: 451 4.3.0 Error writing to file d:\pmta\spool\B\00000414, status = ERROR_DISK_FULL in "DATA" (in reply to end of DATA command))

The above is the log entry, as written to /var/log/mail.log. It is correct.  The trouble is that the backslash characters in the file name are interpreted as escapes when sent to the following SQL recipe:
$template dcdb, "SELECT rsyslog_insert(('%timereported:::date-rfc3339%'::TIMESTAMPTZ)::TIMESTAMP,'%msg:::escape-cc%'::TEXT,'%syslogtag%'::VARCHAR)",STDSQL
:syslogtag, startswith, "postfix" :ompgsql:/var/run/postgresql,dc,root,;dcdb

As a result, the rsyslog_insert() stored procedure gets the following value for as msg:

Vk0nYDKdH3sI: to=<-----@----.--->, relay=----.---[---.---.---.---]:25, delay=1.5, delays=0.77/0.07/0.3/0.35, dsn=4.3.0, status=deferred (host ----.---[18.104.22.168] said: 451 4.3.0 Error writing to file d:pmtaspoolB

The \p, \s, \B and \0 in the file name are interpreted by PostgreSQL as literal p, s, and B followed by a NULL character, thus early-terminating the string. This behavior can be easiily confirmed with:
dc=# SELECT 'd:\pmta\spool\B\00000414';
   ?column?
--------------
 d:pmtaspoolB
(1 row)

dc=#

Is there a way to correct this problem? Is there a way I'm not finding in the rsyslog docs to turn \ into \\?
Answer: First, you should REALLY be using parameterized queries & prepared statements when passing arbitrary strings.
(This probably isn't your fault -- rsyslog is almost certainly responsible for that horror).
If you can't switch to a better query structure the Postgres encode function can probably help you out (see the documentation here) -- Specify an encoding of escape and Postgres will conveniently double all your backslashes in the string you pass to it.

Note that if you're feeling particularly pedantic you can enable standard_conforming_strings, which makes Postgres treat the \ character in a string as a literal backslash rather than its historical (unix-y) behavior of treating it as an escape character.
Whether such a change is viable in your environment depends on a lot of factors...
Comment: I tried your `encode()` suggestion, but the input is escape-processed too soon. The end result is the same.  `standard_conforming_strings` seems to be a reasonable solution. It's unfortunate that with rsyslog I can't just set that as a session variable. But in my case, it should work to make it system-wide without much fallout.  Thanks for the suggestions.
Comment: To limit fallout I believe you can set it on a per-database level (`ALTER DATABASE foo SET standard_conforming_strings=true`) -- never tried this myself, but there's [a promising Postgres mailing list post about it](http://archives.postgresql.org/pgsql-general/2006-07/msg01007.php)


Is paired t test sufficient to show the two data sets are similar

Question: Let me give the details of my problem setting, we have a learning algorithm that can take a collection of algebra problems and automatically generate similar ones. Of course, an important question to ask is are the problems we generated indeed similar to the original ones. We invited 20 students to answer the 10 questions for each of the problem set: original problems and generated problems, and then we use a paired t test to compare the error rate of each student across the two problem sets. The p is calculated to be 0.1 for the two mean value 10.3% (original) and 14.2 (generated), now my question is does this suffice to show the two sets of questions are similar? If not, why and what should we do? Thanks very much.
Answer: No, it doesn't establish similarity, and indeed, it doesn't come close to answering the right question.
i) Failure to reject the null doesn't imply it's true. It simply implies your sample was too small to detect the difference.
ii) You're not actually even interested in the truth of the null you're testing. I presume you don't believe the distribution of errors is actually identical ... you must know that that would be an astronomically unlikely situation -- the new problems will have at least subtle differences from the original. You yourself use the word "similar" and the hypothesis you're testing isn't about that. With a large enough sample size, any difference in mean - no matter how trivial - might be rejected.

You may want to consider whether a confidence interval for the difference is a better tool. You can specify what you regard as the largest size of difference in error rate that is still reasonably consistent with being "similar", and see if the confidence interval contains it.
Alternatively, you might consider an equivalence test.
(I'm not 100% sure I'd use a t-test for this, since the number of errors will be fairly discrete, and there's also a potential issue with heteroskedasticity -- the variance of a difference will tend to be larger for students whose mean number of errors is larger -- but it may do well enough.)

Of course this only detects situations where the mean difference is away from zero.
It's possible that the variation is such that some people score higher and some score lower (for example, weaker students may typically score lower than they do on the original test and stronger students typically score higher than on the original test) and a paired test of means won't detect that. If you want to be able to identify that kind of change, you will want a different test.
Answer: No. You cannot use a t-test to prove the null hypothesis. A $p > \alpha$ only means that you do not have sufficient evidence to reject the null hypothesis.
You could try reporting a simple correlation between the two tests.
Comment: Correlation is no use. If the new test precisely doubled the proportion of errors, the correlation would be 1
Comment: user1935724 - The correlation is completely unrelated to whether the means are close. The closeness of the means is what you seem to be concerned about.
Comment: ... to clarify -- I mean if it doubled the proportion of errors for each individual.
Comment: @Glen_b, I understand exactly what you mean but does it help if the mean is close?
Comment: ... to clarify: If the means are very close, the correlation still doesn't quite do what you need (imagine $y_i-\bar{y} = 0.01 (x_i-\bar{x})$ - the correlation is 1, but the tests are still quite different). Something based on the squared pair-differences (or even absolute pair-differences) would seem to be more relevant, since they'll pick up difference in means when the means differ and also low correlation if the means and variances are identical. Perhaps something based on mean square error.


Javascript keeps running

Question: I am very new to Javascript and I am having difficulty figuring out how to stop it after running first time. I have a simple refresh function and I want it to run once onLoad. Now it keep running. I would appreciate it if you can tell me how to stop it after the first run. Thank you.

Comment: It runs on page-load, then calls a refresh, which in turn runs this on page load.
Comment: I'm curious, why do you want/need it to refresh in the first place?
Comment: This will create an infinite loop. You can't only run it once on page load because it will just load again, and again...
Comment: i see now how pointless this is. thanks all.
Answer: By writing this code, you create an infinite loop:
1/First you access the page
2/then the js code is loaded, and refresh the page
3/then the js code is loaded again, and refresh the page.
4/then .......
So the page 'keep running'
Answer: I dont know how you set refresh process but you can do something like this.
Say you got a query string and if it's set to something you wanna refresh the page e.g. URL?refresh=1
You can read this refresh value and check if it 's set to 1 . If it is redirect the page
function getParameterByName(name) {
  var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
  return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

refresh = getParameterByName("refresh");

if (refresh == "1") window.location = "URL";

FIDDLE
PS: getParameterByName function is found in HERE

Javascript keeps running


Merge files in subdirectories by outside table

Question: I have a folder (split_libs) with subfolders named according to a sample_name described in columns 9 and 32 of SraRunTable3.txt, each associated to a sra_study. Inside each subfolder there is a seqs.fna file, for which I unfortunately can't change the name - it's an output of a QIIME command.
I want to merge seqs.fna files within subfolders according to sra_study by reading the subfolder name (=sample_name). e.g. all seqs.fna from a same SRA study would be merged.
An example overview of the directory:
split_libs
    sample1
      seqs.fna
    sample2
      seqs.fna
    sample3
      seqs.fna

An example overview of the SraRunTable:
(...)Sample_Name(...)SRA_Study(...)
     sample_1        study_1
     sample_2        study_1
     sample_3        study_2

Here's what I've tried so far:
import os
from operator import itemgetter

fields = itemgetter(9, 32)

with open('/home/andre/Desktop/PRJEB0000/SraRunTable3.txt') as csvfile:
next(csvfile)
for line in csvfile:
    sample_name, sra_study = fields(line.split())
for folder in os.listdir('./split_libs'):
    if folder == sample_name:
        open('seqs.fna') as infile, open('/home/andre/Desktop/PRJEB0000/cat_fna/' + sra_study + ".fna", 'a') as outfile:
            outfile.write(infile.read())

This question spinned-off of Joining files by corresponding columns in outside table
Any contributions will be appreciated!
Comment: @mhawke , like we talked , here's the improved re-post!
Answer: import os
from operator import itemgetter

fields = itemgetter(9, 32)

with open('/home/andre/Desktop/PRJEB0000/SraRunTable3.txt') as csvfile:
next(csvfile)
for line in csvfile:
    sample_name, sra_study = fields(line.split())
    #open the folder corresponding to sample_name and add the seqs to the appropriate study file
    with open('split_libs/'+sample_name+'/seqs.fna') as infile, open('/home/andre/Desktop/PRJEB0000/cat_fna/' + sra_study + ".fna", 'a') as outfile:
            outfile.write(infile.read())

All credits to Amanda Clare (not registered on Stackoverflow)!