rank of block triangular matrix and its relation to the rank of its diagonal blocks

Question: Prove that $$rank\begin{pmatrix}A & X \\ 0 & B \\ \end{pmatrix}\ge rank(A) + rank(B)$$ where $$A,B\in \mathbb C^{m \times m}$$.
I know the intuition behind it (i.e. maximal independent rows, etc.), but I am looking for a formal proof.  I have tried QR decomposition of A and B, then broke the block triangular matrix up into a matrix product and used the inequality rank(AB)<= min{rank(A), rank(B)}, but have not made any great progress.  One fact I thought may help was, if A=QR, where Q is unitary, then rank(A)=rank(R).  Again I thought this would help but it did not.  Any help on this problem would be much appreciated.
Answer: Let $a = \text{rank}(A)$ and $b=\text{rank}(B)$.
Consider a set of $a+b$ columns $C_1, \ldots, C_{a+b}$ of your matrix, where $C_1, \ldots, C_a$ correspond to linearly independent columns of $A$ and $C_{a+1}, \ldots, C_{a+b}$ correspond to linearly independent columns of $B$.
Suppose $\sum_{i=1}^{a+b} s_i C_i = 0$ where $s_1, \ldots, s_{a+b}$ are scalars.  Because those $b$ columns of $B$ are linearly independent, we must have $s_{a+1} = \ldots = s_{a+b} = 0$.  And then because those $a$ columns of $A$ are linearly independent, $s_1 = \ldots = s_a = 0$.


$3\times3$ linear system organization

Question: How to organize the system below? Especially the 2nd row of the system.
$$\left\{\begin{eqnarray}
4x-3y+2z+4&=&0\\
x-\frac y3+\frac z2&=&-\frac16\\
5x+2z&=&3y-3\\
\end{eqnarray}\right.$$
Comment: What do you mean by "organizing the system"? Do you mean Gaussian elimination?
Comment: You could clear denominators in the 2nd equation, if the fractions bother you, multiplying both sides by 6.  The third equation might be more of a trap, since the $y$ term needs to be "moved" (subtracted from both sides) to put it into the same format as the other two equations.
Answer: The second row is simply $$x - \frac 13 y + \frac 12 z = -\frac 16$$
Tip for greater ease in computation: the above equation is equivalent to $$6\left(x - \frac 13 y + \frac 12 z\right) = 6\left(-\frac 16\right) \iff6x - 2y + 3z = -1$$
In the first row, subtract $4$ from both sides.
In the third row, subtract $3y$ from both sides of the equation.
This will give you three rows of the form $ax + by + cz = d$, with real constants $a, b, c, d$.
Now, simply set up an augmented coefficient matrix to solve, and/or calculate the determinant of the $3\times 3$ coefficient matrix.
$$\begin{pmatrix}
4 & -3 & 2&|& -4\\
6 & -2 & 3 &|&-1\\
5&-3&2&|&-3\end{pmatrix}$$
Answer: The systems are more easily read when variables are grouped by colums. For instance, every term in $x$ should be on the same columns as others from other lines. And the constant terms are usually placed to the right of the equal signs.
As for your question concerning the second line, it is no different from the other lines if you realize that $y/3$ is the same as $\frac{1}{3} y$.
Eventually, you get:
$$ \left\{ \begin{array}{llll}
4x &-3y    &+ 2z    &= -4\\
x  &-\frac{1}{3} y &+ \frac{1}{2} z &= -\frac{1}{6}\\
5x &-3y    &+2z     &= -3\\
\end{array} \right.
$$
edit: fixed alignment of terms
Comment: Sorry for the edit attempt: I tried to use the align environment, but rolled backed to your post since I may not have helped any. If you like it, you can use it.
Comment: @amWhy Didn't see your attempt. Thank you anyway! I won't improve on it further since Jean-Claude Arbaut's answer already looks better!
Answer: Usually for a linear system, you put variables on the same side, and align columns like this:
$$\left\{\begin{eqnarray}
4x &-& 3y &+& 2z &=& -4\\
x &-& \frac 13y &+& \frac 12z&=&-\frac16\\
5x&-&3y&+&2z&=&-3\\
\end{eqnarray}\right.$$
And you may multiply some rows by a constant to eliminate fractions:
$$\left\{\begin{eqnarray}
4x &-& 3y &+& 2z &=& -4\\
6x &-& 2y &+& 3z&=&-1\\
5x&-&3y&+&2z&=&-3\\
\end{eqnarray}\right.$$
Now, one thing that would be obvious, is that, subtracting third and first rows, you get $x=1$.
Then, computing $3R_1-2R_2$ gives $-5y=-10$ or $y=2$.
You finish with $2z=-4-4x+3y=-2$ so $z=-1$.

$3\times3$ linear system organization


Eclipse does not see my c++ includes from separate folders

Question: I have the folowing folder file hierarchy:
src/
  Fuelable.h
  Fuelables/
    PetrolCar.h
    PetrolCar.cpp

PetrolCar.h:
#include "Fuelable.h"

PetrolCar.cpp:
#include "PetrolCar.h"

In order to make this compile i added src folder to include paths as in this manual:
http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.cdt.doc.user%2Ftasks%2Fcdt_t_proj_paths.htm
The include code is not highlighted as error. But when i am trying to build it fails with error concerning makefile:
Building file: ../src/Fuelables/PetrolCar.cpp
In file included from ../src/Fuelables/PetrolCar.cpp:8:0:
Invoking: GCC C++ Compiler
../src/Fuelables/PetrolCar.h:12:22: fatal error: Fuelable.h: No such file or directory
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/Fuelables/PetrolCar.d" -MT"src/Fuelables/PetrolCar.d" -o "src/Fuelables/PetrolCar.o" "../src/Fuelables/PetrolCar.cpp"
compilation terminated.
make: *** [src/Fuelables/PetrolCar.o]

What is interesting, the intellisence sees all the files.
If I compile from command line:
sashko@sashko-1225C:~/workspaceEclipse/FuelingSystem/src/Fuelables$ g++ PetrolCar.cpp -I
/home/sashko/workspaceEclipse/FuelingSystem/src/Fuelable.h
cc1plus: warning: /home/sashko/workspaceEclipse/FuelingSystem/src/Fuelable.h: not a directory [enabled by default]
In file included from PetrolCar.cpp:8:0:
PetrolCar.h:12:22: fatal error: Fuelable.h: No such file or directory
compilation terminated.

Comment: Compile on the command line. Add appropriate `-I` options to `g++`
Comment: have you tried `#include "../Fuelable.h"` to specify that the file is in the previous directory?
Comment: @Basile Starynkevitch, what do mean by appropriate? Updated question.
Comment: @Gmercer015 I did but I heared it is a bad style. Besides what if I want to include a file wich is far far away e.g.: "ProjectFolder/boost/date_time/gregorian/gregorian.hpp"?
Answer: Lets say you would distribute a library Machines. The include  hierarchy could be:
some_local_or_general_or_system_include_directory
- Machines
  - Fuelables

Then you can #include <Machines/Fuelable.h> or #include <Machines/Fuelables/PetrolCar.h> having a single include directory. Otherwise, you have to add each directory to your include path.
Comment: Fuelable.h is an interface to implementation classes in folder "Fuelables". I can't nest folders as you suggest.


Doubt in given hint's interpretation for a question.

Question: The question is : Given $a,b$ as two odd integers, show $a^2+b^2$ is not a square number.
Book's hint states that any odd integer can be of the form: $n = 3q +r$, hence the $3$ cases based on value of $r$ are : (i) if $r=0, n_1 = 3q \implies  3\mid n_1$
(ii) if $r=1, n_2 = 3q+1\implies   3\mid (2n_2+1)$
(iii) if $r=2, n_3 = 3q+2\implies   3\mid (n_3+1)$
I feel that the book's approach is to find all $6$ possible combinations, with the sum of individual squares as $m_i$ as :
(a) $m_1=n_1^2+n_1^2$
(b) $m_2=n_2^2+n_2^2$
(c) $m_3=n_3^2+n_3^2$
(d) $m_4=n_1^2+n_2^2$
(e) $m_5=n_1^2+n_3^2$
(f) $m_6=n_2^2+n_3^2$
I am doubtful about the interpretation made, hence want to confirm.
Comment: I suspect the book's hint is useless. Looking at it modulo $3$ shows that one of $a$ and $b$ must be divisible by $3$, but there's no obvious way from there onwards. Looking at the matter modulo $4$ gives a short and obvious proof.
Comment: But any integer, not only odd integers, can be of the form $n = 3q +r$
Comment: Hint:  if $n$ is odd then $n^2\equiv 1 \pmod 4$.
Comment: When any number can be in the form of $3q+r$ and nowhere it provided integers to be odd, I also suspect this is not a hint.
Comment: Because odd number $+ 1 =$ even number, and $3q$ depending on $q$ can both be odd or even.
Comment: For your last question: $c^2=a^2 + b^2$ is congruent to $2 ($mode $4)$ and this shows $c$ should have a $\sqrt 2$ factor and that is impossible as it should be an integer. @jiten
Comment: @MehrdadZandigohar This is correct. But, the definite criteria can be not in terms of any residue class for any integer $n$. However, for square of any odd number $n$ can state as, $n^2=(2k+1)^2 = 8k'+1$. So, if IGNORE the book's approach, then two numbers of the $8k'+1$ form will never lead to a square as have residue as $2$ wrt $8$. But, the book's hint seems aimless then, or can-not understand it.
Comment: @jiten What happens after dividing into 6 combinations from the book's approach?
Comment: @MehrdadZandigohar  First, I want to edit my earlier comment by modifying the second line as : "...in terms of any residue class, except $2$, for any integer $n$." The $6$ combinations are my imagination. The book stops at stating the $3$ classes in terms of conditions for divisibility wrt $3$.
Comment: @MehrdadZandigohar I want to ask why it is that for any odd integer, there cannot be any criteria except division by 2. Why any criteria by division by $3$ will fail as : $3n+1$ will fail for $16$, $3n+2$ will fail for $14$. Only the residue class wrt $2$ is a success. Can there be a formal reason/proof  for that. Also, why it is that square of odd integer will satisfy the residue criteria wrt 4/8.
Answer: HINT
Use congruence $\bmod 4$ and $(2k+1)^2=4k^2+4k+1$.
Answer: Yes, you can it confirm as so:
Any odd square is congruent to $1 (\mod 4)$.
Then, what will the sum of two odd squares be? And what conclusion can you arrive at?
Comment: @jiten I think the book is trying to do proof by cases, to eliminate all possible solutions, which ultimately disproves that $a^2+b^2$ cannot be a perfect square.
Comment: @jiten Yes! You are correct.
Comment: Please help in understanding the given hint of book.
Comment: So, my interpretation is correct then.


Como criar um modal corretamente para fazer alteração de dados usando w3

Question: Gostaria de saber como implementar um modal para receber os dados de alteração.
Eu estou usando o w3.
Na Imagem Abaixo quando o usuário apertar o botão AUSENTE tem que abrir um MODAL
com as informações do paciente da linha. Nome, tel, o plano de saúde dele, nr do cartão do plano etc.

Teoricamente tenho que fazer uma requisição php para popular o modal, mas o problema é que não sei onde colocar essa requisição ou se a forma que estou chamando o modal para esse caso é errado

Abaixo Mostro como chamo UM OUTRO MODAL quando aperto o botão ENCAIXE
HTML
     <input type="button" class="add"
         onClick="chama_consulta_01_modal('',
                                          '{$row['id_m_h']}','{$diaN}',
                                          'atendimento')"
         value="ENCAIXE">

JAVASCRIPT
function chama_consulta_01_modal(id_linha_tabs,id_m_h, dia,veio_de)
{
  document.getElementById('id_consulta_01_modal').style.display='block';
  document.getElementById('id_veio_de').innerHTML = veio_de;
  document.getElementById("id_m_h_div").innerHTML = id_m_h;
  document.getElementById("data_div").innerHTML =
           document.getElementById("id_data_atual").innerHTML;
  document.getElementById("index_tab_div").innerHTML = dia;
};

O código acima faz aparecer este MODAL

O código que uso para produzir os MODAIS é assim:

                ×

STATUS PACIENTE

                            <>

                <fieldset>
                    <legend>CONVÊNIO...:</legend>

                            <select name="cb_convenio" class="form-control" id="id_cb_convenio" autofocus style="width:90%;" required="true">
                                <option value="0" disabled selected hidden>
                                    SELECIONE
                                </option>
                                <?php include 'consulta_atendimento_02_modal_cb_convenio.php'?>
                            </select>

                </fieldset>

                        <button onclick="document.getElementById('id_consulta_atendimento_02_modal').style.display = 'none'" type="button" class="w3-button w3-red">FECHAR</button>

Modal Footer

O código acima é um protótipo para o MODAL em questão que estou querendo fazer.
Esse código esta em um arquivo .php. Ele esta na pagina da CONSULTAS MARCADAS:

  CÓDIGO..CÓDIGO..
CÓDIGO..CÓDIGO..CÓDIGO..
 <?php include 'selecionar_paciente_modal.php' ?>
 <?php include 'status_paciente_modal.php' ?>

Quando eu coloco o código php na status_paciente_modal.php para fazer a conexão e montar o MODAL com os dados do paciente, esse código não funciona corretamente pois quando a página CONSULTAS MARCADAS entra, o código do include status_paciente_modal.php é disparado e da erro na página.
Uma forma que encontrei foi colocar atributos no botao:

<input type='button' class='add A'
      data-paciente_nome="<?php echo ($row['nome']);?>"
      data-paciente_cpf="<?php echo ($row['cpf']);?>"
      data-id_convenio="<?php echo($row['id_convenio_fk']); ?>"
      id_consulta_ca_01_busca ="<?php echo($row['tem_consulta']);?>"
      onclick= status_paciente(self)
      value='AUSENTE'>

Ai na função status do paciente pego esses atributos:
 function status_paciente(botao)
{
document.getElementById('id_consulta_atendimento_02_modal').style.display='block';
document.getElementById("id_ca02m_paciente_nome").innerHTML =
                        botao.getAttribute('data-paciente_nome');
document.getElementById("id_ca02m_paciente_cpf").innerHTML =
                        botao.getAttribute('data-paciente_cpf');
document.getElementById("id_cb_convenio_02_modal").value =
                        botao.getAttribute('data-id_convenio');
}

Funcionar o código acima funciona. Ai um amigo meu programador sempre diz..:
"CÓDIGO BOM É AQUELE QUE FUNCIONA"
Sei que quando estamos sendo precionados pelo TEMPO/CHEFE isso é bem verdade. :)
Mas neste instante NÃO é o caso :).
Então volto a questão original do POST.. Como/Onde devo implementar o código php
para fazer uma consulta na base é popular o MODAL?
Pois como falei anteriormente apesar de saber fazer consultas php e chama-las em vários locais e de vários modos, nesta situação em particular não obtive sucesso. Certamente pela minha falta de experiencia na linguagem :)
Espero ter exposto minha NECESSIDADE claramente.
Caso alguém entenda e consiga sintetiza-la seria legal :) e eu agradeceria :).
Caso alguém "PENSE" que entendeu minha necessidade por favor..não altere nada.. me escreva e tentarei explicar de outra forma :)
Abraço a todos :)
Comment: Se estiver disposto a usar `JQuery`, recomendo `ajax()`
Comment: Bom dia @I_like_trains . Obrigado pela dica :).  Teria algum exemplo do que esta falando.. ou algo para ler?? Abraços
Comment: Tem aqui a documentação do `ajax`, darei um exemplo em breve

http://api.jquery.com/jquery.ajax/
Answer: Em ajax(), você pode executar php que vem fora do ficheiro.
Comecemos pelo início.
Se eu bem entendi, cada linha da tabela é referida a um id da base de dados, gerada pelo while. (Falta esse código apresentado mas supomos que seja assim)
Daremos o nome por exemplo $dados, sendo assim a variável que recebe os dados do while, no botão onde carrega, acrescente data-id="<?=$dados['id']; ?>", deste modo todas as linhas ficaram identificadas e nunca iguais.
Agora passemos ao script
Primeiro deverá verificar se carregou lá, seria assim o código:
$(".add").click(function(){       //Visto que o botão tem esta `class`, podemos ir buscar assim
  var id = $(this).data("id");    //O $(this) irá buscar a seguinte informação de onde carregou
$.ajax({
  url: "buscar_modal.php",        //Ficheiro onde iremos buscar as informações
  data: "id="+id,
  type: "POST",
  success: function(e){           //Variável e servirá para escrever no modal ou mostrar erros, se houver
    console.log(e);
    $("#id_consulta_atendimento_02_modal").html(e);
  }
})
});

O script está feito, agora passemos para o buscar_modal.php
O início do ficheiro deve começar com a verificação da variável enviada, se foi recebida ou não
if(isset($_POST['id'])){
Com isto verificará se foi enviada. De seguida iremos selecionar da base de dados a linha desejada.
Irei supor que está a usar mysqli.
require "ligacao.php";
$select=mysqli_query($db, "SELECT * FROM nome_tabela where id = '".$_POST['id']."'") or die ("Erro 01");
$mostra=mysqli_fetch_assoc($select);

Com a linha selecionada só resta apresenta-la.

        ×

STATUS PACIENTE

                    <?=$mostra['nome']; ?>

        <fieldset>
            <legend>CONVÊNIO...:</legend>

                    <select name="cb_convenio" class="form-control" id="id_cb_convenio" autofocus style="width:90%;" required="true">
                        <option value="0" disabled selected hidden>
                            //Executar um while com as informações desejadas
                        </option>

                    </select>

        </fieldset>

                <button onclick="document.getElementById('id_consulta_atendimento_02_modal').style.display = 'none'" type="button" class="w3-button w3-red">FECHAR</button>

Modal Footer

Com isto irá apresentar o que deseja.
Comment: Bom dia @I_like_trains . Muito legal o link que tu passou para eu poder ler. Obrigado.  Muito maneiro o seu exemplo :) Um pergunta: os "PARAMETROS"  do $.ajax({ , , , }) tem que ter uma ordem??? Eu uso essa função mas de um modo diferente e com os parametros em uma ordem diferente. E do modo que uso no paremetro  success: function(e){ } eu retorno um echo da página .php que é um id ou palavra. Não sabia que dava para retorna o  $("#id_consulta_atendimento_02_modal").html(e);  Na Segunda-Feira (08/11/2018) vou fazer uma outra página da forma que você demonstrou :) . Obrigado e Abraços.
Comment: Os parametros podem ter qualquer ordem, mas em termos de organizaçãp, deixe o `success` para ultimo


Can getActivity return null when using a viewpager?

Question: I'm getting a lint warning that getActivity may return null, so i was wondering when getActivity might return null which would be a problem because im using getActivity as a context.
I read in other posts to use onAttach which is deprecated, so what is the best way to get a context or to be sure getActivity() won't return null?
I'm also using a viewPager with fragments so the fragments are attached to an Activity right, so normally it wouldn't return null?
  public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

    private int numOfTabs;

    SectionsPagerAdapter(FragmentManager fm, int numOfTabs) {
        super(fm);
        this.numOfTabs = numOfTabs;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                Log.i(TAG, "Fragment Pos: "+ position);
                return new Tab1();
            case 1:
                Log.i(TAG, "Fragment Pos: "+ position);
                return new Tab2();
            case 2:
                Log.i(TAG, "Fragment Pos: "+ position);
                return new Tab3();
            case 3:
                Log.i(TAG, "Fragment Pos: "+ position);
                return new Tab4();
            case 4:
                Log.i(TAG, "Fragment Pos: "+ position);
                return new Tab5();
            case 5:
                Log.i(TAG, "Fragment Pos: "+ position);
                return new Tab6();
                default:
                    return null;
        }
    }

    @Override
    public int getCount() {
        // Get total pages
        return numOfTabs;
    }
}

setupViewPager() method:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());

    // Set up the ViewPager with the sections adapter
    mViewPager = findViewById(R.id.viewPager);

    mViewPager.setAdapter(mSectionsPagerAdapter);

    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

Answer:
U can always use the context from the view itself viewPager.getContext()
It's ok to use the getActivity() as long as U know for sure that in that point the activity will not be null e.g in onActivityCreated.

and if you want to get rid from the lint warning, just put null check on the getActivity var.


How can I filter a dataset in Delphi on a TDateTime field

Question: I have a dataset that I need to filter by time.  e.g. I want records where the time contained in a TDateTime field is between 6:00 AM and 6:00 PM.
My dataset contains a field named time_of_day, of type TDateTime.  The value assigned to the filed is a time, with no date.
I have tried creating the filter string using both the string representation of the time (time_of_day >= '6:00 AM' and time_of_day <= '6:00 PM'), and also using the floating point representation (time_of_day >= 0.25 and time_of_day < 0.75), but neither have worked.
I need to know how to construct the filter string to assign to the TDataSet.Filter property.
Comment: Not sure if this is relevant to your case, but you could also consider changing the SQL that produced the dataset (unless you want the discarded records for some other purpose).
Answer: I think it might depend on short time format but this works for me using TADODataSet.
ADODataSet1.Filter := 'TimeField = 11:00:00';
ADODataSet1.Filtered := True;

A more full proof solution is to use the OnFilterRecord event instead.
procedure TForm4.ADODataSet1FilterRecord(DataSet: TDataSet; var Accept: Boolean);
begin
    if DataSet.FieldByName('TimeField').AsDateTime = FilterValue then
        Accept := True
    else
        Accept := False
end;

If you need interval it would look like this.
ADODataSet1.Filter := 'TimeField >= 10:00:00 and TimeField < 11:00:00';
ADODataSet1.Filtered := True;

OnFilterRecord
procedure TForm4.ADODataSet1FilterRecord(DataSet: TDataSet; var Accept: Boolean);
begin
    if (DataSet.FieldByName('DateField').AsDateTime >= FromTime) and
         (DataSet.FieldByName('DateField').AsDateTime < ToTime) then
        Accept := True
    else
        Accept := False
end;

If you use AMPM notation you need to enclose the time in '
ADODataSet1.Filter := 'TimeField >= ''10:00 AM'' and TimeField < ''11:00 AM''';
ADODataSet1.Filtered := True;

But I would really recommend the OnFilterRecord instead so you do not have to worry about time formats.
Comment: For the OnFilterRecord, I'd prefer `Accept := ;` instead of the if..else. Good answer, though. :) I'll give you a +1 for the thoroughness alone (and I have answer to this question too).
Comment: My filter expressions are generated dynamically, based on user input, so the OnFilterRecord event isn't practical.  The number of conditions and types of operators vary significantly.  After receiving your answer, I did change my filter to use the ShortTime format, and it did correctly.
Answer: TDateTime in Delphi is type double, where the integral portion is the number of days since 12/30/1899 and the fractional (decimal) portion is the time.
A time of noon (without a date portion) would be indicated as 0.5, which means that 6:00 AM would be 0.25 (exactly, 1 day / 24 hours * 6 hours) and 6:00 PM would be 0.75. The simplest way to filter, then, would be:
// 6 hours after midnight
Frac(YourTimeField.AsFloat) >= (1.0 / 24.0) * 6 and
// 18 hours after midnight
Frac(YourTimeField.AsFloat) <= (1.0 / 24.0) * 18;

Doing the actual calculation makes sure that if the number can't be exactly represented as 0.25 (like 0.2499999999999), you still get the correct value to compare.
Frac returns the fractional portion, just to make the code clearly indicate that you're only considering the time portion of the value.
Comment: I understand that will work as executable code, but can I use the Fract function in a filter string for a dataset?
Comment: No. You can use it in the OnFilterRecord event. What database are you using? There might be a better way than filtering.
Comment: I'm actually using kbmMemData
Answer: I don't use ADO but Zeos, but rendering as float
  xx.filter:='datefieldname > '+floattostr(strtodatetime(edit1.text));

works for me.


Paraboloid geodesic (evaluate integral)

Question: [Some context below, actual question at the end]
Wolfram MathWorld defines the paraboloid using the following parametrization ($u \geq 0$, $v \in [0,2\pi)$):
\begin{align}
x&=\sqrt{u}\cos{v} \\
y&=\sqrt{u}\sin{v} \\
z&=u
\end{align}
and the coefficients of the first fundamental form as
\begin{align}
P&=\left(\frac{\partial x}{\partial u}\right)^2+\left(\frac{\partial y}{\partial u}\right)^2+\left(\frac{\partial z}{\partial u}\right)^2=1+\frac{1}{4u} \\[8pt]
Q&=\frac{\partial x}{\partial u}\frac{\partial x}{\partial v}+\frac{\partial y}{\partial u}\frac{\partial y}{\partial v}+\frac{\partial z}{\partial u}\frac{\partial z}{\partial v}=0 \\[10pt]
R&=\left(\frac{\partial x}{\partial v}\right)^2+\left(\frac{\partial y}{\partial v}\right)^2+\left(\frac{\partial z}{\partial v}\right)^2=u
\end{align}
Next, setting up the Euler-Lagrange equation is pretty straightforward:
\begin{equation}
\underbrace{\frac{\frac{\partial P}{\partial v}+2v\,'\frac{\partial Q}{\partial v}+v\,'^2\frac{\partial R}{\partial v}}{2\sqrt{P+2Qv\,'+Rv\,'^2}}}_{\displaystyle{=0}}-\frac{d}{du}\left(\frac{Q+Rv'}{\sqrt{P+2Qv\,'+Rv\,'^2}}\right)=0
\end{equation}
Plugging in $P$, $Q$ and $R$ from above, the equation will greatly simplify because of the vanishing term on the LHS, so we are left with
\begin{equation}
\frac{d}{du}\left(\frac{u\,v'(u)}{\sqrt{1+\frac{1}{4u}+u\,v'(u)^2}}\right)=0
\end{equation}
Since the total derivative yields zero, the term in parentheses must be constant:
\begin{equation}
\frac{u\,v'(u)}{\sqrt{1+\frac{1}{4u}+u\,v'(u)^2}}=C_1
\end{equation}
Rearrange:
\begin{align}
u\,v'(u)&=C_1\sqrt{1+\frac{1}{4u}+u\,v'(u)^2} \\[8pt]
u^2\,v'(u)^2&=C_1\left(1+\frac{1}{4u}+u\,v'(u)^2\right) \\[8pt]
\end{align}
(Leave $C_1$ unsquared since its value is arbitrary anyway)
Eventually I arrive at
\begin{equation}
v(u)=\pm\int \sqrt{\frac{C_1+\frac{C_1}{4u}}{u^2-C_1 u}}du
\end{equation}
I was curious to see what Mathematica would come up with (solution for the positive branch):
<code>Integrate[Sqrt[(C1 + C1/(4 u))/(u^2 - C1 u)], u,Assumptions -> u >= 0]
</code>
yields
\begin{gather*}
v(u)=\frac{u\sqrt{-C_1+u}\sqrt{\frac{C_1(1+4u)}{u^2(-C_1+u)}}\Bigg(2\sqrt{C_1}\sqrt{C_1(1+4 C_1)}\sqrt{\frac{1+4u}{1+4 C_1}}\text{arcsinh}\left(\frac{2\sqrt{C_1}\sqrt{-C_1+u}}{\sqrt{C_1(1+4 C_1)}}\right) }{C_1+4 C_1\,u} \\[8pt]
\frac{+\sqrt{C_1+4 C_1\,u}\,\arctan\left(\frac{\sqrt{-C_1+u}}{\sqrt{C_1+4 C_1\,u}}\right)\Bigg)}{C_1+4 C_1\,u} +C_2
\end{gather*}
Contrast this to the solution from MathWorld (eq. 11):
\begin{equation}
u-c^2=u(1+4c^2)\sin^2\left(v-2c\ln\left(k\left(2\sqrt{u-c^2}+\sqrt{4u+1}\right)\right)\right)
\end{equation}
where $c$ and $k$ are the integration constants.
Apart from some more or less obvious simplifications to the Mathematica output, I was wondering how Weinstock came up with his solution. Any hints most welcome!

Edit:
Using the identities suggested by Rafa, I was able to get closer to the solution given by Weinstock. First, the output from Mathematica can be further simplified to
$$
v=2\sqrt{C_1}\text{arcsinh}\left(\frac{2\sqrt{-C_1+u}}{\sqrt{1+4 C_1}}\right)+\arctan\left(\frac{\sqrt{-C_1+u}}{\sqrt{C_1+4C_1u}}\right)+C_2
$$
Now, use the trig identities
\begin{align*}
\text{arcsinh}\left(\frac{2\sqrt{-C_1+u}}{\sqrt{1+4 C_1}}\right)=\ln\left(\frac{2\sqrt{-C_1+u}+\sqrt{4u+1}}{\sqrt{1+4C_1}}\right)
\end{align*}
and
\begin{align*}
\arctan\left(\frac{\sqrt{-C_1+u}}{\sqrt{C_1+4C_1u}}\right)=\arcsin\left(\sqrt{\frac{-C_1+u}{u(1+4C_1)}}\right)
\end{align*}
Therefore
\begin{align*}
v=2\sqrt{C_1}\ln\left(\frac{2\sqrt{-C_1+u}+\sqrt{4u+1}}{\sqrt{1+4C_1}}\right)+\arcsin\left(\sqrt{\frac{-C_1+u}{u(1+4C_1)}}\right)+C_2
\end{align*}
Since $C_2$ is arbitrary and $\log a+\log b=\log(a\,b)$:
\begin{align*}
v&=2\sqrt{C_1}\ln\left(\frac{2\sqrt{-C_1+u}+\sqrt{4u+1}}{\sqrt{1+4C_1}}\right)+\arcsin\left(\sqrt{\frac{-C_1+u}{u(1+4C_1)}}\right)+\ln C_2 \\[12pt]
v&=2\sqrt{C_1}\ln\left(C_2\,\frac{2\sqrt{-C_1+u}+\sqrt{4u+1}}{\sqrt{1+4C_1}}\right)+\arcsin\left(\sqrt{\frac{-C_1+u}{u(1+4C_1)}}\right)
\end{align*}
\begin{align*}
\arcsin\left(\sqrt{\frac{-C_1+u}{u(1+4C_1)}}\right)=v-2\sqrt{C_1}\ln\left(C_2\,\frac{2\sqrt{-C_1+u}+\sqrt{4u+1}}{\sqrt{1+4C_1}}\right)
\end{align*}
\begin{align*}
\frac{-C_1+u}{u(1+4C_1)}=\sin^2\left(v-2\sqrt{C_1}\ln\left(C_2\,\frac{2\sqrt{-C_1+u}+\sqrt{4u+1}}{\sqrt{1+4C_1}}\right)\right)
\end{align*}
\begin{align*}
u-C_1=u(1+4C_1)\sin^2\left(v-2\sqrt{C_1}\ln\left(C_2\,\frac{2\sqrt{u-C_1}+\sqrt{4u+1}}{\sqrt{1+4C_1}}\right)\right)
\end{align*}
which is almost identical to the textbook solution:
\begin{equation}
u-c^2=u(1+4c^2)\sin^2\left(v-2c\ln\left(k\left(2\sqrt{u-c^2}+\sqrt{4u+1}\right)\right)\right)
\end{equation}
How can I get rid of the denominator $\sqrt{1+4C_1}$?
Comment: Simply drop it! The factor is constant, so we can redefine the second arbitrary constant as $C'_2=C_2/\sqrt{1+4C_1}$ and the factor is gone.
Comment: That did the trick, awesome!
Comment: The only difference left is $C_1$ vs. $c^2$ - is it permissible to simply replace $C_1$ with $C_1^2$? I hesitated to do so because $C_1$ also occurs as the argument of $sin$ and $ln$, both being transcendental non-linear functions. Would $C_1^2$ break the relationship LHS==RHS?
Comment: No problem, simply replace. In fact you didn't write the square on $C_1$ when rearranging the first integral. You were in fact working with $C_1^2$ all the way.
Answer: Too long for a comment. It's cumbersome. Two identities can help.
Using the one relating $\arctan$ and $\arcsin$:
$\arctan\left(\dfrac{\sqrt{-C_1+u}}{\sqrt{C_1+4 C_1\,u}}\right)=\arcsin\left(\dfrac{\dfrac{\sqrt{-C_1+u}}{\sqrt{C_1+4 C_1\,u}}}{\sqrt{1+\left(\dfrac{\sqrt{-C_1+u}}{\sqrt{C_1+4 C_1\,u}}\right)^2}}\right)=$
$=\arcsin\left(\dfrac{\dfrac{\sqrt{-C_1+u}}{\sqrt{C_1+4 C_1\,u}}}{\sqrt{\dfrac{u+4C_1u}{C_1+4 C_1\,u}}}\right)=\arcsin\left(\sqrt{\dfrac{-C_1+u}{u(1+4C_1)}}\right)$
Compare with the rearranged from MathWorld
$\begin{equation}
\sqrt{\dfrac{u-c^2}{u(1+4c^2)}}=\sin\left(v-2c\ln\left(k\left(2\sqrt{u-c^2}+\sqrt{4u+1}\right)\right)\right)
\end{equation}$
Further, from an identity with $\text{arcsinh}$
$\text{arcsinh}\left(\dfrac{2\sqrt{C_1}\sqrt{-C_1+u}}{\sqrt{C_1(1+4 C_1)}}\right)=\text{arcsinh}\left(\dfrac{2\sqrt{-C_1+u}}{\sqrt{1+4 C_1}}\right)=$
$=\ln\left(\dfrac{2\sqrt{-C_1+u}}{\sqrt{1+4 C_1}}+\sqrt{\left(\dfrac{2\sqrt{-C_1+u}}{\sqrt{1+4 C_1}}\right)^2+1}\right)=$
$=\ln\left(\dfrac{2\sqrt{-C_1+u}+\sqrt{4u+1}}{\sqrt{1+4 C_1}}\right)$
I think this can help.
Comment: Thank you, this almost did it - see my edit above. Still, there's a factor which I could not eliminate, any ideas?
Comment: See my comment below the question.

Paraboloid geodesic (evaluate integral)


What is the meaning of exponentiation?

Question: For natural numbers $a,b$ the operation $a^b$ is defined as $a * a * a * a \cdots b$ times. However when you get to negative powers, complex powers, complex bases, polynomial expressions etc then this definition falls flat. So what exactly is exponentiation?
Answer: The basic idea is to take the concept we have, then keep extending it so as to generalize an identity. To wit:

The definition $a^0:=1,\,a^{b+1}:=a^ba$ obtains $a^b$ for integers $b\ge0$. It implies $a^{b+c}=a^ba^c$ for $b,\,c\ge0$, but we can extend this to any integers $b,\,c$ provided $a\ne0$ by saying $a^{-b}=1/a^b$.
We now have $(a^b)^c=a^{bc}$ for integers $b,\,c$, so to extend this to rationals we say $a^{p/q}=\sqrt[q]{a^p}$. However, if $a<0$ this only gets a real result if $q$ is odd when $p/q$ to be in its lowest terms. If on the other hand $a\ge0$, we've now defined $a^b$ for all $b\in\Bbb Q$.
We can handle arbitrary real $b$ by requiring $a^b$ to be a continuous function of $b$.
Defining the exponential function $\exp x$ as the solution of $\frac{dy}{dx}=y$ for which $y=1$ at $x=0$, and $\ln x$ as its inverse, we can verify the above all satisfy $a^b=\exp(b\ln a)$ if $a>0$. We can use this generalization to define $a^b$ for any nonzero complex $a$ and any complex $b$, but it becomes multi-valued.
Answer: Well the very basic definition of exponentiation defined by you is valid only for positive powers. Different exponents have different definitions.
When we talk about negative powers , the way negative powers is defined is basically like so :
$$a^x\cdot a^y =1\ \  (\forall a>0)$$
$$a^{x+y}=a^0\ \  \text{  (law of exponents)}$$
$$x+y=0 $$
$$\Rightarrow y=-x$$
So basically what we can infer from here is that to define negative powers we define it as the reciprocal of positive exponents i.e.
$$a^{-x}= \frac{1}{a^x}$$
Therefore to define negative powers we basically multiply the reciprocal of the positive power $x$ times.
Comment: Hmm that makes sense. But what about complex bases and powers, how do you define those?
Comment: @Physicist I'm sorry I do not have much knowledge about those. Please refer the other answer..

What is the meaning of exponentiation?


Nginx rewrite rule remove subfolders

Question: I'm trying to setup a nginx rewrite rule but can't figure out how to get it working.
I want to redirect all urls https://domainname.com/archives/year/month/date/postname to https://domainname.com/postname
The page https://domainname.com/archives needs to stay active though.
Who can help me out?
Cheers, Jaap
Comment: It should be a simple regular expression. Are year, month & date all numeric? Do you want a 301 or 302 redirect?
Comment: Yes, all numeric and they should be 301.
Comment: I have posted an answer which assumes the date format is `yyyy/mm/dd`
Answer: Try:
<code>rewrite "^/archives/\d{4}/\d{2}/\d{2}/(.+)$" /$1 permanent;
</code>
See this document for details. A useful resource for regular expressions.
Comment: Thanks the format is indeed yyyy/mm/dd. I've put this in a server block like this:

server {  rewrite "^/archives/\d{4}/\d{2}/\d{2}/(.+)$" /$1 permanent; }

Restarted Nginx but the redirect is not working.
Comment: You need to add it to your existing server block. See [this document](http://nginx.org/en/docs/http/server_names.html) on server blocks.
Comment: Yes! First added it to the wrong one. Corrected this and now it's working except for a couple of urls. Will look into that. Thanks for your quick help @richard-smith !

Nginx rewrite rule remove subfolders


Can't install sqlite

Question: I use mac.
Gem version: 184.108.40.206
Ruby version: ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin15]
Gemfile:
source 'https://rubygems.org'

gem 'rails', '3.2.3'

group :development do
    gem 'sqlite3', '1.3.5'
end

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '3.2.4'
  gem 'coffee-rails', '3.2.2'

  gem 'uglifier', '1.2.3'
end

gem 'jquery-rails', '2.0.1'

group :production do
    gem 'pg', '0.12.2'
end

I spent about 3 hours searching a solution, without luck.
I read 'Ruby on Rails Tutorial' by Michael Hartl, on page 46.
First one error that leads to another, that leads to another...
It starts with this command:
bundle install --without production

That results in this error:
    Fetching gem metadata from https://rubygems.org/..........
Fetching version metadata from https://rubygems.org/..
Fetching dependency metadata from https://rubygems.org/.
Resolving dependencies...
Using rake 11.2.2
Using i18n 0.7.0
Using multi_json 1.12.1
Using builder 3.0.4 (was 3.2.2)
Using erubis 2.7.0
Using journey 1.0.4
Using rack 1.4.7 (was 2.0.1)
Using hike 1.2.3
Using tilt 1.4.1 (was 2.0.5)
Using mime-types 1.25.1 (was 3.1)
Using polyglot 0.3.5
Using arel 3.0.3 (was 7.1.2)
Using tzinfo 0.3.51 (was 1.2.2)
Using bundler 1.13.1
Using coffee-script-source 1.10.0
Using execjs 2.7.0
Using json 1.8.3
Using thor 0.14.6 (was 0.19.1)
Using sass 3.4.22
Installing sqlite3 1.3.5 (was 1.3.11) with native extensions
Using activesupport 3.2.3 (was 18.104.22.168)
Using rack-cache 1.6.1
Using rack-test 0.6.3
Using rack-ssl 1.3.4
Using sprockets 2.1.4 (was 3.7.0)
Using treetop 1.4.15
Using coffee-script 2.4.1
Using uglifier 1.2.3 (was 3.0.2)
Using rdoc 3.12.2
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

/Users/Money/.rbenv/versions/2.2.3/bin/ruby -r ./siteconf20160917-4100-9i5b1f.rb
extconf.rb
checking for sqlite3.h... yes
checking for sqlite3_libversion_number() in -lsqlite3... yes
checking for rb_proc_arity()... yes
checking for sqlite3_initialize()... yes
checking for sqlite3_backup_init()... yes
checking for sqlite3_column_database_name()... no
checking for sqlite3_enable_load_extension()... no
checking for sqlite3_load_extension()... no
creating Makefile

make "DESTDIR=" clean

make "DESTDIR="
compiling backup.c
compiling database.c
compiling exception.c
compiling sqlite3.c
compiling statement.c
statement.c:258:11: warning: implicit declaration of function 'RBIGNUM' is invalid in
C99 [-Wimplicit-function-declaration]
      if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {
          ^
./sqlite3_ruby.h:16:24: note: expanded from macro 'RBIGNUM_LEN'
#define RBIGNUM_LEN(x) RBIGNUM(x)->len
                       ^
statement.c:258:11: error: member reference type 'int' is not a pointer
      if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {
          ^~~~~~~~~~~~~~~~~~
./sqlite3_ruby.h:16:36: note: expanded from macro 'RBIGNUM_LEN'
#define RBIGNUM_LEN(x) RBIGNUM(x)->len
                       ~~~~~~~~~~  ^
statement.c:258:32: error: use of undeclared identifier 'SIZEOF_BDIGITS'
      if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {
                               ^
1 warning and 2 errors generated.
make: *** [statement.o] Error 1

make failed, exit code 2

Gem files will remain installed in
/Users/Money/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/sqlite3-1.3.5 for
inspection.
Results logged to
/Users/Money/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/extensions/x86_64-darwin-15/2.2.0-static/sqlite3-1.3.5/gem_make.out

An error occurred while installing sqlite3 (1.3.5), and Bundler cannot
continue.
Make sure that `gem install sqlite3 -v '1.3.5'` succeeds before bundling.

Then, because of the last phrase " Make sure that gem install sqlite3 -v '1.3.5' succeeds before bundling.
", I run that command:
gem install sqlite3 -v '1.3.5'

And get this error which I have no clue what to do about:
    Building native extensions.  This could take a while...
ERROR:  Error installing sqlite3:
    ERROR: Failed to build gem native extension.

    /Users/Money/.rbenv/versions/2.2.3/bin/ruby -r ./siteconf20160917-4314-20lcl4.rb extconf.rb
checking for sqlite3.h... yes
checking for sqlite3_libversion_number() in -lsqlite3... yes
checking for rb_proc_arity()... yes
checking for sqlite3_initialize()... yes
checking for sqlite3_backup_init()... yes
checking for sqlite3_column_database_name()... no
checking for sqlite3_enable_load_extension()... no
checking for sqlite3_load_extension()... no
creating Makefile

make "DESTDIR=" clean

make "DESTDIR="
compiling backup.c
compiling database.c
compiling exception.c
compiling sqlite3.c
compiling statement.c
statement.c:258:11: warning: implicit declaration of function 'RBIGNUM' is invalid in C99 [-Wimplicit-function-declaration]
      if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {
          ^
./sqlite3_ruby.h:16:24: note: expanded from macro 'RBIGNUM_LEN'
#define RBIGNUM_LEN(x) RBIGNUM(x)->len
                       ^
statement.c:258:11: error: member reference type 'int' is not a pointer
      if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {
          ^~~~~~~~~~~~~~~~~~
./sqlite3_ruby.h:16:36: note: expanded from macro 'RBIGNUM_LEN'
#define RBIGNUM_LEN(x) RBIGNUM(x)->len
                       ~~~~~~~~~~  ^
statement.c:258:32: error: use of undeclared identifier 'SIZEOF_BDIGITS'
      if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {
                               ^
1 warning and 2 errors generated.
make: *** [statement.o] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/Money/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/sqlite3-1.3.5 for inspection.
Results logged to /Users/Money/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/extensions/x86_64-darwin-15/2.2.0-static/sqlite3-1.3.5/gem_make.out
Jonass-MBP:demo_app Money$

I tried the suggestions on this thread, but all suggestions return with "Command not found".
I tried to run gem install sqlite3-ruby as well, as suggested in this thread, didn't work.
I tried to run gem sources --add http://rubygems.org/, as suggested in this thread, in case the failure had something to do with HTTPS or HTTP, didn't work.
Any suggestions?
Thank you!
Jonas
Answer: Please do try to install it as follows :
gem install sqlite3 -v '1.3.5' -- --srcdir=/usr/local/mysql/include
Comment: That helped me on macOS. If you installed `sqlite` via `brew` find the proper path and update accordingly, e.g. `/opt/homebrew/Cellar/sqlite/3.38.5/include`
Answer: try
bundle update sqlite3

I saw it here
http://stackoverflow.com/questions/34151296/cannot-install-sqlite3-gem

Answer: Did you have SQLite3 installed in system?
If you're using MacPorts:
sudo port install sqlite3
or Brew:
brew install sqlite3

Can't install sqlite


James-Stein Estimator with unequal variances

Question: Every statement I find of the James-Stein estimator assumes that the random variables being estimated have the same (and unit) variance.
But all of these examples also mention that the JS estimator can be used to estimate quantities with nothing to do with each other. The wikipedia example is the speed of light, tea consumption in Taiwan, and hog weight in Montana. But presumably your measurements on these three quantities would have different "true" variances. Does this present a problem?
This ties into a larger conceptual problem that I don't understand, related to this question: James-Stein estimator: How did Efron and Morris calculate $\sigma^2$ in shrinkage factor for their baseball example? We compute the shrinkage factor $c$ as follows:
$$ c = 1 - \frac{(k-3) \sigma^2} {\sum (y - \bar{y})^2} $$
Intuitively, I would think that the $\sigma^2$ term is actually $\sigma^2_i$ -- different for each quantity being estimated. But the discussion in that question talks only about using the pooled variance...
I would really appreciate if anyone could clear up this confusion!
Comment: If the variance is $D = \mbox{diag}(\sigma_1^2, \ldots, \sigma_n^2)$ we can just left-multiply by $D^{-1/2}$ to get back to the James-Stein problem. If $D$ is unknown, but each "observation" in the problem is a sample mean calculated on the basis of $m_i$ observations we can estimate $D$ with some $\hat D$ and hope that we also get a James-Stein situation if we pre-multiply by $\hat D^{-1/2}$ instead.
Comment: @guy: this is a sensible suggestion (+1), however this will result in the same shrinkage factor for all variables, whereas one would want to shrink variables differently, depending on their variance/uncertainty. See the answer that I have just posted.
Comment: @amoeba Sure; I wasn't suggesting my estimator was practical, only that it illustrated why people say the things OP mentioned in his/her second paragraph.
Answer: This question was explicitly answered in the classical series of papers on James-Stein estimator in the Empirical Bayes context written in the 1970s by Efron & Morris. I am mainly referring to:

Efron and Morris, 1973, Stein's Estimation Rule and Its Competitors -- An Empirical Bayes Approach
Efron and Morris, 1975, Data Analysis with Stein's Estimator and Its Generalizations
Efron and Morris, 1977, Stein's Paradox in Statistics

The 1977 paper is a non-technical exposition that is a must read. There they introduce the baseball batting example (that is discussed in the thread you linked to); in this example the observation variances are indeed supposed to be equal for all variables, and the shrinkage factor $c$ is constant.
However, they proceed to give another example, which is estimating the rates of toxoplasmosis in a number of cities in El Salvador. In each city different number of people were surveyed, and so individual observations (toxoplasmosis rate in each city) can be thought of having different variances (the lower the number of people surveyed, the higher the variance). The intuition is certainly that data points with low variance (low uncertainty) don't need to be shrunken as strongly as data points with high variance (high uncertainty). The result of their analysis is shown on the following figure, where this can indeed be seen to be happening:

The same data and analysis are presented in the much more technical 1975 paper as well, in a much more elegant figure (unfortunately not showing the individual variances though), see Section 3:

There they present a simplified Empirical Bayes treatment that goes as follows. Let $$X_i|\theta_i \sim \mathcal N(\theta_i, D_i)\\ \theta_i \sim \mathcal N(0, A)$$ where $A$ is unknown. In case all $D_i=1$ are identical, the standard Empirical Bayes treatment is to estimate $1/(1+A)$ as $(k-2)/\sum X_j ^2$, and to compute the a posteriori mean of $\theta_i$ as $$\hat \theta_i = \left(1-\frac{1}{1+A}\right)X_i = \left(1-\frac{k-2}{\sum X_j^2}\right)X_i,$$ which is nothing else than the James-Stein estimator.
If now $D_i \ne 1$, then the Bayes update rule is $$\hat \theta_i = \left(1-\frac{D_i}{D_i+A}\right)X_i$$ and we can use the same Empirical Bayes trick to estimate $A$, even though there is no closed formula for $\hat A$ in this case (see paper). However, they note that

... this rule does not reduce to Stein's when all $D_j$ are equal, and we instead use a minor variant of this estimator derived in [the 1973 paper] which does reduce to Stein's. The variant rule estimates a different value $\hat A_i$ for each city. The difference between the rules is minor in this case, but it might be important if $k$ were smaller.

The relevant section in the 1973 paper is Section 8, and it is a bit of a tougher read. Interestingly, they have an explicit comment there on the suggestion made by @guy in the comments above:

A very simple way to generalize the James-Stein rule for this situation is to define $\tilde x_i = D_i^{-1/2} x_i, \tilde \theta_i = D_i^{-1/2} \theta_i$, so that $\tilde x_i \sim \mathcal N(\tilde \theta_i, 1)$, apply [the original James-Stein rule] to the transformed data, and then transform back to the original coordinates. The resulting rule estimates $\theta_i$ by
  $$\hat \theta_i = \left(1-\frac{k-2}{\sum [X_j^2 / D_j]}\right)X_i.$$ This is unappealing since each $X_i$ is shrunk toward the origin by the same factor.

Then they go on and describe their preferred procedure for estimating $\hat A_i$ which I must confess I have not fully read (it is a bit involved). I suggest you look there if you are interested in the details.
Answer: Page 12 of Demaret's MSc thesis discusses the JS estimator for unequal variances. But some additional deciphering is required of the notation. For example:

$Y$, $\eta$ & $s^*$ are defined as rescaling variables but not later
mentioned

$s$ ($n \times$ the sample variance ?) is said to follow ``$\sim$'' the distribution
$\sigma^2 \chi_n^2$ distribution but how do you then explicitly code this distribution?


prove that the sequence $\{F(n)\}$ converges.

Question: Let $g:\mathbb{R^+}\rightarrow\mathbb{R^+}$ be a function such that $\log g(x)$ is concave, and $\displaystyle{\lim_{x\to\infty}}\frac{g(x+w)}{g(x)} = 1$ for each $w>0$ . Then:
Fact 1: $g(x)$ is increasing;

Fact 2: $\log g(x)$ has derivative $\frac{g^\prime_{-}(x) + g^\prime_{+}(x) }{2g(x)}$ except, possibly, on a countable set, where $g^\prime_{+}(x)$ and $g^\prime_{-}(x)$ are right and left derivatives, respectively;
Fact  3: $\frac{g^\prime_{-}(x) + g^\prime_{+}(x) }{2g(x)}$ is decreasing and non-negative on $\mathbb{R}^+$.

My question is:
Let
\begin{align*}
F(n) = \sum_{i=1}^n \frac{g^\prime_{-}(i) + g^\prime_{+}(i) }{2g(i)} - \log g(n),
\end{align*}
prove that the sequence $\{F(n)\}$ converges.
Thanks in advance.
Comment: This seems fairly easy for $g\in C^1.$
Answer: Alternative solution:
Fact 1: Let $f: \mathbb{R} \to \mathbb{R}$ be a convex function.
Then, $f(x) - f(y) \ge c(x-y)$ for any real numbers $x, y\in \mathbb{R}$ and $c\in [f'_{-}(y), f'_{+}(y)]$.
See: https://en.wikipedia.org/wiki/Subderivative
https://www.sintef.no/globalassets/project/evitameeting/fho.pdf
A proof of Fact 1 is also given later.
From Fact 1, by letting $f = -\log g$ and $c = \frac{f'_{-}(y) + f'_{+}(y)}{2}$, we have,
for any $x, y\in (0, \infty)$,
$$-\log g(x) + \log g(y) \ge -\frac{g'_{-}(y) + g'_{+}(y)}{2g(y)}(x-y). \tag{1}$$
By letting $x = i, y = i+1$; $x = i+1, y = i$ respectively, we have, for $i = 1, 2, \cdots$,
$$\frac{g'_{-}(i+1) + g'_{+}(i+1)}{2g(i+1)} \le \log g(i+1) - \log g(i) \le
\frac{g'_{-}(i) + g'_{+}(i)}{2g(i)}. \tag{2}$$
Let $n < m$ be two positive integers.
From (2), we have
$$\sum_{i=n}^{m-1} \frac{g'_{-}(i+1) + g'_{+}(i+1)}{2g(i+1)} \le \sum_{i=n}^{m-1} (\log g(i+1) - \log g(i)) \tag{3}$$
and
$$\sum_{i=n+1}^{m} (\log g(i+1) - \log g(i)) \le \sum_{i=n+1}^{m} \frac{g'_{-}(i) + g'_{+}(i)}{2g(i)} \tag{4}$$
which results in
$$\log \frac{g(m+1)}{g(m)} - \log\frac{g(n+1)}{g(n)} \le \sum_{i=n+1}^{m} \frac{g'_{-}(i) + g'_{+}(i)}{2g(i)} - \log\frac{g(m)}{g(n)} \le 0. \tag{5}$$
Thus, we have
$$\log \frac{g(m+1)}{g(m)} - \log\frac{g(n+1)}{g(n)} \le F(m) - F(n) \le 0.\tag{6}$$
Since $\lim_{k\to \infty} \log \frac{g(k+1)}{g(k)} = 0$, we know that
$\{F(n)\}$ is a Cauchy sequence. Thus, $\{F(n)\}$ has a limit denoted by $\gamma_g$.
Then, let us prove that
$$0 \le \gamma_g + \log g(1) \le \frac{g'_{-}(1) + g'_{+}(1)}{2g(1)}. \tag{7}$$
From (2), we have
$$\sum_{i=1}^{n-1} \frac{g'_{-}(i+1) + g'_{+}(i+1)}{2g(i+1)} \le \sum_{i=1}^{n-1} (\log g(i+1) - \log g(i))\tag{8}$$
and
$$\sum_{i=1}^{n} (\log g(i+1) - \log g(i)) \le \sum_{i=1}^n \frac{g'_{-}(i) + g'_{+}(i)}{2g(i)}\tag{9}$$
which results in
$$\log\frac{g(n+1)}{g(n)} \le \sum_{i=1}^n \frac{g'_{-}(i) + g'_{+}(i)}{2g(i)} - \log g(n) + \log g(1) \le
\frac{g'_{-}(1) + g'_{+}(1)}{2g(1)}. \tag{10}$$
By using $\lim_{n\to \infty} \log\frac{g(n+1)}{g(n)} = 0$, the desired result follows.
$\phantom{2}$
Proof of Fact 1: We have, for any $r < t < y < u < v$,
$$\frac{f(r) - f(y)}{r- y} \le \frac{f(t)-f(y)}{t-y} \le \frac{f(u)-f(y)}{u-y} \le \frac{f(v)-f(y)}{v-y}.$$
Indeed, for example, $\frac{f(r) - f(y)}{r- y} \le \frac{f(t)-f(y)}{t-y}$ can be written
as $f(t) = f(\frac{t-r}{y-r}\cdot y + \frac{y-t}{y-r}\cdot r) \le \frac{t-r}{y-r}f(y) + \frac{y-t}{y-r}f(r)$ which is true by the definition of convex functions.
Thus, $f'_{+}(y) = \lim_{x \to y+} \frac{f(x)-f(y)}{x-y}$ and $f'_{-}(y) = \lim_{x \to y-} \frac{f(x)-f(y)}{x-y}$ both exist,
and $f'_{-}(y) \le f'_{+}(y)$; moreover, if $x > y$, we have $f'_{+}(y) \le \frac{f(x)-f(y)}{x-y}$
which results in $f(x) - f(y) \ge f'_{+}(y)(x-y) \ge c(x-y)$ for any $c\in [f'_{-}(y), f'_{+}(y)]$,
and if $x < y$,
we have $\frac{f(x)-f(y)}{x-y} \le f'_{-}(y)$ which results in $f(x)-f(y) \ge f'_{-}(y)(x-y) \ge c(x-y)$
for any $c\in [f'_{-}(y), f'_{+}(y)]$. We are done.
Comment: River Li. Thanks a lot. I have a question: why $c\in [f^\prime_{-}(y), f^\prime_{+}(y)]$? and  how to get the relationship (5)?
Comment: @koohyareslami   Did you see the wikipedia link? From (3), $\sum_{i=n+1}^{m} \frac{g'_{-}(i) + g'_{+}(i)}{2g(i)} \le \log g(m) - \log g(n)$. From (4), $\log g(m+1) - \log g(n+1) \le \sum_{i=n+1}^{m} \frac{g'_{-}(i) + g'_{+}(i)}{2g(i)}$.
Comment: River Li. I see but I still didn't understand why $c\in [f^\prime_{-}(y), f^\prime_{+}(y)]$?
Comment: @koohyareslami  I give a proof of Fact 1.
Comment: River Li. Thanks. Why the sequence $\{F(n)\}$  is a Cauchy sequence?
Comment: @koohyareslami   You can see https://brilliant.org/wiki/cauchy-sequences/ or  https://mathworld.wolfram.com/CauchySequence.html
Answer: The following can give ideas (and is too long for a comment).
You can bound the sum from below and above :
\begin{align*}
&&\int_1^{n+1} \frac{g'_{-}(x) + g'_{+}(x) }{2g(x)} dx&\leq\sum_{i=1}^n \frac{g'_{-}(i) + g'_{+}(i) }{2g(i)} \leq \int_0^n \frac{g'_{-}(x) + g'_{+}(x) }{2g(x)} dx\\
\Leftrightarrow &&\log g(n+1)-\log g(n)-\log g(1) &\leq F(n)\leq \log g(0)\\
\Leftrightarrow &&\log \frac{g(n+1)}{g(n)}-\log g(1) &\leq F(n)\leq -\log g(0)
\end{align*}
so when $n$ tends to infinity the left term tends to $0$. This do not guaranty convergence as is but maybe be of help.


Visualizing a covering space of a torus

Question: Note that the fundamental group of the torus $T$ is given by $\pi_1(T)=\Bbb Z \times \Bbb Z =<a,b~|~aba^{-1}b^{-1}>$. By the Galois correspondence of covering spaces, I know that there is a unique (up to covering isomorphism) covering space of $T$ corresponding to (the conjugacy class of) the subgroup $<a^3, a^2b>$. Can I visualize this covering space using square diagrams? I want to describe the covering space explicitly, but I have no idea.
Answer: Subdivide the universal covering space $\mathbb R^2$ in the usual manner as squares, with vertical lines $x=m$ and horizontal lines $y=n$ for integers $m,n \in \mathbb Z$.
To visualize the desired covering space, draw two vectors based at the origin: $v = \langle 3,0 \rangle$ corresponding to $a^3$; and $w = \langle 2,1 \rangle$ corresponding to $a^2 b$. Let $P$ be the parallelogram determined by the vectors $v,w$, which form two sides of $P$, the other two sides then being determined. Now glue opposite sides of $P$ to form a quotient space $S$. And as usual, gluing opposite sides of the unit square $Q = [0,1] \times [0,1]$ gives the covering space $T$.
You can then use the pattern of intersections of the parallelograph $P$ with unit squares $[m,m+1] \times [n,n+1]$ to define the desired covering map $Q \mapsto T$.
It is theoretically more straightforward to view this construction using orbit spaces of deck transformations. If I have $(a,b) \in \mathbb R^2$ let me use $\tau_{(a,b)}$ to represent the translation $\tau_{a,b}(x,y) (x+a,y+b)$. Thus we can think of $T$ as the quotient of $\mathbb R^2$ by the action of the deck group $\langle \tau_{(1,0)},\tau_{(0,1)} \rangle$ (with fundamental domain $[0,1] \times [0,1]$), so
$$T = \mathbb R^2 / \langle \tau_{(1,0)},\tau_{(0,1)} \rangle
$$
and we can think of $S$ as the quotient of $\mathbb R^2$ by the action of the deck group $\langle \tau_{(3,0)}, \tau_{(2,1)} \rangle$ (with fundamental domain $P$), so
$$S = \mathbb R^2 / \langle \tau_{(3,0)}, \tau_{(2,1)} \rangle
$$
This way, the desired quotient map $S \mapsto T$ can be precisely defined as the map
$$S = \mathbb R^2 / \langle \tau_{(3,0)}, \tau_{(2,1)} \rangle \mapsto  = \mathbb R^2 / \langle \tau_{(1,0)},\tau_{(0,1)} \rangle = T
$$
that is induced by the identity map $\mathbb R^2 \mapsto \mathbb R^2$.
Answer: All of the coverings of the torus are homeomorphic to $\mathbb R^2,\mathbb R\times S^1$, or $T=S^1\times S^1$. Any subgroup of $\mathbb Z^2$ spanned by two independent elements corresponds to the covering space $T$. What changes is the covering map, which in this case is given by $p(x,y)=(3x,2x+y)$.

Visualizing a covering space of a torus


Porque este código não está a calcular a média corretamente?

Question: Eu provavelmente hoje devo estar muito mau em matemática para não conseguir fazer um código simples que calcule a média de dois valores... Eu simplesmente não entendo o que fiz errado...
BTW, espero que a média seja calculada assim...(soma de vários valores / quantidade de valores; neste caso valor1 + valor2 /2)
double valor1 = 0; // Valor a calcular
double valor2 = 0; // Segundo valor a calcular
double resultado = 0; // Variável para mostrar o resultado

Console.Write("Escreva o primeiro valor da para calcular a média: "); // Perguntar o primeiro valor
valor1 = double.Parse(Console.ReadLine()); // Leitura + conversão da string para double
//
Console.Write("Escreva o segundo valor: "); // Perguntar o segundo valor
valor2 = double.Parse(Console.ReadLine()); // Leitura + conversão da string para double

resultado = valor1 + valor2 / 2; // Cálculo da média -> valor1 + valor2 / 2

Console.WriteLine("O resultado é: " + resultado); // Mostrar o resultado
Console.Read(); // Pausar a aplicação e permitir o utilizador ler o resultado

Comment: Da uma olhada no comentário acima, você está esquecendo os parênteses que separam a soma da divisão. Se você não colocar a soma no parênteses, a conta irá fazer primeiro a divisão e depois a soma
Comment: Qual é o resultado que está dando? Você chegou a testar colocando o `valor1` e o `valor2` entre parenteses? Tipo, `(valor1 + valor2)/2`?
Comment: @Willian Se por exemplo, o primeiro valor for 10 e o segundo for 5 o resultado é 12,5. Eu acho que deveria ser 7,5 ou não sei matemática???
Comment: @Willian Não sabia que isso era possível em C#, pensava que apenas permitia cálculos "simples"... Vou tentar! Se funcionar, obrigado!
Answer: Conforme apresentado nos comentários, o erro está no resultado = valor1 + valor2 /2.
Pela matemática, se você quiser que a soma seja feita antes da divisão, você tem de colocar a soma entre parênteses e depois dividir. No caso ficaria:
resultado = (valor1 + valor2) / 2
Comment: Muito obrigado por explicar que era possível executar cálculos deste tipo em C#, parece que tenho ainda tenho muito a aprender... :)
Comment: Por nada, boa sorte :D
Answer: O problema se encontra na linha:
resultado = valor1 + valor2 / 2;
Acontece que a operação de divisão e multiplicação sempre tem prioridade sobre a adição e subtração, caso você queira especificar que uma adição é mais importante no seu contexto você deve fazer o seguinte:
resultado = (valor1 + valor2) / 2;

Dessa forma a adição será executada primeiro e o resultado será divido pelo número 2.
Espero ter ajudado.
Comment: Obrigado por responder, mas alguém respondeu primeiro... Mas obrigado pela ajuda na mesma :D
Comment: De nada, boa sorte na sua jornada.


Measure zero and compact then content zero

Question: I'm trying to show that a compact set $E$ with measure zero has content zero. It seems simple because for every $\varepsilon$ I take a subcover of the rectangles, but the issue I'm facing here is that I can't take a subcover because the rectangles are closed. I tried using the interior but what guaranties that for every $\varepsilon > 0$ I'll have a set of rectangles such that $E \subset\bigcup_{k \in \Bbb{N}} R_k^\circ $ and $\sum_{k=1}^\infty \mu (R_k) < \varepsilon$.
Definition measure zero for every $\varepsilon >0$ we have a set of closed rectangles such that $E \subset\bigcup_{k \in \Bbb{N}} R_k$ and $\sum_{k=1}^\infty \mu (R_k) < \varepsilon$. Content zero is the same but with finitely many rectangles.
Note I don't know any measure theoretic concepts besides those.
Answer: Hint: a closed rectangle is contained in a slightly larger open rectangle.
For example, you can keep the same center and double the sidelengths. The new (open) rectangle has area $4$ times the area of the old (closed) rectangle. Choose a finite cover of those.


Programmatically change drawable and shape color in layer list?

Question: I have a layer list like this:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/black" />
        </shape>
    </item>

    <item
        android:drawable="@drawable/ic_pin"
        android:adjustViewBounds="true"
        android:scaleType="fitXY" />
</layer-list>

How can I programmatically change the color of the shape as well as the drawable?
For example, how can I change the color to #FF0000 and change the drawable to @drawable/ic_globe programmatically?
Answer: Please Add id attribute to item of layer like below code:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/bg_layer">
        <shape android:shape="oval">
            <solid android:color="#000000" />
        </shape>
    </item>

    <item
        android:id="@+id/top_layer"
        android:drawable="@drawable/ic_pin"
        android:adjustViewBounds="true"
        android:scaleType="fitXY" />
</layer-list>

Code in Java
LayerDrawable bgDrawable = (LayerDrawable) getResources().getDrawable(R.drawable.border);/*drawable*/
GradientDrawable bg_layer = (GradientDrawable)bgDrawable.findDrawableByLayerId (R.id.bg_layer);/*findDrawableByLayerId*/
bg_layer.setColor(Color.RED);/*set color to layer*/
bgDrawable.setDrawableByLayerId(R.id.top_layer,getResources().getDrawable(R.drawable.ic_globe));/*set drawable to layer*/
image.setImageDrawable(bgDrawable);/*set drawable to image*/

Here R.drawable.border is my drawable, R.id.bg_layer and top_layer are ids of items of layerlist in drawable
I hope its work for you


Como poderia melhorar essa query de consulta SQL com sub querys?

Question: São muitos sub selects, como poderia melhorar esta consulta no MySQL e fazer um SUM do max do 'total_points_period'?
Pegar o total de pontos por um período da tabela "user_bigdata" e o total de pontos da tabela "olympic_players_niveis" de acordo com o período.
A tabela user_bigdata, é uma lista onde tem todos os pontos por usuário do sistema, porém preciso pegar e somar todos os pontos máximos da relação de mesma action_id, já a pontuação de olympic_player_niveis é a pontuação de uma determinada competição por período, que tem relação com a competição ativa na tabela olympic, onde contém o período inicial e final desta competição. Eu gostaria de relacionar ambas sem precisar de uma subquery com outra subquery.
A query atual:
SELECT `tab`.`user_id`, `tab`.`total_points`,
                    (SELECT max(CASE WHEN ub.action_type = 'points' and ub.value <> 'giveup' and  ub.created between start_date and end_date THEN CAST(ub.value as UNSIGNED) ELSE 0 END ) AS pontos_obtidos
                        FROM user_bigdata ub
                        WHERE ub.usr_id = user_id
                        AND (ub.action_type in ('points') and ub.type_utilization=2)
                        group by ub.action_id, ub.question_id) as total_points_period
                     FROM (
            SELECT
                SUM(opn.points) AS `total_points`,
                ol.start_date AS start_date,
                ol.end_date AS end_date,
                u.ID as user_id,
                u.avatar_json

            FROM
                `olympic_players_niveis` AS `opn`
                    INNER JOIN
                olympics ol ON (ol.active = 1 AND ol.ID = opn.olympic_id AND ol.ID = 1 )
                   INNER JOIN users u ON(`opn`.`user_id`=u.ID)
            GROUP BY `opn`.`user_id`
            ORDER BY SUM(opn.points) DESC , `opn`.`created` DESC , FIELD(opn.tip_resolved, 1, NULL) DESC
            ) AS `tab` ORDER BY `total_points` DESC, `total_points_period` DESC

Tabelas:
CREATE TABLE `olympic_players_niveis` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `nivel_id` int(4) NOT NULL,
  `points` int(6) NOT NULL,
  `olympic_id` int(4) DEFAULT NULL,
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `tip_resolved` int(1) DEFAULT NULL,
  `updated` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`ID`),
  KEY `fk_olympic_players_Olympics1_idx` (`olympic_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

CREATE TABLE `olympics` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `active` int(11) NOT NULL,
  `title` text CHARACTER SET utf8 NOT NULL,
  `badge_id` int(11) NOT NULL,
  `person_1` int(3) DEFAULT NULL,
  `person_2` int(3) DEFAULT NULL,
  `initial_talk_id` int(3) DEFAULT NULL,
  `end_talk_id` int(3) DEFAULT NULL,
  `logo` varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
  `regulation` text COLLATE utf8_unicode_ci,
  `start_date` datetime DEFAULT NULL,
  `end_date` datetime DEFAULT NULL,
  `free_users_access` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `user_bigdata` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `usr_id` int(4) NOT NULL,
  `action_type` varchar(50) NOT NULL,
  `action_id` int(4) NOT NULL,
  `question_id` int(4) NOT NULL,
  `data_type` varchar(30) NOT NULL,
  `value` varchar(100) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `start` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `end` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `seconds` int(5) NOT NULL,
  `answer` varchar(5) DEFAULT NULL,
  `answer_correct` int(2) DEFAULT NULL,
  `type_utilization` int(2) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  KEY `indice1` (`value`,`data_type`,`action_id`,`usr_id`),
  KEY `type_value` (`data_type`,`value`,`usr_id`),
  KEY `indiceusuario` (`usr_id`),
  KEY `actiontimeid` (`action_type`,`action_id`,`question_id`),
  KEY `action_search` (`usr_id`,`action_type`,`data_type`,`action_id`),
  KEY `index_busca_atividade` (`usr_id`,`action_type`,`question_id`,`created`,`value`,`action_id`),
  KEY `index_recentes` (`usr_id`,`action_id`,`action_type`),
  KEY `index_data` (`created`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE `users` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(200) CHARACTER SET utf8 NOT NULL,
  `role` varchar(50) CHARACTER SET utf8 NOT NULL,
  `password` varchar(500) CHARACTER SET utf8 NOT NULL,
  `status` int(11) NOT NULL,
  PRIMARY KEY (`ID`),
  KEY `idx_role` (`ID`,`role`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Os dados seriam basicamente estes:
INSERT INTO `user_bigdata` (`ID`, `usr_id`, `action_type`, `action_id`, `question_id`, `value`, `type_utilization`) VALUES ('', 1, 'points', 1, 0, 200, 2);
INSERT INTO `user_bigdata` (`ID`, `usr_id`, `action_type`, `action_id`, `question_id`, `value`, `type_utilization`) VALUES ('', 1, 'points', 1, 0, 100, 2);
INSERT INTO `user_bigdata` (`ID`, `usr_id`, `action_type`, `action_id`, `question_id`, `value`, `type_utilization`) VALUES ('', 1, 'points_tips', 1, 0, 50, 2);

INSERT INTO `user_bigdata` (`ID`, `usr_id`, `action_type`, `action_id`, `question_id`, `value`, `type_utilization`) VALUES ('', 2, 'points', 1, 0, 100, 2);
INSERT INTO `user_bigdata` (`ID`, `usr_id`, `action_type`, `action_id`, `question_id`, `value`, `type_utilization`) VALUES ('', 2, 'points', 1, 0, 80, 2);
INSERT INTO `user_bigdata` (`ID`, `usr_id`, `action_type`, `action_id`, `question_id`, `value`, `type_utilization`) VALUES ('', 2, 'points_tips', 1, 0, 10, 2);

INSERT INTO `user_bigdata` (`ID`, `usr_id`, `action_type`, `action_id`, `question_id`, `value`, `type_utilization`) VALUES ('', 3, 'points', 1, 0, 'giveup', 2);

INSERT INTO  `olympics` (`ID`, `active`, `title`, `start_date`, `end_date`) VALUES (1, 1, "Jogo", 0, DATE_ADD(NOW(), INTERVAL -1 DAY), DATE_ADD(NOW(), INTERVAL +10 DAY));

INSERT INTO  `olympic_players_niveis` (`ID`, `user_id`, `nivel_id`, `points`, `olympic_id`, `created`, `tip_resolved`)
VALUES ('', 1, 1, 30, 1, now(), null);

INSERT INTO  `olympic_players_niveis` (`ID`, `user_id`, `nivel_id`, `points`, `olympic_id`, `created`, `tip_resolved`)
VALUES ('', 2, 1, 130, 1, now(), null);

INSERT INTO `users` (`ID`, `username`, `role`, `password`) VALUES (1, 'ononnoonon1', 'nonono', 'onnonono');
INSERT INTO `users` (`ID`, `username`, `role`, `password`) VALUES (2, 'ononnoonon2', 'nonono', 'onnonono');
INSERT INTO `users` (`ID`, `username`, `role`, `password`) VALUES (3, 'ononnoonon2', 'nonono', 'onnonono');

SQL Fiddle
Comment: Acredito que seja importante informar os dados que deseja na consulta. Facilita uma possível melhoria na sua `query` ou até uma nova `query` para satisfazer sua necessidade.
Comment: @ThiagoMagalhães, editei a pergunta, para ficar mais claro.
Comment: Coloque um exemplo real usando o sql fiddle: E comecei um [aqui](http://sqlfiddle.com/#!9/24910f/1), mas os dados que voce colocou não estão corretos
Comment: http://sqlfiddle.com/#!9/d26084/1
Comment: Aqui tem um exemplo, se fosse 2 registros: http://sqlfiddle.com/#!9/7c2e4/2
Comment: @IvanFerrer, estou tentando entender as relações e a query que você apresentou e surgiu uma dúvida. Essa query está certa? Pois os pontos de `user_bigdata` por player mostrado na `query` é 200, mas olhando os dados de teste do link que passou, acredito que um teria 200 e outro 180.
Comment: Na verdade, há um problema na query, ele deveria fazer um SUM no max(...).
Answer: @Ivan, vi que você alterou sua tabela, adicionando uma nova tabela e alterando o campo de outras. Mas como o seus dados de INSERT não estão atualizados, acabei não podendo testar com a nova estrutura.
Mas com base na estrutura desse exemplo que você passou, criei esse SQL. Acredito que isso atende a sua necessidade e também acredito que seja de fácil entendimento e adaptação.
Segue a query:
SELECT
SUM(opn.points) as points,
new.total_pontos,
ol.start_date AS start_d,
ol.end_date AS end_d,
opn.user_id
FROM olympic_players_niveis AS opn
INNER JOIN olympics ol ON (ol.active = 1 AND ol.ID = opn.olympic_id)
INNER JOIN (
    SELECT ub.usr_id, SUM(ub.value) as total_pontos
    FROM user_bigdata ub
    INNER JOIN olympic_players_niveis o ON (o.ID = ub.usr_id)
    INNER JOIN olympics ol ON (ol.id = o.olympic_id)
    WHERE ub.action_type IN ('points') AND ub.created BETWEEN ol.start_date AND ol.end_date AND ol.active = 1
    GROUP BY ub.usr_id
) new ON (new.usr_id = opn.user_id)
GROUP BY opn.user_id

Caso deseje retornar apenas um usuário especifico, basta colocar
WHERE opn.user_id = ?

Antes do GROUP BY, onde o ? você substitui pelo id do usuário.
Comment: o problema é que vai ficar pesada a forma que vc fez, mas eu consegui fazer aqui de uma forma melhor... vou postar a solução. Obrigado.
Answer: Como eu fiz para resolver os problemas:
select user_id_int, total_points , sum(pontos_obtidos_period) as pontos_periodo, u.avatar_json, ano from (

                    SELECT user_id_int, total_points , ub.action_id, ub.question_id, start_date, end_date, ano,
                    max(CAST(ub.value as UNSIGNED))  AS pontos_obtidos_period

                    FROM (
                            SELECT
                                SUM(opn.points) AS `total_points`,
                                ol.start_date AS start_date,
                                ol.end_date AS end_date,
                                opn.user_id as user_id_int,
                                (case when sc.scc_year is null then opi.opi_school_year else sc.scc_year end) as ano

                            FROM
                                `olympic_players_niveis` AS `opn`
                                    INNER JOIN
                                olympics ol ON ( ol.ID = opn.olympic_id AND ol.ID = 7 )

                                 left JOIN school_class_members as scm ON(scm.usr_id = opn.user_id)
                                 left JOIN Schools as s ON(s.ID = scm.sch_id)
                                 left JOIN school_classes as sc ON(sc.sch_id = s.ID and scm.cls_id = sc.scc_id and sc.scc_status = 1)
                                 left join Planos as p on p.ID = s.plan and (p.data_exp > CURDATE())
                                 left join olympic_players_initial opi on opi.usr_id = opn.user_id

                            GROUP BY `opn`.`user_id`
                            ORDER BY `opn`.`created` DESC , FIELD(opn.tip_resolved, 1, NULL) DESC
                    ) AS `tab`

                    left join user_bigdata ub
                    on (ub.usr_id = user_id_int
                    and ub.action_type = 'points'
                    and ub.value <> 'giveup'
                     and ub.created between start_date and end_date)

                    group by user_id_int, ub.action_id
) as tab4
inner join Users u on u.ID = user_id_int

group by user_id_int
order by total_points desc, pontos_periodo desc;


IntelliJ IDEA 13 highlighting of SQL statement

Question: IntelliJ IDEA 13 includes new improvement Statement highlighting in Database Console:

How to change color of highlighting ?
Answer: You have to go to: Setting -> Editor -> Colors  & Fonts -> General -> Injected language fragment -> Background
Comment: Please give me more exact instruction. Which of the options I must to change in SQL section ?
Comment: @DozortsevAnton Sorry - I've read your question one more time and just fixed my answer :)
Comment: @Anton Dozortsev, Setting -> Editor -> Colors & Fonts -> General -> **Code ** -> Injected language fragment -> Background


What are key points to determine SQL Server version cost?

Question: I have to design website to start migration of sql server from one version to another and based on client database requirements we will tell him the cost of this migration and which sql server version is best to use?
Comment: You aren't actually asking a question. Vote to close.
Answer: There are some important factors in choosing SQL Server version and edition on following topics:

How many CPU cores it can utilize
How much RAM it can utilize
What key feature it supports. for instance some versions do not support columnstore index or partitioning. Read the feature list.
Number/Size of supported databases
AFAIK some editions have better query optimization. (I'm not sure though)
Do you need BI feature? How about Replication, High Availability features like Mirroring? Always On? Data Encryption? Data/Index Compression?

You need to know, volume of data and concurrent users to decide.
Some features are critical for large volume databases and some are not.


Solving $x\; \leq \; \sqrt{20\; -\; x}$

Question: This is how I tried to solve it:
By squaring both sides:
$x^{2}\; \leq \; 20\; -\; x$
$x^{2}\; +\; x\; -\; 20\; \leq \; 0$
Thus
$-5\; \leq \; x\; \leq \; 4$
However, it seems that values less than -5 work too. Where did I go wrong?
Comment: Note that $\sqrt{20-x} > 0$ for all $x < 0$, and thus $x < 0 < \sqrt{20-x}$ for all $x < 0$. By squaring both sides, you lose information about the negative solutions to this inequality.
Comment: The issue is that $x \mapsto x^2$ is not monotone on $\mathbb{R}$, so you need to take care when squaring. For example, with $x=-16$, the inequality is satisfied, but if you square both sides, the 'squared' inequality is not true.
Comment: Ah.. ok. Thanks!
Comment: +1 for "However, it seems that values less than -5 work too" and +1 for @AWertheim's comment.. well asked.. well said :)
Comment: In agreement with @AWertheim, I point out that "where you went wrong" is exactly at the first step. For when $a\le b$, it is false that then necessarily $a^2\le b^2$, since one or both of $a$, $b$ may be negative.
Answer: A related problem. You should advance formaly as
$$ (x+5)(x-4) \leq 0 $$
$$ \implies ( (x+5)\leq 0 \quad \cap  \quad (x-4)\geq 0 ) \cup  ( (x+5)\geq 0 \quad \cap  \quad (x-4)\leq 0 ) $$
Comment: @AndréNicolas: thanks for the comment.
Answer: $\sqrt{20-x}$ is a decreasing function (everywhere it's defined), while $x$ is an increasing function. Therefore the fact that they're equal at $x=4$ implies that $x\le\sqrt{20-x}$ precisely for $x \le 4$.

Solving $x\; \leq \; \sqrt{20\; -\; x}$


Running CLI scripts from create-react-app

Question: In a new app created with create-react-app, how can I run a command-line script? The following fails:
$ npx create-react-app foo
[snip]
$ cd foo/
$ echo "import {App} from './src/App.js';" > test.js
$ node test.js
/private/tmp/foo/test.js:1
import {App} from './src/App.js';
       ^

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:718:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
    at Module.load (internal/modules/cjs/loader.js:641:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:837:10)
    at internal/main/run_main_module.js:17:11

I've tried running both babel-node and node --harmony. I just need some way to have the script run successfully whether it's changing the script or changing how I run it.
Comment: Why did you think that *would* work? You're bypassing all of the babeling and webpacking that CRA sets up for the source code; it's not magically patching Node for you. If you run a script like that it has to be compatible with your current Node version (see also `--harmony`).
Comment: I didn't really think it would work. But I haven't found a way to make it work. I know  it's not magic.
Comment: Could you use `require` for that script? When you say you tried `babel-node`, could you expand on that? At the moment the directory and presence of a CRA app is irrelevant, you'd get the same syntax error anywhere.
Comment: @jonrsharpe I can't use `require` because the script uses ES6 syntax. When I say I tried `babel-node`, I mean I just ran that instead of `node`. I think the presence of the CRA app is relevant because there may be some existing machinery there that could be used.
Comment: That's not some immutable property of it, surely; in your example it uses that syntax because *that's the syntax you used*. Evidently you can edit it because that's what your answer does, using the require syntax.
Comment: @jonrsharpe My point was that I can't edit the file that I'm requiring. Plus I want to be able to require other files from my React app which also use ES6, JSX, etc.
Answer: Adding the following at the beginning of the script solved my issue:
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';

require('@babel/register')({
  presets: [
    '@babel/preset-env',
    'babel-preset-react-app'
  ]
});

Answer: As an alternative to adding the require and the options in the file, you can also make a .babelrc file in root to hold the options and the use -r for the require flag in cli , -r @babel/register as the alternative if you don't want to add the require statement in the file. Just an alternative.
.babelrc file in root:
{
 "presets": [
   [
     "@babel/preset-env",
     {
       "targets": {
         "node": "current"
      }
     }
   ]
  ]
 }

then in cli
node -r @babel/register executeMyFileWithESModules.js

for more details on setup see:  https://stackoverflow.com/a/55309534/4263440
or
https://stackoverflow.com/a/55428342/4263440


Expressão regular 6 casas decimais

Question: Alguém me saber dizer se é possível criar uma expressão regular com as seguintes características:

valor entre 31.000000 e 43.000000
o valor pode ter 6 casas decimais, mas deve estar no intervalo de 31 a 43.

O que eu tenho é o seguinte:
^(\+|-)?(\d\.\d{1,6}|[1-6]\d\.\d{1,6}|1[1-7]\d\.\d{1,6}|43\.0{1,6})$

é possível definir um valor minimo?
Comment: Precisa ser regex? Dependendo da linguagem, é possivel que já tenha algum recurso mais simples do que regex.
Comment: eu trabalho com formulários online e só posso criar as regras por regex ou então por regras de validação. se não der para fazer por regex tento criar por regras de validação que me digam se o valor é >31 e <43
Comment: mas pediram-me para tentar fazer por regex primeiro
Comment: Sem tempo agora, mais dá uma melhorada aqui: `^[3-4]{1}+[0-9]{1}.?[0-9]{6}$`. Primeiro caractere 3 ou 4 + Segundo caractere entre 0 e 9 o ponto separando, após a interrogação é opcional 6 dígitos entre 0 e 9
Comment: Formulário online? HTML? Se sim, JavaScript está aí para salvar sua vida. Só não se esqueça que é preciso fazer a validação a nove de servidor também, que validação a nível de cliente é só para melhorar a experiência de uso, mas não pode ser usado como única maneira de verificação/validação.
Comment: O intervalo é aberto ou fechado? Nos comentários está escrito que os valores extremos não devem pertencer ao intervalo
Comment: @PauloRicardo Há alguns erros na sua Regex: **1** `{1}` não é quantificável por `+`. **2** `.` o ponto final corresponde qualquer caractere e não `/.` o ponto literalmente e o `?` corresponde a 0 ou 1, porém deve haver ponto. **3** Valores como 47.000000 e 30.000000 são aceitos pela lógica de regex utilizada.
Comment: @danieltakeshi, não deixei como resposta pois já sabia que haveria erros, tentei deixar só um ponto de partida, no intuído de ajudar apesar de esta "engatinhando" com Regex, Mais obrigado pelo alerta, já estou exercitando o uso da classe, para entender um pouco melhor.
Answer: Concordando com todas as ressalvas que uma validação via expressão regular não é o caminho, podemos divagar no assunto.

Não custa lembrar, só porque você pode fazer, não quer dizer que deve fazer.
Vou repetir o aviso que coloquei nesta resposta, porque não custa nada alertar:

Você tem a arma, eu te dou a munição, mas você quem decide se deve atirar na própria perna ou não.

A resposta do @JJoao trata de intervalos fechados. Eu li que em seus comentários você cita que o intervalo é aberto. Então, pondero, como deveria ser para intervalos abertos?
Vamos falar aqui primeiramente em intervalos unitários, depois extrapolamos para um intervalo qualquer.
Aberto no limite superior
O primeiro caso é se o limite superior for aberto. Por exemplo, o intervalo [42, 43) aceita o valor 42.999999, mas não 43.000000.
Para reconhecer esse intervalo, com seis casas decimais, não tem segredo algum. Só extrapolar a ideia do @JJoao para o número desejado.
42(\.[0-9]{1,6})?

Essa expressão é fechada no limite inferior é aberta no superior. Aceita de 42 a 42.999999, assim como 42.0000, mas não aceita 43.
Aberto no limite inferior
E no limite inferior? Foi fácil no limite superior, será que também será no inferior?
Para isso, precisamos reconhecer qualquer string depois do . que contenha pelo menos um número diferente de zero, limitado a 6 números.
Basicamente essa é a mesma pergunta de gerar uma string de 1 a 6 dígitos em que pelo menos um desses dígitos seja diferente de zero. Consegui isto para responder, não consegui simplificar. Eu separei as alternativas abaixo, a resposta seria colocar elas todas intercaladas com |.
[1-9][0-9]{0,5}
0[1-9][0-9]{0,4}
0{2}[1-9][0-9]{0,3}
0{3}[1-9][0-9]{0,2}
0{4}[1-9][0-9]{0,1}
0{5}[1-9]

De certo modo, para um total de m casas decimais no máximo, começando com z zeros a esquerda, a fórmula de criação dessas subexpressões é:
0{z}[1-9][0-9]{0,m-z-1}

Sendo que 0 <= z <= m - 1, com z e m inteiros não negativos.
Então, para reconhecer um número no intervalo aberto inferior (e apenas inferior), a regex seria um tanto quanto grande. Para (42,43], seria:
42\.([1-9][0-9]{0,5}|0[1-9][0-9]{0,4}|0{2}[1-9][0-9]{0,3}|0{3}[1-9][0-9]{0,2}|0{4}[1-9][0-9]{0,1}|0{5}[1-9])|43(\.0{1,6})?

Já se fosse aberto em ambas as extremidades, a expressão não precisaria considerar o inteiro 43 ao final:
42\.([1-9][0-9]{0,5}|0[1-9][0-9]{0,4}|0{2}[1-9][0-9]{0,3}|0{3}[1-9][0-9]{0,2}|0{4}[1-9][0-9]{0,1}|0{5}[1-9])

Unindo intervalos consecutivos
Bem, começamos com intervalos unitários, que começam em números inteiros. E como seria a união desses intervalos caso eles sejam consecutivos?
A primeira alternativa seria colocar as expressões de cada intervalo agrupadas entre ( parentes ) e intercaladas com |.
Mas, poderíamos fazer melhor, não é?
O intervalo mais bem comportado é o intervalo fechado no limite inferior porém aberto no limite superior. Ele contém uma parte constante (a parte inteira do número) seguida da seguinte expressão:
(\.[0-9]{1,6})?

Quando estamos intercalando diversos desses intervalos, basta colocar essa expressão do lado direito e por do lado esquerdo as constantes separaras por | ou alguma outra expressão que remeta a isso. Por exemplo, [32,43) pode ser representado assim:
(3[2-9]|4[0-3])(\.[0-9]{1,6})?

Do lado direito, a expressão mágica que representa o intervalo unitário fechado no limite inferior porém aberto no superior. Do lado direito, uma expressão que representa todos os inteiros no intervalo passado.
Caso seja necessário lidar com um intervalo fechado no limite superior, basta adicionar o valor limite seguido de 0 a 6 zeros. Como se fosse uma união entre o intervalo fechado no começo porém aberto no final e do número individual: [42,43) U {43}
42(\.[0-9]{1,6})?|43(\.0{1,6})?

As outras uniões podem continuar sendo aplicadas normalmente, então fazer [32, 43] é fazer [32,42) U [42,43) U {43}:
(3[2-9]|4[0-3])(\.[0-9]{1,6})?|43(\.0{1,6})?

Para intervalo aberto, entretanto, a fórmula vai ficar grande. Não vou por como ficaria a expressão aqui, ela seria ilegível de qualquer sorte. O pensamento, entretanto, seria isolar um único intervalo unitário aberto em ambas as extremidades, então tratar o resto como intervalos fechados no limite inferior e aberto no superior. Tipo, (32,43] pode ser interpretado como (32,33) U [33,43], ou então como (32,33) U [33,43) U {43}.
Comment: @GuilhermeLautert, responder sempre, simplificar nunca, e complicar preferencialmente =D Só estou lembrando aqui da pergunta que fizeram sobre reconhecer anos bissextos com regex
Comment: Obrigada! Ajustei ao que era pretendido e consegui. (Também tinha de fazer para um intervalo negativo).
Comment: Obrigada pela resposta e pela explicação. Fiquei a perceber muito melhor as expressões regulares
Comment: @JeffersonQuesado, gostei de sua resposta, ate pelo fato de querer dar o máximo de informações possíveis, contudo creio que você complicou mais do que necessitava. Geralmente as coisas são mais simples do que parecem. Mesmo assim muito bem :D
Comment: excelente Jefferson, esclareceu algumas duvidas que tinha.
Answer: Não é o caminho ideal, mas tendo que ser:
^((3[1-9]|4[0-2])(\.\d{0,6})?|43(\.0{0,6})?)$

Comment: Obrigada. Já consegui fazer :D

Expressão regular 6 casas decimais


Pointwise, uniform, normal and $L^p$ convergence of $\sum\limits_{n=1}^{\infty}\frac{e^{-nx}}{1+n^2}$

Question: Study the pointwise, uniform, normal and on $L^p$ convergence of the series
$$\sum_{n=1}^{\infty}\frac{e^{-nx}}{1+n^2}$$
My approach
Let $f_n(x)=\frac{e^{-nx}}{1+n^2}$, it's easy to show that:

$f_n(x)\ge 0 \ \ \ \forall x\in\mathbb{R}$;
$\lim_{n\to+\infty}f_n(x)=0 \iff x\in [0,+\infty)$
$\sum_{n=1}^{+\infty}\frac{e^{-nx}}{1+n^2}\le\sum_{n=1}^{+\infty}\frac{1}{n^2+1}\le\sum_{n=1}^{+\infty}\frac{1}{n^2}<+\infty$

where the first inequality of (3) is true for $x\ge0$. From (3) I know that the series is normally convergent on $[0,+\infty)$, hence it converges pointwise and uniformly on the $[0,+\infty)$.
Now $\sum\frac{e^{-nx}}{n^2+1}$ is a normal convergent series in $[0,+\infty)$ because $\sum\frac{1}{n^2}$ converges.
Let $S_k(x)=\sum_{n=1}^{k}\frac{e^{-nx}}{1+n^2}$ and $S(x)=\sum_{n=1}^{+\infty}\frac{e^{-nx}}{1+n^2}$, how can I prove that
$$\|S-S_k\|_{p}^{p}=\int_{0}^{+\infty}\left|\sum_{n=k+1}^{+\infty}\frac{e^{-nx}}{n^2+1}\right|^pdx \longrightarrow 0$$ for $k\to +\infty$.
My first idea is to use the Lebesgue dominated convergence theorem: if so, the limit operator goes trough the integral, hence $\|S-S_k\|_{p}^{p}\to 0$ for $k\to +\infty$ because $$\sum_{n=k+1}^{+\infty}\frac{e^{-nx}}{n^2+1}$$ is the tail of a convergent series (then $\sum_{n=k+1}^{+\infty}\frac{e^{-nx}}{n^2+1}\to 0$ for $k\to+\infty$).
Now I have many troubles to find $g(x)$ such that $\left|\sum_{n=k+1}^{+\infty}\frac{e^{-nx}}{n^2+1}\right|^p\le g(x)$ and $g(x)\in L^1([0,+\infty))$
I try this:
$$\sum_{n=k+1}^{+\infty}\frac{e^{-nx}}{n^2+1}\le\sum_{n=k+1}^{+\infty}e^{-n x}=\frac{e^{-(k+1)x}}{1-e^{-x}}$$
and now I'm stuck because of  $1-e^{-x}$.
Every other inequalities I found are useless to find a proper $g(x)$. Maybe there is a easier way to solve this. Need help. Thanks.

Edit: This part

where the first inequality of (3) is true for $x\ge0$. From (3) I know
  that the series is normally convergent on $[0,+\infty)$, hence it
  converges pointwise and uniformly on the $[0,+\infty)$

is logically incorrect, in fact 3. must be $$3. \ \frac{e^{-nx}}{n^2+1}\le\frac{1}{n^2+1}\le\frac{1}{n^2}$$ and so $\sum\frac{e^{-nx}}{n^2+1}$ is a normal convergent series in $[0,+\infty)$ because $\sum\frac{1}{n^2}$ converges.
Comment: Another English way should be "normal convergence"
Comment: Your reasoning for 3. is incorrect.
Comment: What do you call « total convergence »?
Comment: @mathcounterexamples.net Sorry, it's the translation of the italian expression: "convergenza totale". I know now that in English, the "total convergence" is called "Weierstrass M-test". More precisely, in Italy we say that a series $\sum f_n(x)$ is "totalmente convergente" in a set $E$ if and only $\exists (M_n)_n\ge 0$ such that $|f_n(x)|\le M_n \ \ \ \forall x\in E$ and $\sum M_n<+\infty$.
Comment: Thanks @LucaMac.
Comment: @zhw Why? $e^{-nx}\le 1 \ \ \ \forall x\in[0,+\infty)$ so $\frac{e^{-nx}}{n^2+1}\le\frac{1}{n^2+1}\le\frac{1}{n^2}\ \ \ \forall n\ge 1.$
Comment: Now it's correct! Notice the difference between this and what you wrote in 3.
Comment: @zhw, from the double inequality it follows that $\sum \frac{e^{-nx}}{n^2+1}\le\sum\frac{1}{n^2+1}\le\sum\frac{1}{n^2}$, right? It is a conseguence of the squeeze theorem. Is it correct?
Comment: Of course. But that doesn't prove uniform convergence. What you wrote in the comment proves uniform convergence by Weierstrass M.
Comment: @zhw. ?!...!! O_O you're right! Gosh, I should have paid more attention. Thanks
Comment: You're welcome. It's a common mistake.
Answer: $$\left|\sum_{n=k+1}^{+\infty}\frac{e^{-nx}}{n^2+1}\right|^p\le e^{-px} \cdot \left(\sum_{n\geq 1}\frac{1}{(n^2+1)}\right)^p = c^p \cdot e^{-px}$$
And $$ \int_0^{+\infty} c^p \cdot e^{-px} = \frac{c^p}{p} < + \infty $$
So you can use dominated convergence theorem and show the $L^p$ convergence.
Comment: I'm trying to figure out how you did it (+1) anyway!
Comment: I just used $e^{-nx} \leq e^{-x}$ for any $n \geq 1$
Comment: That was ok. I didn't understand why in the second term of inequality (RHS) $n\ge 1$...but now is clear! Thank you so much! (I am a donkey)
Comment: Well, I just increased the number of things to sum. I had to do so because $g$ must not depend on $k$.
Comment: Yes, you're right. Well done sir, chapeau! Can you use another name for the sum of $\left[\sum_{n\ge 1}\frac{1}{(n^2+1)}\right]^p$? $k$ and $k(p)$ can be confusing.
Comment: Yes, you're right! I have edited my post.


How to approach variable image sizes for Image Classification?

Question: I am working on classification of brain tumors. The dataset is comprised of brain images from various angles, with a border and mask of the tumor position. I have cropped the rectangle that contains the tumor, as the other parts of the image are irrelevant and vary due to the different angles from which the image is taken. Now I am left with a series of images of the tumor, each belonging to 1 of 3 possible cases of tumor. But to train this data for classification, I need to have the 2d image array in a uniform shape I believe.
Possible approaches:
1) Crop each image to a fixed size (say 100x100). But this would result in loss of data and also depending on position of the tumor in image, I could be facing uneven crops due to reaching the edge of the image.
2) Pad the image to a fixed shape, bigger than the biggest cropped image shape (say 350x350). But again this would introduce noise in the data I suppose, and I'm not sure how can I pad the image uniformly across all 4 sides of the rectangle.
As these don't seem viable, I'm looking for other solutions to tackle this problem.
Comment: Larger resolution would be better but how many images do you have and what are their resolution before and after cropping? If you have thousands of images larger resolution will require a lot of GPU to normalize and training could be slow.
Comment: @Suleiman I have 3064 images. The shape of the cropped tumor image varies from around (15, 15) to (350, 300)
Comment: 15x15 is quite small in dimension to extract useful features, what machine learning algorithm are you using for classification?
Comment: @SuleimanVery few images will actually be that small though. The mean shape is (75, 75). I will be trying out various classification algorithms and present a study of which performs the best. So I'll start with SVM, Decision Trees and CNN.
Comment: OK, in that case I guess 100x100 might be a good size to start with and then if possible experiment with larger and smaller sizes to see if performance improves.
Answer: The common approach is to crop the tumor on each image. You will obtain different tumor image size. Then rescale the tumor images to the smallest one. Choose wisely the resampling technic for the rescale depending on the algorithm you will use for classification. The fastest one would be nearest neighborhood resampling, a smoother one would be linear interpolation, the ultimate one can be spline interpolation.
Comment: Yes, this seems like the best approach, I'll likely scale all to the mean shape.


Calculating Radon Nikodym derivative

Question: I am trying to calculate the Radon-Nikodym derivative for $\mu = m + \delta_0$ where $m$ is Lebesgue measure over a compact subset of $\mathbb R$ and $\delta_0$ is Dirac measure at $0$.
Clearly, $m \ll \mu$ and $\mu \perp \delta_0$. Therefore, the Radon-Nikodym derivative exists, as both measures are $\sigma-$finite.
Let $f$ be a function such that $m(E) = \int_E fd\mu$. What is $f$ explicitly? Can I say $ 1_{X \setminus\{0\}} = f$ ??
Answer: Yes, the Radon-Nikodym derivative is $1_{X\setminus\{0\}}$. Note that $1_{X\setminus\{0\}}\ne1$ ($\mu$-a.e.) as $0$ is an atom for $\mu$.
Comment: Does it make sense to find Radon Nikodym derivative at a point for measures?
Comment: At an atom? Of course.
Answer: The Radon-Nikodym derivative is $1_{X\setminus\{0\}}$. Note that $1_{X\setminus\{0\}}\ne1$ ($\mu$-a.e.) as $0$ is an atom for $\mu$.
Add:
Notice that $1_{X}$ is wrong, because μ({0})==1!=0, the R-N derivative is unique in the sense of μ-a.e.

Calculating Radon Nikodym derivative


Get Json object or loop

Question: I have the following json:
<code>{"sockets":{"16":true},"length":1}
</code>
I need to get the values of the sockets, already tried with loop and several other ways more can not. Can someone help me?
Already I tried this:
<code>$.each(json, function(idx, obj) {
    alert(obj);
});
</code>
Comment: Is the json object in string format, and what does the alert give you?
Answer: <code>var obj= {"sockets":{"16":true},"length":1}

$.each( obj, function( key, value ) {
  alert(JSON.stringify(key) + ": " + JSON.stringify(value) );
});
</code>
codepen-http://codepen.io/nagasai/pen/ZOBgvK
Comment: To get only value of sockets ,use alert(stringify(obj));
Comment: Updated codepen with same variable names and created another for the same code - http://codepen.io/nagasai/pen/wWoVmB  Hope this works
Comment: You know how I would do to just get `{"16":true}` ?
Comment: Yes!! The value you need is actually the only 16
Comment: $.each( json, function( index, obj ) {
  alert(JSON.stringify(json.sockets)) ;
});
Comment: It will alert two times , as we are alerting it in the .each loop , so it will display 2 times due to length of object
Comment: Did you check in the codepen which i have provided - http://codepen.io/nagasai/pen/wWoVmB
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/115454/discussion-between-naga-sai-a-and-rene).

Get Json object or loop


Calculating the value with large exponents

Question: I'm trying to solve $2014^{2015}$ $\pmod {11}$, is there a trick or tip to break the problem down to make it easier to solve?
Comment: What do you mean by solve? To simplify it?
Comment: What do you mean by *"solve it"*?
Comment: I guess you really want something along the lines of $2014^{2015} \bmod m$?
Comment: Is there a method to solve it without a calculator?
Comment: I actually made a mistake and forgot the modulus, I edited it
Comment: Then note that $a\equiv b \pmod{m} \implies a^k \equiv b^k\pmod{m}$ for all $k$, and recall Fermat's (so-called little) theorem.
Comment: @DanielFischer:  In this case, Fermat's little theorem is overkill.
Comment: @RossMillikan Yeah, I only looked at the remainder of $2014$ modulo $11$ after I wrote the comment. But since in general, that's useful, I've left it stand.
Comment: To show a modulus in $\LaTeX$, you can use \pmod {modulus}.  You don't need the braces for a single digit.  It gets you the font and the parentheses.
Answer: Your result will have $6658$ digits in base $10$.  Alpha seems up to the task, but I got tired of clicking on More Digits.  Are you sure you don't want this modulo some number?
Now that you added the $\pmod {11}$, it becomes much easier.  Note that $2014 \equiv 1 \pmod {11}$
Comment: The answer can be attained with very little calculation.
Comment: @NovaDenizen:  The $\pmod {11}$ was not there when this answer was written.  I have accounted for it now.
Comment: How would I solve this without a calculator or Alpha
Comment: In the specific case here, you have $1^{2015}$, which is easy.  If the base is not $1$, you use [Euler's theorem](http://en.wikipedia.org/wiki/Euler%27s_theorem) to reduce the exponent modulo $\phi(n)$, Euler's totient function of the modulus.  In this case, $\phi(11)=1, 2015 \equiv 5 \pmod {10}$, so the exponent becomes $5$
Answer: It's important to remember that if $a \equiv b \mod m$ then $a \cdot c \equiv b \cdot c \mod m$.  From this you can prove if $a \equiv b \mod m$ then $a^c \equiv b^c \mod m$.
So what is the remainder of 2014 divided by 11?
Comment: 183 is the remainder
Comment: @ChetSteadman No, 183 is the quotient.
Comment: woops I meant remainder is less than 1
Comment: @ChetSteadman No, the remainder is not less than 1.
Comment: okay I'm tracking now, 2014 Mod 11 = 1. What is the next step?
Answer: If you are trying to do this efficiently on a computer or something, you can use a binary expansion of $2015$ to calculate the number.
$$2015 = 1 + 2 + 4 + 8 + 16 + 64 + 128 + 256 + 512 + 1024$$
thus
$$x^{2015} = x\cdot x^2\cdot x^4\cdot x^8\cdot x^{16}\cdot x^{64}\cdot x^{128}\cdot x^{256}\cdot x^{512}\cdot x^{1024}$$
This method is much faster than $x \cdot x \cdot x \cdots $.
Comment: Your answer misses a much easier method.
Comment: The original question didn't have any moduli.


How do you drop an undo file from MySQL cluster?

Question: I was hoping someone had an answer for an issue I'm having with MySQL Cluster. Let's say you do this:
<code>ALTER LOGFILE GROUP lg1
ADD UNDOFILE 'undofile1.dat'
INITIAL_SIZE 63995904
ENGINE=ndbcluster;
</code>
and then  you realize you made a mistake (say, with the initial_size setting) and want to either modify the initial size setting for undofile1.dat or even better, drop the new undo file entirely.
How do you do that?
Thanks in advance!
Answer: No one seems to know how (it's possible there's no implemented way to do this).
What I used as a workaround was to dump the current data into a file, edit the dumpfile to modify/take out the creation of the undo file in question then re-import afterwards.
It's not perfect, and it might not be a viable approach in some cases, but it worked.