intuition behind stability in different norms

Question: I want to understand connection between property of solution and energy estimates. Say I have a pde $u_t=Lu$ and I proved that there exist a unique solution that is in $C^2$. In pde analysis using the energy methods we can estimate the norm of the solution by the initial data. For example $\frac{\partial \vert\vert^2 u(x,t) \vert\vert}{\partial t}\leq 0$. Now the norm that is typically used in the book is $L^2$ norm. Can I show similar estimates using $H^1$ norm? And if I do so, what would that imply? That's is how do I decide which norm to choose in order to get the estimates for the norm of the solution? thanks!
Answer: I think you meant to say that there exists a unique solution $u\in C^{2,1}(\mathbb{R}^n \times (0,T))\bigcap C(\mathbb{R}^n \times [0,T])$(? or other reasonably regularity for $u$), it has $C^2$ and $C^1$ differentiability in space and time respectively, also continuous up to the boundary, due to the regularity you gave, I am guessing $L$ should be a second order linear differential operator, for example, $L = \Delta$ then you have a homogeneous heat equation on the whole space, and I will use this as an example to illustrate the intuition behind the "energy estimate", so the language may be a little bit informal.
The estimate you gave was:
$$
\frac{d}{d t} \|u(\cdot,t)\|_{L^2(\mathbb{R})}^2 \leq 0
$$
If we go back to the derivation of the heat equation, the solution $u$ represents concentration of a certain quantity(heat, chemical substance, probability density), the estimate above implies two things:

The concentration decays as we marching in time without any "input", otherwise we should have $u_t = Lu + f$ and the estimate would be different.
The $L^2$-integrability implies that there is control of this concentration outside a ball of certain radius, just think of the normal distribution density function, the total concentration far from the origin is rather small.

Now back to your question, why the $L^2$-norm for energy estimate? Because it is most natural estimate originated from the weak formulation of this equation. Why not the $H^1$-norm for the energy estimate? By $H^1$-norm, I am guess you would like to get the same estimate for $\displaystyle \frac{d}{d t}\|u(\cdot,t)\|_{H^1(\mathbb{R})}^2$, the meaning of this would be that you have decaying property on the flux density $\boldsymbol{F} = -\nabla u$! Unfortunately for general $L$ and even for $\Delta$, this is not true, physically speaking, the flux $-\nabla u$ describes the flow across $\partial \Omega$ from the higher concentration region to lower concentration region in the following sense:
$$
\frac{d}{dt}\int_{\Omega} u = - \int_{\partial \Omega} \boldsymbol{F}\cdot \boldsymbol{n} \,dS
$$
And that the concentration is decaying over time doesn't imply the flux has the temporal decaying property too. Secondly $\displaystyle \frac{d}{d t}\|u(\cdot,t)\|_{H^1(\mathbb{R})}^2$ is not well-defined for $u$ either.
However, we could have another type of estimate for $\|u(\cdot,t)\|_{H^1(\mathbb{R})}^2$, let's say for the heat equation:
$$
\left\{
\begin{aligned}
u_t &= \Delta u & \text{ for }x\in \mathbb{R}^n
\\
u(0,x) &= g(x)
\end{aligned}
\right.
$$
Apply the same technique that gets us to the energy decaying estimate:
$$
\frac{1}{2}\frac{d}{dt}\int_{\mathbb{R}^n} u^2(x,t) dx + \int_{\mathbb{R}^n} |\nabla_x u(x,t)|^2 dx = 0
$$
then we integrate w.r.t time on $[0,t]$ for any $t&ltT$ we have:
$$
\frac{1}{2}\int_{\mathbb{R}^n} u^2(x,t) dx + \int^t_0 \int_{\mathbb{R}^n} |\nabla_x u(x,\tau)|^2 dx d\tau = \frac{1}{2}\int_{\mathbb{R}^n} g(x)^2 dx
$$
hence we have a rather primitive estimate
$$
\int^T_0 \int_{\mathbb{R}^n} |\nabla_x u(x,\tau)|^2 dx d\tau \leq \frac{1}{2}\int_{\mathbb{R}^n} g(x)^2 dx
$$
Comment: Jon, thanks for you answer, you got my question precisely. You have mentioned that $\frac{d\vert\vert u(⋅,t)\vert\vert^2_{H^1}}{dt}$ is not well-defined for u either. What do you mean? Because I think I can show for the case of $u_t=(a(x)u_x)_x$ stability in $H^1$, however I am still working on showing that for  $u_t=(a(x)u_x)_x+b(x)u_x+c(x)u+d(x)$. I can't find that in the book so I am in process of getting this result and your answer made me think it is impossible...
Comment: @Medan You are correct, I was too indoctrinated by the weak formulation, and thought of the weak solution situation. If $\displaystyle \|\frac{d}{d t}u(\cdot,t)\|_{H^1(\mathbb{R})}^2$ exists, we are requiring the time derivative of the gradient is $L^2$-integrable too, this isn't necessarily true for weak solution though. However you could refer to L.C.Evans's PDE book Page 360 about the improved regularity for the linear evolution equation, and there is a bound for the second order time derivative which is related to the growth rate of $\nabla u$.
Comment: @Medan and by any chance you are working on the design of a stable numerical scheme for the variant coefficient parabolic equation? If you are, I am thinking Stig Larsson and Vidar Thomée's book Partial Differential Equations With Numerical Methods may have something that you need.
Comment: thanks for suggestion, I am working on proving stability of CN for variable coefficients advection-diffusion. So far have it in L^2 but would be nice to see in other norms. I will take a look at Evans book as well. I think I can show the stability in H^1 as well but that requires equation to be strong parabolic and a(x) degenerates in my equation. May be those books have something. thanks!


Melhor forma para acessar componentes da activity - MVP

Question: Estou utilizando o padrão MVP no meu projeto Android.
Em minha MainActivity tenho os seguintes componentes:
private Paciente paciente;
private EditText nome, cpf, cpfTutor, telefone;
private CheckBox checkbox;

logo depois tenho esse metodo que é iniciado quando se clica em um botão:
private void initPaciente() {
    paciente = new Paciente();

    paciente.setNome(nome.getText().toString());
    paciente.setCpfTitular(cpf.getText().toString());
    paciente.setCpfTutor(cpfTutor.getText().toString());
    paciente.setTelefone(telefone.getText().toString());
    paciente.setDataCadastro("27/01/2017");
    paciente.setStatus(status.getSelectedItem().toString().toLowerCase());
    paciente.setTimestamp(new Timestamp(System.currentTimeMillis()).getTime());

    paciente.save;
}

Bom, se eu intendi bem o conceito do MVP esse tipo de acesso direto ao objeto paciente não é válido.
Como que eu acesso esses componentes EditText nome, cpf, cpfTutor, telefone; pelo Presenter?
Eu tentei acessar assim:
private PacienteActivity activity = (PacienteActivity) getContext();
Paciente paciente = new Paciente();
paciente.setNome(activity.nome.getText().toString());
// ...

Mas desse modo tenho que deixar os atributos como public (que não acho bacana), ou criar um monte de geters que vão poluir meu codigo.
Comment: eu estudei pelo blog do Thiengo: http://www.thiengo.com.br/mvp-android, e tem um vídeo no YT: https://www.youtube.com/watch?v=WRGqmqZwEcQ, também dele, que explica melhor como utilizar esses conceitos.
Comment: Se está preocupado em seguir padrões e "boas práticas", reveja o facto de Paciente ser responsável por se gravar a si próprio.
Comment: Sim, isso no exemplo acima eu tinha antes de seguir os padrões. Hoje o objeto é responsável por apenas controlar seus dados, quem o persiste agora é a Model. Mas de qualquer forma, muito obrigado pela dica.
Answer: Dentro do padrão MVP (Model-View-Presenter), a construção do objeto Paciente deve ser feita dentro do seu Presenter e sua View (seja ela Activity ou Fragment) fica responsável apenas por ceder as informações para seu Presenter.
Primeiro, você precisa criar um contrato (interface) entre seu Presenter e View:
public interface PacienteView {
    String getNome();
    String getCpfTitular();
    ...
}

E a implemente dentro de sua View:
public class PacienteFragment implements PacienteView {

    @Override
    void getNome() {
        return nome.getText().toString();
    }

    @Override
    void getCpfTitular() {
        return cpf.getText().toString();
    }

    ...
}

A parte "confusa" vem agora: seu Presenter precisa acessar essas informações de alguma maneira. Você tem várias opções de fazer isso, mas aproveitando que no Java nós conseguimos ter uma instância de uma interface, precisamos de uma instancia nossa interface PacienteView com nosso Presenter, para assim podemos construir o objeto Paciente:
public class PacientePresenter {

    private PacienteView view;

    public void configuraPaciente() {
        Paciente paciente = new Paciente ();

        paciente.setNome(view.getNome());
        paciente.setCpfTitular(view.getCpfTitular());
        ...
    }
}

Agora, dentro da nossa View, precisamos atrelar a intância view (instanciada acima) ao nosso Presenter. Para fazer isso, é bem tranquilo. É algo como um setOnClickListener(this) que você deve estar acostumado a utilizar:
public class PacientePresenter {

    private PacienteView view;

    public void setView(PacienteView view) {
        this.view = view;
    }
}

...

public class PacienteFragment implements PacienteView {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        presenter = new SubscriptionsPresenter();

        presenter.setView(this);
    }
}

Pronto! Dessa maneira seu Presenter irá ter a instância da View e você pode adicionar o que for preciso nos métodos. Agora, para salvar seu objeto Paciente, ficaria algo como:
public class PacienteFragment implements PacienteView {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        presenter = new SubscriptionsPresenter();

        presenter.setView(this);
    }

    ...

    private void initPaciente() {
        presenter.configuraPaciente();
    }
}

Comment: E quando eu for receber dados de um servidor, por exemplo? É o presenter que deverá fazer a request?
Comment: @Mr_Anderson O `Presenter` é responsável por providenciar as informações para a `View`. Nesse caso, o `Presenter` deve trabalhar em conjunto com outros patterns (como `Client` ou `Repository`) para realizar essas requisições.


Prove that the general formula for a sequence $a_n$ is $\frac{(-1)^n}{n!}$

Question: Here is a sequence $a_n$ where the first five $a_n$ are:
$a_1=-\frac{1}{1!}$
$a_2=-\frac{1}{2!}+\frac{1}{1!\times1!}$
$a_3=-\frac{1}{3!}+\frac{2}{2!\times1!}-\frac{1}{1!\times1!\times1!}$
$a_4=-\frac{1}{4!}+\frac{2}{3!\times1!}+\frac{1}{2!\times2!}-\frac{3}{2!\times1!\times1!}+\frac{1}{1!\times1!\times1!\times1!}$
$a_5=-\frac{1}{5!}+\frac{2}{4!\times1!}+\frac{2}{3!\times2!}-\frac{3}{3!\times1!\times1!}-\frac{3}{2!\times2!\times1!}+\frac{4}{2!\times1!\times1!\times1!}-\frac{1}{1!\times1!\times1!\times1!\times1!}$
For each term in $a_n$:
1.The denominator enumerates all combinations that sum to $n$.
2.The numerator represents the number of permutations possible for that combination.
3.If the number of elements in the combination is odd, the term is negative.
I have computed the first five $a_n$ mentioned above, and it appears that $a_n=\frac{(-1)^n}{n!}$. However, I am struggling to provide a proof for this formula. Could someone please assist me?
Comment: I invented it when I try to solve my problem about Taylor expansion. I probably would not ask for help online if it is just an exercise in a math book.
Comment: An obvious remark, though not sure it makes things simpler: you can take the numerator to be $1$ if you consider instead *ordered* integer partitions (for each permutation you get one of them). Then [there are](https://math.stackexchange.com/questions/31562/number-of-ordered-partitions-of-integer) $2^{n-1}$ ordered partitions of $n$, so $2^{n-1}$ terms in $a_n$.
Comment: Then, multiplying everything by $n!$, you have a sum of multinomial coefficients, that you can split according to partition length, each sub-sum is $u_p=\sum (n; n_1,\dots,n_p)$, with $(n;n_1\dots n_p)=n!/(n_1!\cdots n_p!)$ and the sum runs on all ordered partitions. Checking in [Abramowitz & Stegun](https://en.wikipedia.org/wiki/Abramowitz_and_Stegun), $u_p=p!S_n^p$ (24.1.2.II.B), where $S_n^p$ are [Stirling number of the second kind](https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind), and then $\sum_{p=0}^n (-1)^{n-p}p!S_n^p=1$ (24.1.4.II.B).
Comment: The second sum is a direct consequence of the relation (which can be a definition) $x^n=\sum_{p=0}^n S_n^p x(x-1)\cdots(x-p+1)$.
Comment: By 1. I assume you mean [integer partitions](https://en.wikipedia.org/wiki/Partition_(number_theory))? And 2. is the number of distinct permutations you can form with the terms of each partition?
Comment: Yes, it is exactly integer partitions and distinct permutations.
Comment: Did you invent this problem or is it an exercise?
Comment: Of course all of this needs a full proof, but at least it's a known relation.
Comment: An omission: when I wrote above *"the sum runs on all ordered partitions"*, it's with the additional constraint $n_k\ge 1$ for all $k$. That's implicit as we have split the sum in smaller sums with fixed partition length (all terms of which are $>0$).
Comment: Thank you for your meticulous and insightful answer to this problem. Your clarity in explanation is very helpful.
Comment: @Jean-ClaudeArbaut I recommend you write up an answer
Answer: We can prove this combinatorially, using a sign-reversing involution, also known as the the DIE method (Description, Involution, Exception).
First, let us split your sum up in a way such that all numerators are $1$. To do this, we take a sum over all ordered partitions of $n$ (also known as compositions of $n$), instead of just the integer partitions of $n$. For example, when $n=4$, this looks like
$$
-\frac1{4!}+\frac1{1!\cdot 3!}+\frac1{3!\cdot 1!}+\frac1{2!\cdot 2!}-\frac1{2!\cdot 1!\cdot1!}-\frac1{1!\cdot2!\cdot1!}-\frac1{1!\cdot1!\cdot2!}+\frac1{1!\cdot1!\cdot1!\cdot1!}
$$
Next, we multiply both sides of the equation to be proved by $n!$. The result is
$$
\sum_{\alpha \text{ is a composition of }n} \binom{n}{\alpha}(-1)^{\text{len}(\alpha)}=(-1)^n\tag1
$$
where...

$\alpha$ ranges over all lists of positive integers summing to $n$. Each $\alpha=(\alpha_1,\alpha_2,\dots,\alpha_k)$ for some $k\in \{1,\dots,n\}$, where $\alpha_1+\dots+\alpha_k=n$.

$\text{len}(\alpha)=k$.

$\binom{n}{\alpha}$ is the multinomial coefficient, defined by $$\binom n{\alpha}=\frac{n!}{\alpha_1!\alpha_2!\cdots \alpha_k!}.$$

Description
Thinking combinatorially, $\binom{n}{\alpha}$ counts the number of ways to put $n$ distinct items into $k=\text{len}(\alpha)$ distinct boxes, such that box number $i$ receives exactly $\alpha_i$ items for each $i \in \{1,\dots,k\}$. We are counting all such arrangements of $n$ items into some number of boxes, where every box is nonempty, and where arrangements with an even number of boxes count positively, and those with an odd number count negatively.
Involution
I will now define a way to divvy up all but one of these arrangements into pairs, where one of the pair counts positively, and the other counts negatively. This means that these pairs cancel themselves out in the count. Here is the method. Assume that the $n$ distinct objects are just the integers from $1$ to $n$. Let $P$ be a particular assignment of $\{1,\dots,n\}$ to some number of distinct boxes (numbered $1$ to $k$), where each box is nonempty. We give describe a different assignment, $P'$, which is the one $P$ will be paired with.

Say that number $1$ is in box number $i$. If $1$ is all by itself in $P$, then $1$ will be moved to the box on the left, and the box originally containing $1$ is deleted in $P'$ (unless $i=1$, see next bullet). Otherwise, if $i$ is in a box with other numbers, then $i$ gets kicked out to a new box on the right, numbered $i+1$  Example: $$P=\boxed{2,3},\boxed{1\phantom{,}},\boxed{4,5}\quad \iff \quad P'=\boxed{2,3,1},\boxed{4,5}$$

The only exception to this rule is when $1$ is all by itself, and is in box number $1$. In this case, we instead apply the exact same process to the number $2$. If $2$ is not alone, then kick it out to a new box on the left. If $2$ is alone, and $2$ is NOT in box number $2$, then we re-house $2$ to the box on its left.

The only exception to this is when $1$ and $2$ are both alone, and in boxes numbered $1$ and $2$ (resp.). In this case, we do the same process with number $3$.

$\vdots$

It should be clear that this process either adds exactly one box, or deletes exactly one box. Therefore, $P'$ has the opposite parity of $P$, and they cancel each other in the count.
Exception
There is exactly one arrangement which does not get a partner from this process. Namely, the arrangement with $n$ boxes, such that box number $i$ contains only the number $i$ for each $i\in\{1,\dots,n\}$. This is the only arrangement which is not canceled out, and it comes with a sign of $(-1)^n$. Therefore, we conclude that the entire sum in the LHS of $(1)$ is equal to $(-1)^n$, as desired.
Comment: @KniferPlasma No it does not. It is the arrangements themselves which cancel each other, because the arrangements contributing $+1$ and $-1$ to the sum are joined in pairs. There is only one arrangement that has no counterpart.
Comment: I think I didn't quite understand the answer well. When you say P' has the opposite parity of P and can cancel each other, does that mean a complete cancellation? As your example provided in the first bullet, does it mean $\frac{5!}{2! \cdot1!\cdot 2!}$ cancels $\frac{5!}{2!\cdot 3!}$ ?
Comment: @user Thanks, now I got it.


Is it common in song structure for a "Bridge" to be shorter than the verses?

Question: I am a songwriter.  I write Western Music - mostly in the Country genre.
Every song I have ever written has at least two verses and a chorus.  I don't always add a bridge as I recognize that a bridge is not essential.
Sometimes I add a bridge and often it is the same length (usually 8 bars) as the verses.  However, I have written several songs where (either through laziness, or because I felt it was enough) I wrote a bride that was only half as long as the verses.  For example the verses may be 8 bars long and the chorus may be 8 bars long but I may put in a 4 bar bridge (followed by the final repeat of the 8 bar chorus).
I know that in song writing terminology the "bridge" is often referred to as "the middle eight" thus inferring a preferance for an 8 bar bridge.
My question is, how common is it for songs to have a shorter bridge (say half the length of the verses)?  Is there a good reason to try to make the bridge the same length as the verses - or is it perfectly acceptable and/or common to have a bridge that is shorter than the verses?
Comment: There are only two kinds of music - Country and Western...
Comment: The bridge is literally a bridge, it gets you across from one part of the song to another.  If it's long an important to the song, it might be better to refer to it as something else.  That said I think this is really subjective.  Of course it is perfectly "acceptable" to have a short bridge.
Answer: 'Middle eights' can be as short as 4 and as long as 24 bars! They are just often 8 bars long - the clue's in the words! Each and every song needs what it needs, and if a song you've written sounds good with a * bar middle, then so be it. The old adage - if it sounds good...  Whilst there is no perfect formula for a song - V1, V2, Ch, V3, Ch, etc., a lot will follow similar patterns. There will always (thank goodness) be other songs which do their own thing - and it often makes them the stand-out songs. With or without a 'middle eight'.
Answer: Good question with many potential answers.
I've written with many songwriters, from Grammy winning to hobbyists and these words mean different things to different people.
Yes, many people equate "bridge" to "middle 8", however more strictly speaking the "bridge" is the "pre-chorus". Named thus as it is the "bridge" between the verse and the chorus.
There are no hard and fast definitions as I said above. People generally get a definition of what the words mean when they first start, and it sticks with them for their whole career.
Your question about how long it should be?
It should be exactly as long as you write it to be :-)
Comment: In jazz, the verse is commonly the intro.
Answer: Google for "Midge Ure Building Bridges" for a BBC radio documentary on bridges in songwriting, presented by the ex-frontman of Ultravox. When I heard it on the radio, I'm sure I remember one contributor saying one of his songs contained a 1-bar middle eight. I did intend posting a link to the BBC website but this particular programme isn't available there any more.
Here is a link to the above mentioned documentary Midge Ure Building Bridges Documentary on YouTube
Comment: Thanks Brian.  I found the documentary you referred to.  And I edited your answer to include a link.  Plus 1 - now that you have the link ;-)
Answer: Dude, you don't need to be worried about it at all! Your song might not have even a chorus (or a bridge or whatever) and be very good! Don't be concerned about the amount of bars or verses. The most important is that sounds true. Don't follow formulas! A lot of Bob Dylan's songs have no chorus or bridges. Wikipedia knows nothing! ;) sorry my english


free 2d array(matrix) of struct named "cell" where each of them as member of string(char*)

Question: Allocations :
cell **initBoard(int boardSize)
{
    int i, j, k;
    cell **matrix;
    matrix = (cell **) malloc((boardSize + 1) * sizeof(cell *));

    // init upper frame
    matrix[0] = (cell *) malloc((boardSize + 1) * sizeof(cell));
    matrix[0][0].type = (char *) malloc(3 * sizeof(char));
    matrix[0][0].type[0] = ' ';

    for (k = 1; k <= boardSize; k++)
    {
        // +1 for null char ?
        matrix[0][k].type = (char *) malloc(3 * sizeof(char));
        matrix[0][k].type = arrNo[k - 1];
    }

    // init inner rows
    for (i = 1; i <= boardSize; i++)
    {
        matrix[i] = (cell *) malloc((boardSize + 1) * sizeof(cell));

        // first letter each row
        matrix[i][0].type = (char *) malloc(3 * sizeof(char));
        matrix[i][0].type[0] = (char) (BASE_ALPHABET + i);

        // init cols
        for (j = 1; j <= boardSize; j++)
        {
            matrix[i][j].type = (char *) malloc(2 * sizeof(char) + 1);
            matrix[i][j].type[0] = EMPTY;
            matrix[i][j].type[1] = WATER; // default status
            matrix[i][j].hidesShip = NULL;
        }
    }
    return matrix;
}

Deallocations :
void freeMatrix(cell **matrix, int boardSize)
{
    int k, l;
    for (k = 0; k <= boardSize; k++)
    {
        for (l = 0; l <= boardSize; l++)
        {
            free(matrix[k][l].type);
        }
        free(matrix[k]);
    }
    free(matrix);
}

I run the code above(malloc + free are showed) and then checked memory-leak with Valgrind and got this output :
Valdrind Log
Any idea what I am doing wrong here? The Valgrind means I did one extra free command? I cant see where exactly because I moved over all cells.. maybe better understanding of pointers is required here? thanks.
Answer: matrix[0][k].type = (char *) malloc(3 * sizeof(char));
matrix[0][k].type = arrNo[k - 1];

The problem is that you are allocating memory and immidiatly after you write to the pointer holding the address. You can no longer access the memory therefore valgrind reports it as leaked.
You probably wanted to write
    matrix[0][k].type[0] = arrNo[k - 1];

Assuming that arrNo is a character array, the first assignment would be illegal since you are assigning char to char *. Your compiler should have given you a warning.


Mockito and private field / injected bean

Question: What's the standard way of accessing/setting a private field in a Java-EE-Bean for Mockito testing? The test is as follows, but the MyDao-field is null, of course, if I run the (Mockito-) test. A NullPointerException is thrown for MyDao.
But I don't want to use Reflection - is there another way to do it or is the architecture of the service bad?
The class to test:
@Stateless
public class MyServiceImpl extends AbstractService {

@Inject
private MyDao myDao;

public MyEntity findByIdOrThrow( final long id ) throws Exception {
        if ( id > 0 ) {
            final MyEntity entity = myDao.findById( id );
            if ( entity == null ) {
                throw new Exception(  );
            } else {
                return entity;
            }
        } else {
            throw new Exception(  );
        }
    }

The test class:
public class MyServiceImplTest {
private MyServiceImpl myServiceImpl;

@BeforeEach
public void setup() {
    myServiceImpl = new ServiceServiceImpl();
}

@Test
public void findByIdOrThrow() throws Exception {
    Long id = 1L;
    when( myServiceImpl.findByIdOrThrow( id ) ).thenReturn( new MyEntity() );
}}

Test class updated:
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;

import de.myapp.dao.MyDao;
import de.myapp.entity.MyEntity;

@RunWith( MockitoJUnitRunner.class )
public class ServiceServiceImplTest {

    @Mock
    public MyDao myDao;

    @InjectMocks
    public MyServiceImpl myServiceImpl;

    @Test
    public void findByIdOrThrow() throws Exception {
        final Long id = 1L;
        when( myServiceImpl.findByIdOrThrow( id ) ).thenReturn( new MyEntity() );
    }

}

Comment: Look into the `@InjectMocks` annotation - if you have an appropriate mock, it will set it to that field.
Answer: I'm supposing that MyDao is an interface. You have to do the following in your test class:
@Mock
private MyDao myDao;

@InjectMocks
private MyServiceImpl myServiceImpl;

and remove the @BeforeEach method. In this way you will inject a mock of your dao in te class. Using Mockito.when you will setup the dao-mock correctly to simulate your real dao. Do not forget to change the test declaration as it follows:
@RunWith(MockitoJUnitRunner.class)
public class MyServiceImplTest

If you are using JUnit 5 the test class declaration should be the following:
@ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)

In this last case probably you can omit the @RunWith, but I am not sure.
Comment: Thank you very much: As you said, JUnit 5 was the problem. Adding
@ExtendWith( MockitoExtension.class )
did it (@RunWith wasn't necessary).
Comment: If I do it like you suggested, I get a NullPointerException in the line with when( myServiceImpl. ...) because myServiceImpl is null. I added @RunWith( MockitoJUnitRunner.class) but it didn't help. Anyway, MyDao is an implementation, not an interface.
Comment: Can you post the updated class that gives you the NPE? Also consider that Mockito highly relies on interface and implementation separation to perform well.


How do I check if the current password that the user gives in the password reset form matches with the hashed password?

Question: I'm trying to reset a user password programmatically in Drupal 8 without the email link. For this the first step would be to check if the password(which is plain) that the user enters in the password reset form is matching with the hashed password of the respective user. And then save the new password.
Each time I hash the password, its giving a different value, this is because its salted. How shall I compare the password which the user enters in the form with the hashed password from the table.
This is the code that I have in my controller for checking the current password :
<?php
/**
* @file
* contains \Drupal\customer_profile\Controller\ProfileUpdateController
*/

 namespace Drupal\customer_profile\Controller;

 use Drupal\Core\Controller\ControllerBase;

 use Symfony\Component\HttpFoundation\JsonResponse;
 use Drupal\Core\Password\PhpassHashedPassword;
 use Drupal\Core\Password\PasswordInterface;

 class ProfileUpdateController extends ControllerBase {

   $user =\Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
   $ret = \Drupal\Core\Password\PasswordInterface::check('secret', $user);
   //$user->setPassword('secret');
   //$pass = $user->save();

   $response->password = $ret;
   return new JsonResponse($response);
  }
 }

After using \Drupal\Core\Password\PasswordInterface::check() method, for comparing the plain text password with the hash password, I get this fatal error :
Fatal error: Non-static method Drupal\Core\Password\PasswordInterface::check() cannot be called statically, assuming $this from incompatible context in C:\xampp\htdocs\ijarah\modules\custom\customer_profile\src\Controller\ProfileUpdateController.php on line 725
In Drupal 7 we have user_check_password to check the password with string and user_hash_password for hashing.
How can I approach the same in Drupal 8.
Please help.
Answer: Ok, the solution would be to use the Dependency Injection as suggested by @mradcliffe above and then use the check() method. Here is the code :
<?php
/**
* @file
* contains \Drupal\customer_profile\Controller\ProfileUpdateController
*/
namespace Drupal\customer_profile\Controller;

use Drupal\Core\Controller\ControllerBase;

use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Password\PasswordInterface;

 class ProfileUpdateController extends ControllerBase implements ContainerInjectionInterface {

  public function __construct(PasswordInterface $password_hasher, AccountInterface $account) {
   $this->passwordHasher = $password_hasher;
   $this->account = $account;
  }

   public static function create(ContainerInterface $container) {
     return new static(
       $container->get('password'),
       $container->get('current_user')
     );
   }

   public function updatePassword() {
     //global $user;
     $response = new \stdClass();
      //check the plain password with the hashed password from db
     $pass = $this->passwordHasher->check('secret', 'hashed_password_from_db');

     $response->password = $pass;
     // this will return true if the password matches or false vice-versa
     return new JsonResponse($response);
   }
  }
   ?>

After checking the password, we can save the new password using
  $user = User::load(1);
  $user->setPassword('new_password_secret');
  $user->save();

Hope this helps others :)
Answer: The hash is different every time, that's by design, because it is salted.
If you want to change the password of a user, you don't have to hash it yourself. Just load the user, set the password and save.
$user = User::load(1);
$user->setPassword('secret');
$user->save();

For the fatal error that you mentioned before, @mradcliffe already had the answer in a comment of this (now deleted) answer:

I think MigratePassword is overriding the default password service. You can try changing the constructor argument to be PasswordInterface instead of PhpassHashedPassword if the Drupal instance is using MigratePassword. Or disable migrate module.

Always type hint on the interface if an interface is available. Services might be switched out, like migrate is doing that for example.
To check the password, you just have to use the other method of that interface, \Drupal\Core\Password\PasswordInterface::check(). Those two methods are a direct match for user_hash_password() and user_check_password()
Comment: Yes, the error means that the calling code is not doing so properly. The `::` is meant for `static` methods. In order to use the check method, the calling code needs to call the check method on an instance of an object that implements PasswordInterface. Learning object-oriented programming in PHP is a bit out of scope for DA though.
Comment: Thanks for the response @Berdir, actually the reason I'm trying to hash the password is to check if the current password that the user gives in the password reset form matches with the hashed password in the table. But each time I do a hashing the value is different as you have said, its salted. Once the match is success I can proceed with new password save.
Comment: I deleted my answer because the question is "how do I check if the current password that the user gives in the password reset form matches with the hashed password?".
Comment: The question is edited. Hope this is more clear.
Comment: @mradcliffe I would actually recommend to undelete your answer. It's  pretty close, you just have to switch hash() to check().
Comment: @Berdir, I tried using **\Drupal\Core\Password\PasswordInterface::check()** with no luck. Updated the code above. Got a fatal error saying , _**Fatal error: Non-static method Drupal\Core\Password\PasswordInterface::check() cannot be called statically, assuming $this from incompatible context in C:\xampp\htdocs\ijarah\modules\custom\customer_profile\src\Controller\ProfileUpdateController.php on line 725**_ . Am I using the method wrong?
Comment: Found the solution by using the dependency injection that you have provided below. Posted the code in the answer section. Thanks for your help.
Answer: Note that this answer is superceded by Berdir's answer. I initially removed it because it no longer answers the question, and did not want to confuse anyone. It is undeleted to use as an example of using dependency injection on a service and the hash method.
The password service suggests that the argument for the constructor should be 16. Additionally the minimum value is 7 and the maximum value is 30. Anything outside of those ranges will return FALSE (on failure), which your code should really be checking to be secure.
In the following example, you would not need to worry about the constructor arguments. In this way your code is more portable if password hashing changes or someone installs a module that changes the password service.
class ProfileUpdateController extends ControllerBase implements ContainerInjectionInterface {

   public function __construct(PasswordInterface $password_hasher, AccountProxy $account) {
     $this->passwordHasher = $password_hasher;
     $this->account = $account;
   }

   public static function create(ContainerInterface $container) {
     return new static(
       $container->get('password'),
       $container->get('current_user')
     );
   }

   public function updatePassword() {
     $response = new \stdClass();
     $pass = $this->passwordHasher->hash('1234');
     if (!$password) {
        throw new \Exception('An error occurred.');
     }
     $response->password = $pass;
     return new JsonResponse($response);
   }
 }

Subjective comment: Drupal core does not return passwords as part of user objects in its Restful API because it does not consider that a secure approach.
Comment: Thanks for the response @mradcliffe, I've modified the code. This time getting a fatal error.
Comment: I think MigratePassword is overriding the default password service. You can try changing the constructor argument to be PasswordInterface instead of PhpassHashedPassword if the Drupal instance is using MigratePassword. Or disable migrate module.
Comment: Ok, I finally found the solution. I tried using the `AccountInterface` as the second parameter in the constuctor. Using AccountProxy gave me a fatal error.  And then used the `check()` instead of `hash()` . Will post the code below. Thanks for your help @mradcliffe :)


Maximum Likelihood Question

Question: The aim is to find the maximum likelihood estimator for theta. $f(x)$ is given and we can assume that $1\le x\le-1$. I have completed the steps seen in the image, however I am having difficulty differentiating the logarithmic summation.
$$f(x) = \frac 1 2 (1+\theta x)$$
$$ L(\theta \mid x_1,\ldots,x_n) = \frac 1 {2^n}\prod_{i=1}^n(1+\theta x_i)$$
\begin{align}
\ell & = \ln\left[ \frac 1 {2^n}\prod_{i=1}^n(1+\theta x_i) \right] \\[10pt]
& = \ln\frac1{2^n} + \ln\prod_{i=1}^n (1+\theta x_i) \\[10pt]
& = n\ln\frac 1 2  + \sum_{i=1}^n \ln(1+\theta x_i)
\end{align}
$$
\frac{\partial\ell}{\partial\theta} = 0 + \frac{\partial\sum_{i=1}^n \ln(1+\theta x_i)}{\partial\theta}
$$
Thanks in advance!
Comment: If $i$ goes from $0$ to $n$ rather than from $1$ to $n$, then you'd have $(1/2)^{n+1}$ rather than $(1/2)^n$.  That doesn't change your bottom line, but it makes me wonder if you intended $1$ rather than $0$. ${}\qquad{}$
Comment: There is a possibility of an endpoint maximum.  Notice that the parameter space is given by $-1/2\le\theta\le1/2$, a fact it might not hurt to bear in mind. ${}\qquad{}$
Comment: @MichaelHardy you are correct. That was my mistake it is from 1 not 0.
Comment: However, let's be clear: the $x$ values still run from $-1$ to $1$.
Comment: https://math.stackexchange.com/q/562037/321264
Answer: You want linearity of differentiation and the chain rule:
$$
\begin{align}
\frac{\partial \sum \ln (1 + \theta x_i)}{\partial \theta} &= \sum \frac{1}{1 + \theta x_i} \frac{\partial (1 + \theta x_i)}{\partial \theta} \\
&= \sum \frac{x_i}{1 + \theta x_i} = 0
\end{align}
$$
I can't see a solution to that though... I would use the Newton-Rhapson method.

Maximum Likelihood Question


Extension of Newton-Girard to matrix-indexed monomials

Question: The Newton-Girard recursions evidently give a fast algorithm for computing the elementary symmetric polynomials $e_d(x_1,\ldots,x_n):=\sum_{1\leq k_1<\cdots <k_d\leq n} x_{k_1}\cdots x_{k_d}$ in terms of power polynomials $p_d(x_1,\ldots,x_n) :=\sum_{k=1}^n x_k^d$. I am looking for an extension to summations over monomials indexed by a matrix, where the index ordering is enforced separately over each dimension.
Let $x:=\{x_{a,b}: a=1,\ldots A; b = 1,\ldots B\}$ be a two-dimensional array of variables.  I want an extension of Newton-Girard (or some other fast recursion) for computing
$$
E_d(x):=\sum_{1\leq a_1<\cdots< a_d \leq A} \sum_{1\leq b_1 < \cdots< b_d \leq B}   x_{a_1,b_1} x_{a_2,b_2} \cdots x_{a_d,b_d}
$$
Answer: Here is a recursive evaluation, that should be fast. Change of notation: $F_d[A,B]:=E_d(x)$. By recursing over the final term,
$$
F_d [A,B] = x_{A,B}\cdot F_{d-1}[A-1,B-1] + \sum_{a_d\leq A-1} x_{a_d,B}\cdot F_{d-1}[a_d -1,B-1]+\\
\sum_{b_d\leq B-1} x_{A,b_d} F_{d-1}[A-1,b_d -1] + F_d [A-1,B-1]
$$


leaflet choropleth map using dynamic value

Question: I am doing a choropleth map using leaflet and JSON data. I got a clean tutorial in leaflet site. In that tutorial the used us-states.js JSON file where the choropleth was based on the feature.properties.density feature of the JSON if I am not wrong. If we see the JS file we can found there is a field called "ID" which is state id. I have a database where I have 5 different categories of data based on state ID. Categories are population, density, male_population, female_population, literacy_rate. I am calling those data through ajax and get a GeoJSON data state-wise as follows (Its a dummy data).
[{"state_id":"01","population":"123456","density":"1234","male_pop":"65432","female_pop":"57421","literacy_rate":"98"}]
...
[{"state_id":"50","population":"123456","density":"1234","male_pop":"65432","female_pop":"57421","literacy_rate":"98"}]

I want to integrate this data as choropleth value. when I call on literacy function the variation of color will be based on literacy_rate data. I can make the changes in getcolor function category wise.
Thanks
Answer: I would recommend using Leaflet Data Visualization Framework (DVF) plugin, located here. This plugin contains a set of Layers, (such as a Choropleth layer) and a set of functions to help color-code your data.
The example located here will demonstrate the DVF Choropleth Data layer.
Using DVF, you can create a color function to create your scaling color values. For example, this function will generate a function from yellow to red. The point values contain the range of values, and the HSL Hue.
var yellowToRed = new L.HSLHueFunction(new L.Point(50, 60), new L.Point(100, 0));

DVF contains a L.ChoroplethDataLayer layer that will accept your GeoJSON, and your color function, and will generate the layer for you.
var layer = new L.ChoroplethDataLayer(geoJSON, {
    // For the full options, see the documentation
    displayOptions: {
        // The display will be colored by your 'density' property in your GeoJSON. This accesses the feature object directory, so the 'properties' prefix is required if you're going to access a GeoJSON property on your data.
        'properties.density': {
            // A legend will automatically be generated for you. You can add this as a control. This displayName property will be the title for this layer's legend.
            displayName: 'Density',
            color: yellowToRed
        }
    };
});

This is just a simple example. For your data, it might look slightly different. Go through the DVF documentation and samples and you'll find what's right for you.
Comment: Thak You very much for the detailed help


Can a node belong to multiple menus?

Question: I have a few pages such as a general "contact us" page. I'd like this page to exist inside of the Main Menu but be able to be linked from other menus (Theatre menu, for example). I create the contact us page and assign it to the Main menu on the node's form. Then, I add the link from the Theatre menu.
However, the contact us page now shows the Theatre menu.
How do I accomplish linking a page from multiple menus but keeping it inside of it's own menu?
I thought the old convention was to add existing links such as http:/learn/contact_us. If I add the link learn/contact_us to Theatre's menu, the Contact us page now shows the Theatre menu (instead of the Main menu).
Additional folks running across this problem:
https://drupal.org/node/1314742
Comment: Can you not add the menu items manually and just point both at "contact us" page???
Comment: It seems that if I add this page to the Theatre menu for example. Upon viewing the page, the Theatre menu is now rendered on the page instead of the Main menu.
Comment: Perhaps the menu is not being removed in the block management settings??? Sorry I am having a hard time comprehending what the exact issue is without seeing what your doing
Comment: If you want to create 2 menu items linked to the same node at different levels of a menu. When you'll try to view the node only one menu trail will be active. So the breadcrumb for example will always be the same. You may take a look at [NodeSymlinks](https://drupal.org/project/nodesymlinks)
Comment: Alex, no worries. I appreciate the questions. DnBase, thanks. I just came across multiple_node_menu that looks similar and giving it a try.
Answer: Actually, the project menu token allowed me to find a good work around. I set it up as pictured below. By using the token [site:url] followed by an existing path, a effectively have a link to an existing node without changing the existing nodes current parent menu.

Can a node belong to multiple menus?


What does the null hypothesis $H_0:\beta_2=0$ mean?

Question: For the model $$Y=\beta_1+\beta_2X_2+\beta_3X_3+\epsilon$$ what does the null hypothesis $H_0:\beta_2=0$ mean?
I think that then $X_2$ would not affect the expected value of $Y$ since the coefficient os then $0$.
But is that correct?
Comment: Even more, in this case, $Y$ is independent of $X_2$ , so the value of $X_2$ does not matter at all.
Comment: Correct, this will be a test of whether $X_2$ affects the value $Y$.  If you do not get a good answer here, you could try https://stats.stackexchange.com
Comment: Thank you!! :-)
Answer: Yes that is correct. If $\beta_3$ is 0, the variable has no predictive value for the response. No matter what value $X_2$ has, it does not alter the predicted value of the response.
Comment: Thank you!! :-)


Orthonormality proof on outer product of SVD unitary matrices columns

Question: If I have the two unitary matrices from the SVD of an m x n matrix (U, V*) and I form a set of new matrices by doing $u_iv_i^H$ (forms an m x n matrix).  Assuming $r = min(m, n)$ and my set is $X_1, X_2, ..., X_r$, how can I show that this is an orthonormal set?  Is there some property of unitary matrices that I've forgotten?  Their rows and columns form an orthonormal basis in $C^n$ but what of the product of two orthonormal vectors?
Furthermore, how do I generalize the coordinates of the original matrix using this orthonormal basis of the vector space?
Comment: I understand the definition of orthonormal. I was asking what inner product you are using for two matrices? One definition is $\langle A, B \rangle = \mathbb{tr} A^*B$, and with this inner product the $X_k$ are orthonormal.
Comment: What are $X_k$, the dyads $u_kv_k^*$? If so, what do you mean by orthonormal (for matrices)?
Comment: By orthonormal matrices, I mean the set is orthogonal and the matrix norm (generalization of the vector norm) is 1.
Comment: Sorry - yes, the inner product would be as you have specified above.
Answer: If you let $X_{ij} = u_i v_j^*$, and define the inner product $\langle A, B \rangle = \mathbb{tr} A^*B$, then you have $\langle X_{ij}, X_{ab} \rangle = \delta_{ia} \delta_{jb}$, from which it follows that the $X_{ij}$ form an orthonormal basis (there are $mn$ of them).
The collection of matrices you have above is a subset of this collection, so they are orthonormal (but not a basis).


Why is homomorphism defined as such?

Question: I am studying ring homomorphism and was curious why it is defined as such.The definition I have is

Let $(R,+,*)$ and $(S,\oplus,\cdot)$ be two rings. A map $\varphi : R \to S$ is called a homomorphism if for every $a,b \in R, \varphi(a+b)= \varphi(a) \oplus \varphi(b)$ and $\varphi(a*b)=\varphi(a)\cdot\varphi(β)$

I get that since $a,b\in R$, then $a * b\in R$ as well, and that $\varphi(a),\varphi(b),\varphi(a*b)\in S$, as well as that $\varphi(a)\cdot\varphi(b)\in R$. But why does $\varphi(a*b)=\varphi(a)\cdot\varphi(b)$ though?
Thanks in advance :)
Comment: The map preserves the structure of the ring.  Isomorphic rings are really the same; the elements just have different names.
Comment: Did you mean to say "*homomorphism*" in your question instead of "*isomorphism*"?
Comment: As an aside, some people consider zero and the additive inverse to be part of the structure of a ring, and thus $\varphi(-a) = \ominus a$ and $\varphi(0_R) = 0_S$ should be added to the definition; it is an odd feature of groups that these are automatically implied by $\varphi(a+b) = \varphi(a) \oplus \varphi(b)$. Some people also consider a multiplicative unit to be part of the structure of a ring, in which case you should have $\varphi(1_R) = 1_S$. This identity is not redundant and needs to be explicitly added to the definition of ring homomorphism if you consider 1 part of the structure.
Answer: A ring is a set with some extra structure. It is a general theme in mathematics: whenever we have sets with some extra structure we want to define maps between them so that they preserve that structure.
If we try to define what it means "to preserve structure" in the case of rings, then the only natural way to do so is as follows.
Given rings $A$ and $B$, and a map $\varphi\colon A\to B$ we want the following two procedures to yield the same result:

Take two elements in $A$, add (or multiply) them and apply $\varphi$ to the result.
Take two elements in $A$, apply $\varphi$ to both of them and THEN add (or multiply) them in $B$.

This is essentially the definition of a homomorphism of rings.
Answer: Here's a slightly different way of getting an intuition about this. Let's say we did have a bijection $\varphi:R\to S$. Then the most natural way of "mapping" the operations would be to say $s\oplus s' = \varphi(\varphi^{-1}(s)+\varphi^{-1}(s'))$ and similarly for the multiplicative structure. This can be equivalently written $r+r'=\varphi^{-1}(\varphi(r)\oplus\varphi(r'))$. Finally, this can also equivalently be written $\varphi(r+r')=\varphi(r)\oplus\varphi(r')$. This last form no longer requires assuming that $\varphi$ is a bijection.
As a historical note, quoting from the second footnote of Colin McLarty's The Uses and Abuses of the History of Topos Theory (PDF):

Group theorists into the 1950s generally counted as homomorphisms only
  isomorphisms and projections onto quotient groups. In hindsight they
  lacked the idea of a codomain as opposed to an image so they
  recognized only surjective homomorphisms, where the image coincides
  with the codomain.

I suspect that the way this manifested is they wouldn't talk about a homomorphism between groups, but rather the group structure induced by a bijection via my first two equations in the case of isomorphism. For projections onto quotient groups, this just looks like considering the "same" operation only "mod $N$" (for $N$ a normal subgroup).

Why is homomorphism defined as such?


Write an expression in powers of $(x+1)$ and $(y-1)$ for $x^2+xy+y^2$

Question: Write an expression in powers of $(x+1)$ and $(y-1)$ for $x^2+xy+y^2$

I calculated
$f_x=2x+y $
$f_{xx}=2 $
$f_y=x+2y$
$f_{yy}=2$
And then what I need to do?
What is the formula to solve the question ?
Comment: Now use Taylor's formula for a function of two variables; see http://www.math.colostate.edu/~newton/notes10-7.pdf
Answer: Let $u=x+1$, $v=y-1$, then
$$
x^2+xy+y^2=(u-1)^2+(u-1)(v+1)+(v+1)^2=u^2+v^2+uv-u+v+1=\;\cdots
$$
Comment: This is simpler than my suggestion!
Comment: So easy? Thank you :)
Answer: Since $x^2+xy+y^2$ is a polynomial of degree $2$, the answer is the Taylor expansion of $x^2+xy+y^2$ about the point $(-1,1)$. Let $f(x,y)=x^2+xy+y^2$.
Note that $f_x(x,y)=2x+y$, $f_y(x,y)=2y+x$, $f_{xx}(x,y)=f_{yy}(x,y)=2$ and $f_{xy}(x,y)=1$.  All higher order partial derivatives are identically $0$.
So the Taylor expansion is
$$f(-1,1)+f_x(-1,1)(x+1)+f_y(-1,1)(y-1)+\frac{1}{2!}\left(f_{xx}(-1,1)(x+1)^2 +2f_{xy}(-1,1)(x+1)(y-1)+f_{yy}(-1,1)(y-1)^2\right).$$
It looks messy, isn't too bad. We have $f(-1,1)=1$, $f_x(-1,1)=-1$, and $f_y(-1,1)=1$. The second-order partial derivatives are constant so are already evaluated at $(-1,1)$.
Remark: Note that the approach by Norbert is quite a bit quicker. It has the further great advantage of being less likely to produce an error.
The only advantage of the procedure above is that it lets you practice a bit with the second-order Taylor polynomial.
Comment: You explained in detail. So good:)


In the given figure, $X$ and $Y$ are two centres

Question: In the given figure, $X$ and $Y$ are two centres of two circles. They touch each other externally at a point $S$. $AB$ be the common tangent of both circles. $O$ be the centre of the third circle which touches the two circles at points $Q$ and $R$. If $AX=h$, $OM=f$ and $BY=g$, then prove that $$\frac {1}{\sqrt { f }}=\frac {1}{\sqrt { h }} +\frac {1}{\sqrt { g }}$$

My attempt
If we join $OA$ we have,
$$f^2={OA}^2-{AM}^2=$$; using pythagoras theorem
Again if we join $OB$ then
$$f^2={OB}^2-{MB}^2$$
Now how should I move further?
Comment: Possible duplicate of [Finding the radius of a third tangent circle](http://math.stackexchange.com/questions/1071577/finding-the-radius-of-a-third-tangent-circle)
Comment: Maybe [Decartes' Theorem](https://en.wikipedia.org/wiki/Descartes%27_theorem) applies?
Answer: Hint:
$BM^2=(g+f)^2-(g-f)^2=4gf$
$AM^2=(h+f)^2-(h-f)^2=4hf$
$(AM+BM)^2=(g+h)^2-(g-h)^2=4gh$
Square root both sides of all three expressions, then plug the first two expressions into the third one,  and you get the final equality you need to prove.
Comment: How do you get the first step?
Answer: How long is AB?
$XY = g + h$
you have a already constructed parallel to $AB$ from $Y$ to an unidentified point that I will call $Y'$
$YY' = h-g\\
(h-g)^2 + AB^2 = (h+g)^2\\
AB^2 = 4gh$
We can do a similar construction to get $BM$ and $AM$
$BM^2 = 4fg\\
AM^2 = 4fh\\
\sqrt {4fg} + \sqrt{4fh} = \sqrt{4gh}$
divide trough by $2\sqrt{fgh}$ and we get our desired result.
Comment: I couldn't understand your parallel concept, please clarify.
Comment: You have constructed a line in your diagram that is parallel to AB and intersects Y, forming a narrow little right triangle.  One leg is has the same length as AB, one leg has a length equal to h-g, and the hypotenuse = XY has a length equal to g+h


Angular 1.6: Abrir um uibmodal dentro de outro uibmodal usando "resolve"?

Question: Estou com um problema para abrir um uibmodal dentro de outro uibmodal passando o mesmo através do resolve.
Tenho dois modals declarados dentro de um mesmo controller, Modal1 e Modal2.
Modal 1 passa o modal2 no resolve, tudo funciona bacana, menos a questão do "result.then", o modal 2 retorna um valor x para um $scopo, porém o mesmo retorna o valor para o controller principal e eu gostaria que fosse retornado para o Modal1
Veja o exemplo: http://plnkr.co/edit/ltzJzn27413sQ17YThoX?p=preview
Alguém sabe como resolver esta questão? Já tentei usar angular.copy mas não funciona :(
Muito Obrigado
Comment: Mostre o que você tentou ate agora.
Comment: Olá Lucas, eu coloquei o exemplo do código no plnkr: http://plnkr.co/edit/ltzJzn27413sQ17YThoX?p=preview
Answer: Uma opção é fazer com que a função de abrir modals receba um callback:
<code>angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $uibModal) {

  //abre um Modal
  function openModal( templateUrl, controller, resolve, callback ){
    return $uibModal.open({
      templateUrl,
      controller,
      resolve
    }).result.then( callback || angular.noop );
  }

  //abre modal 1
  const openModal1 = (resolve, callback) =>
    openModal( 'modaltemplate1.html', 'ModalController1', resolve, callback);

  //abre modal 2
  const openModal2 = (resolve, callback) =>
    openModal( 'modaltemplate2.html', 'ModalController2', resolve, callback);

  $scope.produtos = 0;

  $scope.openModal1 = function () {
    openModal1({
      openModal2: function() {
        //envia a função de abrir o modal 2
        return openModal2;
      }
    });
  };

  $scope.openModal2 = () => openModal2({},  result => $scope.produtos = result);

});

angular.module('ui.bootstrap.demo').controller('ModalController1', function ($scope, $uibModalInstance, $uibModal, openModal2) {

  $scope.produtos = 1;

  $scope.ok = () => $uibModalInstance.close($scope.produtos);

  $scope.openModal2 = () => openModal2({}, result => $scope.produtos = result );

});

angular.module('ui.bootstrap.demo').controller('ModalController2', function ($scope, $uibModalInstance, $uibModal) {

  $scope.produtos = 2;

  $scope.ok = function () {
    $uibModalInstance.close($scope.produtos);
  };

});
</code>
Comment: Agora como eu faço para chamar o modal2 dentro do meu controller principal?
http://plnkr.co/edit/ltzJzn27413sQ17YThoX?p=preview
Comment: Atualizei para ficar mais fácil.
Comment: Muito obrigado! ;)


Testing the validation of uniqueness of the field in Rails's model using rspec without helper gems

Question: I'm trying to write test to validate the uniqueness of the field in RoR's model.
I am working on Ruby on Rails apps which I use to practice my skills in TDD. I have used Internet as my resource so far. I'm writing testing on validation for model.I will not be using 'shoulda', 'FactoryGirl' (and etc) gems.
I know using those gems will save me lots of coding but I will use those gems eventually. I want to learn how to write rspec test on it own without gems to help me understand how to write testing. I am doing good so far until 'uniqueness' testing.
How do I create test to validate the uniquenss of the 'email' field in 'User' model without using 'shoulda', 'FactoryGirl' (and etc) gems.
I know using those gems will save lots of coding but I will use those gems eventually. I want to learn how to write rspec test on it own without gems to help me understand how to write testing.
Most 'answer' to this questions on Stackoverflow (and elsewhere on the Net) includes the use of those helper gems. But find no answer to this without gems.
Here is model, User.rb
```
<code>class User < ApplicationRecord
  validate: :name, :email, presence: true
  validates :name, length: { minimum: 2 }
  validates :name, length: { maximum: 50 }
  # validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
  validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
  validates :email, uniqueness: true
end
</code>
<code>
And here is `user_spec.rb`.
</code>
<code>require 'rails_helper'

RSpec.describe User, type: :model do
  subject {
    described_class.new(name: 'John', email: 'email@example.com')
  }

  describe 'Validation' do
    it 'is valid with valid attributes' do
      expect(subject).to be_valid
    end

    it 'is not valid without name' do
      subject.name = nil
      expect(subject).to_not be_valid
    end

    it 'is not valid without email' do
      subject.email = nil
      expect(subject).to_not be_valid
    end

    (...)

    it 'is invalid if the email is not unique' do
      expect(????????).to_not be_valid
    end

  end
end
</code>
```
how do I write to test for uniqueness. Should I use something else other than 'subject' to test against? Remember, I don't want a solution that use gems (Shoulda/FactoryGirl/etc) this time.
I've been at it for the last few days and no luck. Any solution?  And where is the best tutorial on rspec on Ruby on Rails?
Answer: To test for uniqueness, first you have to create a user with same email as used in subject. Then, your subject would be invalid because of uniqueness validation on email.
Something like:
before { described_class.create!(name: 'foo', email: 'email@example.com') }
it 'is invalid if the email is not unique' do
  expect(subject).to be_invalid
end

Comment: If it's that simple, then what is the point of
`subject { described_class.new(name: 'John', email: 'firstname.lastname@example.com') }`?
Comment: @JohnTowery check now
Comment: Note: Do not run this `before` block for other tests. Wrap this in a `context`.
Answer: Ok I got it working.
Ok, at the suggestion of @Jagdeep Singh, I wrote this test:
```
<code>context 'when email is not unique' do
  before { described_class.create!(name: 'foo', email: 'firstname.lastname@example.com') }
  it {expect(subject).to be_invalid}
end
</code>
<code>
</code>
<code>context 'when email is unique' do
  before { described_class.create!(name: 'foo', email: 'firstname.lastname@example.com') }
  it {expect(subject).to be_valid}
end
</code>
```
and it seems to pass the test. I added other test to test valid uniqueness.
Thanks for the help.
I decided to rewrite whole test to make use of context to make it more clear and readable.
Here is my rewrite:
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe User, type: :model do
  subject {
    described_class.new(name: 'John', email: 'email@example.com')
  }

  describe '.validation' do

    context 'when email is not unique' do
      before { described_class.create!(name: 'foo', email: 'email@example.com') }
      it {expect(subject).to be_invalid}
    end

    context 'when email is  unique' do
      before { described_class.create!(name: 'foo', email: 'firstname.lastname@example.com') }
      it {expect(subject).to be_valid}
    end

  end
end


Monitoring "external" worm activity remotely

Question: Some of our computers in our company has been infected with the worm Conficker. We don't know the source of the infection, but I want to monitoring the outside activity to see if we are still infected (we have already "protect" some computers). That's important to ensure that I can ask for being unlisted.
My question is: which means does I have to monitor the whole outbound traffic from my source IP, and/or the specific trafic to a concrete IP, and/or the outbound traffic in a port-based manner (the traffic from each port together with its destination port/IP), everything remotely (outside the infected network)?
I don't ask here for ways to detect infected PCs, but to see the outside activity as an indirect proof of "cleanliness".
You can see our IP and the description of our infection from the following link:
http://cbl.abuseat.org/lookup.cgi?ip=188.8.131.52&.pubmit=Lookup
The destination IP is 184.108.40.206. If I dig in it:
 $ dig -x 188.8.131.52
 109.64-18.104.22.168.in-addr.arpa. 3600 IN PTR  sinkhole-iad1-1.cwg.fsi.io.

No surprises here (clearly stated as a sinkhole).
I can explore from home (Ubuntu 14.04), but, if my ISP or router blocks me in some way, I can ssh-connect to a public server of our company (Ubuntu Server 14.04) to scan from there. So, let's assume I've no restrictions to make that sort of scanning.
Answer: If your router is rflow enabled, you can have it report in to an external computer running a rflow collector.
Example for a ddwrt router:
http://www.dd-wrt.com/wiki/index.php/Using_RFlow_Collector_and_MySQL_To_Gather_Traffic_Information


Compute adjusted McFadden's pseudo-R2 from deviances

Question: I know, that the "ordinary" McFadden's pseudo-R2 can be computed like this:
$$
R^2 = 1 - \frac{\text{Residual deviance}}{\text{Null deviance}},
$$
but today I've read about adjusted McFadden's pseudo-R2 here and I thought if it's possible to compute it like this?
$$
R^2_{\text{adj}} = 1 - \frac{\text{Residual deviance}-K}{\text{Null deviance}}
$$
$K$ is the number of predictors.
Comment: It looks like your equation is correct but the paper said that $k$ was the number of predictors (to avoid over-fitting), not the number of observations.
Comment: Yes, blokeman' Answer is essential. deviance = -2*LogL, so the numerator above should be Residual deviance + 2*K.
Comment: @Tavrock Thank you, I meant predictors - it's corrected now. And could you, please, expand your comment to an answer, so I could accept it?
Comment: @Tavrock And I notices, that with increasing $K$ the $R^2$ will increase to... Shouldn't I add $K$ to Residual deviance instead of substracting it?
Comment: This will be clear to anyone who carefully reads the accepted answer, but just to make it more obvious to casual readers: the equations in the question are not correct.
Answer: I too have only just now run into this adjusted R-squared. It seems a handy and useful diagnostic. I don't quite agree with your definition though. Rather than the number of predictors, K is the number of additional parameters relative to the null model. Unlike the number of predictors, the number of parameters includes interaction terms, random effects, dummy variables standing for non-reference categories of a nominal predictor, polynomials, etc.
Long (1997: 104) defines the statistic thus:
$$\begin{equation}
R^2_{adj} = 1 - \frac{logL(M) - K}{logL(M_{null})}
\end{equation}$$
where K, unless I'm mistaken, turns out to be the familiar Akaike penalty when converted to the Deviance scale.

Long, J. S. (1997). Regression models for categorical and limited dependent variables. Thousands Oaks: Sage.
Comment: Thanks. That should be fixed now.
Comment: If $K$ includes the intercept term, then why isn't the denominator $\ln L(M_{0})-1$ since the null model also includes an intercept?


url rewriting with .htaccess

Question: I'm trying to rewrite the url  on a site I have on localhost (port 8000), I have already set this up for certain other directorys but I can't manage to do it for this one. I compared it to several other working .htaccess files but there wasn't any difference. (The module is activated.) The site is in a subdirectory called HTF and the file single.php works just fine. The htaccess file is placed in the same directory.
Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteRule videos/([0-9]+)/$ /HTF/single.php?id=$1 [L]

I would like to get an url like  localhost:8000/HTF/video/1232434 for exemple.
Any help appreciated, tested several types of htacces files, here a working exemple for a other subdirectory called sorted:
Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteRule ^image-post/([0-9]+)/(.+)\.php$ /sorted/image-post.php?   id=$1&title=$2 [L]
RewriteRule ^pages/([0-9]+)/(.+)\.php$ /sorted/page.php?page_number=$1&cat=$2 [L]

Answer:  localhost:8000/HTF/video/1232434

will not match
 videos/([0-9]+)/$

because of the trailing slash /. Try /? to make the slash optional or leave away. And videos.
^/HTF/video/([0-9]+)/?$ /HTF/single.php?id=$1 [L]

or
^/HTF/video/([0-9]+)$ /HTF/single.php?id=$1 [L]

This shall do the job. Sorry can not try here.
Comment: sadly not working, the page displays as wanted but the url is not changing.   I would also be happy with /HTF/2343545 as rewritten url for exemple..
Comment: If such a rule is not working the way you expect if may collide with an `Alias` in `httpd.conf` or others. Have you checked? Set `RewriteLog "/var/www/mod_rewrite.log"` and `RewriteLogLevel 2` (or higher) and read logs.
Answer: Your rule will match videos, not video as you were wanting. Also it will only match with a trailing slash.
This will work
RewriteEngine on
RewriteRule ^video/([0-9]+)/?$ single.php?id=$1

Comment: sadly not working, the page displays as wanted but the url is not changing.   I would also be happy with /HTF/2343545 as rewritten url for exemple..
Comment: Could you clarify what you mean by the URL not changing? That rewrite rule will show the contents of /HTF/single.php?id=123 when you visit /HTF/video/123

url rewriting with .htaccess


Text position is under Picture

Question: I have a css styling problem:
I created a header with text inside. The header has two pseudo elements: ::before and ::after.
Both elements lay on top of the header element. How do I get the h1 to stay in front of everything??
Here is my code example: (got code snippets removed?? i didnt found the button where to add)

header {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: 99;
  background-image: url("Bild1.svg");
  background-size: 100% 100%;
  text-align: center;
  padding: 1px 20px;
}

header::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url("Bild2.svg");
  background-size: 100% 100%;
  opacity: .5;
}

header::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: -10px;
  background-image: url("Bild3.svg");
  background-size: 100% 100%;
  opacity: .5;
}

Title Text

Here is a image how it looks:

As you can see the Text is behind both elements.
I tried to fix it using z-index but nothing worked for me. U have and ideas?
Comment: make your h1 position relative and give it a higher z-index that your pseudo elements (1 will do it as your pseudo elements don't have their z-index set - not sure why everyone is saying use 100)
Comment: Yes thank you! i forgot to set position relative...
Answer: apply z-index 99 on background
and apply z-index 999 on the text I hope it will work
Comment: z-index doesn't work on non positioned elements
Answer: I would suggest making the z-index of the h1 tag
h1{
            z-index: 999;
            color: white;
        }

and making the background z-index to 99 or something below that.
Comment: z-index doesn't work on non positioned elements

Text position is under Picture


Handle exceptions in concurrent-ruby thread pool

Question: How to handle exceptions in concurrent-ruby thread pools (http://ruby-concurrency.github.io/concurrent-ruby/file.thread_pools.html)?
Example:
pool = Concurrent::FixedThreadPool.new(5)
pool.post do
  raise 'something goes wrong'
end

# how to rescue this exception here

Update:
Here is simplified version of my code:
def process
  pool = Concurrent::FixedThreadPool.new(5)

  products.each do |product|
    new_product = generate_new_product

    pool.post do
      store_in_db(new_product) # here exception is raised, e.g. connection to db failed
    end
  end

  pool.shutdown
  pool.wait_for_terminaton
end

So what I want to achive, is to stop processing (break loop) in case of any exception.
This exception is also rescued at higher level of application and there are executed some cleaning jobs (like setting state of model to failure and sending some notifications).
Comment: Fallback policy tells only how to handle tasks that are rejected when maximum queue size is exceeded or when pool is shut down.
Comment: That depends on what kind of exception happens and how do you want to respond. Please extend your example.
Comment: I've updated original post with more explanations.
Comment: Have you looked for a approriate `:fallback_policy`?
Comment: We've been struggling with this for months now, too. Since there really doesn't seem to be any sensible literature around, I asked the developers: https://github.com/ruby-concurrency/concurrent-ruby/issues/616 Hopefully, they will reply.
Answer: The following answer is from jdantonio from here https://github.com/ruby-concurrency/concurrent-ruby/issues/616
"
Most applications should not use thread pools directly. Thread pools are a low-level abstraction meant for internal use. All of the high-level abstractions in this library (Promise, Actor, etc.) all post jobs to the global thread pool and all provide exception handling. Simply pick the abstraction that best fits your use case and use it.
If you feel the need to configure your own thread pool rather than use the global thread pool, you can still use the high-level abstractions. They all support an :executor option which allows you to inject your custom thread pool. You can then use the exception handling provided by the high-level abstraction.
If you absolutely insist on posting jobs directly to a thread pool rather than using our high-level abstractions (which I strongly discourage) then just create a job wrapper. You can find examples of job wrappers in all our high-level abstractions, Rails ActiveJob, Sucker Punch, and other libraries which use our thread pools."
So how about an implementation with Promises ?
http://ruby-concurrency.github.io/concurrent-ruby/Concurrent/Promise.html
In your case it would look something like this:
promises = []
products.each do |product|
  new_product = generate_new_prodcut

  promises << Concurrent::Promise.execute do
    store_in_db(new_product)
  end
end

# .value will wait for the Thread to finish.
# The ! means, that all exceptions will be propagated to the main thread
# .zip will make one Promise which contains all other promises.
Concurrent::Promise.zip(*promises).value!

Comment: This is not a reasonable answer. Any application should be able to use public api directly, because it is public. This api should be transparent for user. It shouldn't just ignore exceptions.
Comment: You've offered people to change *thread pool* into *promises* just because ... thread pool don't want to support abortable workers. xDD Yea I think it is enough to click -1 button.
Comment: that has actually nothing to do with my answer. It is your opinion as we can see here https://github.com/ruby-concurrency/concurrent-ruby/issues/634 and apperently not the opinion of everbody. I don't say you are wrong, maybe your way is better. but I provided a way to handle his problem, and even if it isn't the best answer it is a perfectly valid answer, that solved the problem for us. And I see the advantages of your method, but the downvote is completly based on your opinion!
Comment: No I offered the people nothing, I let them knew what answer there is in the official github repo. Which is a valid contribution to SO.
Comment: How does one control concurrency with high-level abstractions such as promises? That has been the main concern for me, and I couldn't fine any answers in the documentation.
Answer: There may be a better way, but this does work. You will want to change the error handling within wait_for_pool_to_finish.
def process
  pool = Concurrent::FixedThreadPool.new(10)
  errors = Concurrent::Array.new

  10_000.times do
    pool.post do
      begin
        # do the work
      rescue StandardError => e
        errors << e
      end
    end
  end
  wait_for_pool_to_finish(pool, errors)
end

private

def wait_for_pool_to_finish(pool, errors)
  pool.shutdown

  until pool.shutdown?
    if errors.any?
      pool.kill
      fail errors.first
    end
    sleep 1
  end

  pool.wait_for_termination
end

Answer: I've created an issue #634. Concurrent thread pool can support abortable worker without any problems.
require "concurrent"

Concurrent::RubyThreadPoolExecutor.class_eval do
  # Inspired by "ns_kill_execution".
  def ns_abort_execution aborted_worker
    @pool.each do |worker|
      next if worker == aborted_worker
      worker.kill
    end

    @pool = [aborted_worker]
    @ready.clear

    stopped_event.set
    nil
  end

  def abort_worker worker
    synchronize do
      ns_abort_execution worker
    end
    nil
  end

  def join
    shutdown

    # We should wait for stopped event.
    # We couldn't use timeout.
    stopped_event.wait nil

    @pool.each do |aborted_worker|
      # Rubinius could receive an error from aborted thread's "join" only.
      # MRI Ruby doesn't care about "join".
      # It will receive error anyway.

      # We can "raise" error in aborted thread and than "join" it from this thread.
      # We can "join" aborted thread from this thread and than "raise" error in aborted thread.
      # The order of "raise" and "join" is not important. We will receive target error anyway.

      aborted_worker.join
    end

    @pool.clear
    nil
  end

  class AbortableWorker < self.const_get :Worker
    def initialize pool
      super
      @thread.abort_on_exception = true
    end

    def run_task pool, task, args
      begin
        task.call *args
      rescue StandardError => error
        pool.abort_worker self
        raise error
      end

      pool.worker_task_completed
      nil
    end

    def join
      @thread.join
      nil
    end
  end

  self.send :remove_const, :Worker
  self.const_set :Worker, AbortableWorker
end

class MyError < StandardError; end

pool = Concurrent::FixedThreadPool.new 5

begin
  pool.post do
    sleep 1
    puts "we shouldn't receive this message"
  end

  pool.post do
    puts "raising my error"
    raise MyError
  end

  pool.join

rescue MyError => error
  puts "received my error, trace: \n#{error.backtrace.join("\n")}"
end

sleep 2

Output:
raising my error
received my error, trace:
...

This patch works fine for any version of MRI Ruby and Rubinius. JRuby is not working and I don't care. Please patch JRuby executor if you want to support it. It should be easy.


publish-subscribe mechanism and read-side critical section in RCU lock

Question: Question 1:
In the article to introduce RCU lock, he writes a publish-subscribe mechanism. But I have a question about rcu_assign_pointer(), in this article, he said:
1 p->a = 1;
2 p->b = 2;
3 p->c = 3;
4 rcu_assign_pointer(gp, p);

The rcu_assign_pointer() would publish the new structure, forcing both
  the compiler and the CPU to execute the assignment to gp after the
  assignments to the fields referenced by p.

But how could compiler and CPU know p has been assigned?For example, If I just initialise the p->a and p->b, then how compiler and CPU distinguish the two situation?
situation 1:
1 p->a = 1;
2 p->b = 2;
3 p->c = 3;
4 rcu_assign_pointer(gp, p);

situation 2:
1 p->a = 1;
2 p->b = 2;
3 rcu_assign_pointer(gp, p);

Question 2:
As for the read-side critical section, If there are continuous readers to read the data, should writer must wait for them or writer couldn't do the synchronise operation? If yes, reader will always read the older version?
Answer: Answer to Question1:
rcu_assign_pointer() instructs the compiler not to optimize the machine-instructions, such that any modifications to fields of 'p' done before the rcu_assign_pointer() statement, in the implementation/code, are executed in the CPU-pipeline before the assignment of 'p' to 'gp'. This makes sure that when 'gp' gets assigned, all the fields of 'p', and hence now 'gp', that the developer chose to assign are indeed assigned.
To illustrate further, take the following code, whose intent is to return 'y' back to the caller:

     void
     my_func(struct foo **y)
     {
         struct foo *x = malloc(sizeof (struct foo));
         x->val1 = 1;
         *y = x;
         x->val2 = 2;
         return;
     }
The developer does not really care about the order of the assignment statements above because his/her intent is to simply return *y filled with 2 values. Hence, given code like the above, the compiler can choose to execute the 3 assignment statements in parallel in the CPU-pipelines and it does not break correctness.
Now, if you use a similar assignment statement when doing rcu type of work, the compiler might choose to do the same kind of optimization and hence readers might end up with a "partially-initialized" 'gp'. rcu_assign_pointer() makes sure the ordering of assignment is maintained so that the developer's intent, to assign 'p' to 'gp' AFTER all of p's fields have been initialized, is preserved.
This hopefully should illustrate that if you, the developer, chose to assign only p->a and p->b, without assigning p->c, before assigning 'p' to 'gp', then that's what gp will get - a partially-initialized structure.
Answer to Question2:


Tooltip Bootstrap 3 sumir quando eu clicar em outro

Question: Eu tenho 3 tooltips. Quero que eles apareçam no click, então usei o seguinte:
$('[data-toggle="tooltip"]').tooltip({
        trigger : 'click'
    });

Assim, quando eu clico no primeiro, por exemplo, ele exibe o tooltip.
Porém, quero que quando eu clique em um tooltip ele ative o mesmo e desative os outros que estiverem ativos.
Alguém sabe como me ajudar?
Comment: Separe a sua chamada do Tooltip por id do botão. Assim você garante que apenas um seja chamado.
Comment: Pode mostrar um exemplo seguindo o caso de eu ter 3 tooltips?
Answer: Você deve fechar todos os outros tooltips e abrir apenas o que clicou.
Com este html:
Um
Dois

Bastaria apenas essa chamada para se comportar como citou:
$('[data-toggle="tooltip"]').tooltip({trigger: 'click'});

$('[data-toggle="tooltip"]').on('click', function (e) {
    $('[data-toggle="tooltip"]').not(this).tooltip('hide');
});

Segue link de exemplo: http://jsfiddle.net/vFDSZ/526/
Comment: Muito obrigado, amigo!
Answer: Segue uma outra alternativa de solução, mostrando os tooltips manualmente
Sempre que o evento de click de um elemento que tem tooltip é acionado, esconde todos os tooltips visíveis e mostra somente o tooltip do elemento clicado.
Segue um fiddle com um exemplo funcional: https://jsfiddle.net/mathiasfcx/rha7ppu7/5/
Comment: Resolveu meu problema, funcionou perfeitamente ;) +100 Abraços


Is $\int\frac{\cos^5x\sin^3x}{1+\cos2x}dx = \frac{\sin^4x}{8}-\frac{\sin^6x}{12} +C$ or $\frac{\cos^6x}{12}-\frac{\cos^4x}{8} +C$?

Question: $\int\dfrac{\cos ^5x\sin ^3x}{1+\cos 2x}dx = \dfrac{\sin ^4x}{8}-\dfrac{\sin ^6x}{12} +C$ or $\dfrac{\cos ^6x}{12}-\dfrac{\sin ^4x}{8} +C$?
$\int\dfrac{\cos ^5x\sin ^3x}{1+\cos 2x}dx$ = $\dfrac{1}{2}\int{\cos ^3x\sin ^3x} dx$
1) $\dfrac{1}{2}\int{\cos ^3x\sin ^3x} dx$
= $\dfrac{1}{2}\int{\cos ^2x\sin ^3x\cos x} dx$
= $\dfrac{1}{2}\int{(1-\sin ^2x)\sin ^3x} d\sin x$
= $\dfrac{1}{2}\int{\sin ^3x-\sin ^5x} d\sin x$
= $\dfrac{\sin ^4x}{8}-\dfrac{\sin ^6x}{12} +C$
2) $\dfrac{1}{2}\int{\cos ^3x\sin ^3x} dx$
= $\dfrac{1}{2}\int{\cos ^3x\sin ^2x\sin x} dx$
= $-\dfrac{1}{2}\int{(1-\cos ^2x)\cos ^3x} d\cos x$
= $-\dfrac{1}{2}\int{\cos ^3x-\cos ^5x} d\cos x$
= $\dfrac{\cos ^6x}{12}-\dfrac{\cos ^4x}{8} +C$
Which one is correct? or both are correct?
Answer: You can differentiate and simplify your two answers to see that they are both correct. If you take the first answer, expand it using the identity $\sin^2 x = 1-\cos^2 x$, and simplify, you will get the second answer plus an additional constant. Thus the two expressions (ignoring the $C$'s) differ by a constant.


What's the difference of source complile or use apt?

Question: For example, I want to install glog, I could use
sudo apt-get install libgoogle-glog-dev
or
git clone https://github.com/google/glog

./autogen.sh && ./configure && make && make install

What's the difference?
I'll appreciate it if you help me.
Answer: In
sudo apt-get install libgoogle-glog-dev,
It installs and maintains programs and other collections of files (data, documentation, etc.) in the form of packages.
while in second one you first download the source from Github repository and then run various shell files which get it installed on your system.
I hope it helps you.


In terms of functions why am I allowed to separate $f$ and $g$ from $x$?

Question: While studying Linear Algebra I came across a function notation that looked like this: $(f + g)(x)$.
I also saw that this was the same thing as saying $f(x) + g(x)$.
I understand the function notation $f(x)$ and $g(x)$ (which are literally functions) but I do not understand the notation $(f + g)(x)$.
Could anyone please fill me in with some introductory info of what this notation means? My guess is that it is a composite function. However I saw that a composite function does not have a plus but a circle in it so I may be wrong. Also from an algebraic perspective, it sort of looks like you can apply the distributive law on $(f + g)(x)$ to make it into $f(x) + g(x)$. That sounds a bit strange to me because notation wise it doesn't make sense.
I have heard that this means $(f + g)$ "evaluated at $x$", which I don't understand.
I would greatly appreciate it if someone gave an overview of the $(f + g)(x)$ notation. Thank you in advance everyone.
Comment: Literally, $f(x)$ and $g(x)$ are numbers, not functions -- specifically the result of applying the functions $f$ and $g$ to the number $x$. More formally, $f(x)$ is an expression of type "number" with a free variables $f$ and $x$, where $f$ has type "function" and $x$ has type "number".
Comment: (of course, in more general contexts, "number" could be replaced with any other kind of type compatible with the function, and "function" should be annotated with its domain and codomain. Sometimes $x$ might refer to a specific constant, such as when working with polynomials. And sometimes $()$ might be used not something generalizing evaluation)
Comment: $f$ is a function, $f(x)$ is a number (specifically, the number $f$ gives you as output when you give $f$ the number $x$ as input).
Answer: This is just a definition.  We are defining a new function, which we might call $h(x)$, by the formula $h(x)=f(x)+g(x)$ for all $x$.  We are then choosing to also refer to this function as "$f+g$", so instead of writing $h(x)$ we can write $(f+g)(x)$.  There's no magic assertion about the distributive law being made here--we're just making up a meaning for the notation $(f+g)(x)$.
Comment: I received catty comments on my answer, so may I make a catty comment on this one. It is the operation that maps the pair of functions $(f, g)$ to the function $f + g$ that needs to be explained. Using this operation does not define anything new (such as your $h$). Talking about magic and making up meanings for notations seems to me to be wishy-washy and unhelpful.
Comment: @RobArthan Seems to me that this answer is exactly right. The point is that $f+g$ is a function, _defined_ by $(f+g)(x)=f(x)+g(x)$...
Comment: @DavidC.Ullrich: it's the pointwise addition operation on functions that is defined by $(f, g) \mapsto x \mapsto (f + g)(x)$. When I write $1 + 2$, I am not defining a new number and I am not defining a new name for an existing number. Likewise, when I write $f + g$, no new definition is implied.
Comment: @RobArthan " it's the pointwise addition operation on functions that is defined by (f,g)↦x↦(f+g)(x)"That's not a definition of anything _until_ we have a definition of $(f+g)(x)$. I didn't say that a "new definition" was "implied" when you write $f+g$, all that's been asserted here is that the definition of $f+g$ is $(f+g)(x)=f(x)+g(x)$. Or more completely, "Def: If $f,g:X\to\Bbb R$ then $f+g:X\to\Bbb R$ is defined by $(f+g)(x)=f(x)+g(x)$." I don't understand how you can object to this - if that's not it, what _is_ the definition of $f+g$?
Answer: The set of real valued functions $f$ and $g$ on a space is a vector space and even an 'algebra': You may naturally define their sum and product by declaring:
$$ (f+g)(x)=f(x)+g(x) \ \ \mbox{and} \ \ (f\cdot g)(x) = f(x) g(x) $$
Often you simply write $f+g$ and $fg$ for the sum and the product (without parantheses when you omit the argument). Then e.g. $f_1+\cdots + f_n$ denotes a sum of $n$ functions.
Comment: +1: "Vector space", "algebra": well done for escaping the criticism I got for mentioning (apparently) difficult technical terms like "group".
Answer: To expand on the explanation by Eric Wofsey:
Assume we have any two functions $f:X\to Y$ and $g:X\to Y$ (if you are not familiar with that notation, it just means in $f(x)$ resp. $g(x)$ we can use for $x$ any value from the set $X$, and the corresponding function value will always be found in the set $Y$). Further assume we can add those values found in $Y$ (for example, $Y$ contains real numbers). Then no matter what $f$ and $g$ are, we can define a function $h$ by $h(x) = f(x)+g(x)$.
So for example, take the function $\sin x$ and the function $\cos x$. Then we have a function $h(x) = \sin x + \cos x$.
Or take the functions $\ln x$ and $\tan x$. Then we have a function $h_2(x) = \ln x + \tan x$.
Observe that the resulting function depends only on the two functions which we started with. But for such a relation where you can put something in, and then get something else which only depends on what we have put in, we have a name: It's a function! So what we have defined here is, indeed a function, but one that doesn't operate on numbers or vectors, but on other functions.
Let's for the moment call that function $S$. So $S$ takes two functions, say $f$ and $g$, and gives another function, let's call it $h$, which for any given $x$ gives the sum of the values of $f(x)$ and $g(x)$. So we have
$$h = S(f,g)$$
OK, this is straightforward, isn't it? But wait, as $h$ is a function, we can apply it; such an application is written $h(x)$. Now insert the $h$ from above, and you get:
$$h(x) = S(f,g)(x).$$
Of course, the way we defined $S$, we just have $h(x) = f(x) + g(x)$. Therefore,
$$S(f,g)(x) = f(x) + g(x).$$
What is left is just a notational convenience: The fundamental operation $S$ is defined on is the operation of adding two values. Now remember that when we write $a+b$ for two numbers, all we do is to apply a two-argument function $s$ to $a$ and $b$. But instead of writing $s(a,b)$ and explaining in detail what $s$ is, we just introduce an operator notation and write $s(a,b) = a+b$.
Now our function $S$ essentially is nothing but an addition: We add two function values in order to obtain the result. Therefore just as with numbers, we define the operator notation
$$f + g := S(f,g).$$
And if we use this notation in the previous displayed equation, we get exactly
$$(f+g)(x) = f(x) + g(x).$$
However there's more to it, especially in linear algebra: As it turns out, if $f$ and $g$ are linear functions, then $f+g$, as defined above, is also a linear function. Moreover, with this definition (and a similar definition for scalar multiplication), the linear functions turn out to be a vector space in their own right, and in  this vector space, the operation $f+g$ acts exactly how the addition of vectors should act, therefore giving an additional justification of that notation.
Finally, if you look very closely, you'll find that the standard vector addition in $\mathbb R^n$ itself is nothing than such a function addition: When you write $a_k$ for the $k$-th component of the vector $a$, what you are really doing is to apply a function from a set $I$ of indices (usually $I=\{1,2,\ldots,n\}$) to the set of real numbers. That is, you can interpret your vector $a\in\mathbb R^n$ as a function that maps indices to real numbers. It's just that instead of writing the function application as $a(k)$, you write it as $a_k$. But there's really not the slightest difference apart from notation: You put an index in, you get a number out. And the vector describes which number you get for each index.
Now how do you add vectors in $\mathbb R^n$? Well,
$$(a+b)_i = a_i + b_i.$$
Now let's rewrite the index notation into standard function application notation:
$$(a+b)(i) = a(i) + b(i).$$
And voila, there's the function addition formula again.
Answer: If $f$ and $g$ are functions from a set $X$ to a group $G$, it is standard to write $f + g$ for the function from $X$ to $g$ that maps $x$ to $f(x) + g(x)$. This makes the set $X \to G$ of functions from $X$ to $G$ into a group.
In the context of linear algebra, if $f$ and $g$ are linear transformations from the set $X = \Bbb{R}^m$ of all vectors $(x_1, \ldots, x_m)$ of $m$ real numbers to the set $Y = \Bbb{R}^n$ of all vectors $(y_1, \ldots, y_n$) of $n$ real numbers, then we can represent $f$ and $g$ by $n\times m$ matrices of real numbers, $\mathbf{F}$ and $\mathbf{G}$ say. Then $f + g$ is the linear transformation represented by the matrix $\mathbf{F} + \mathbf{G}$ that you get by adding corresponding elements of $\mathbf{F}$ and $\mathbf{G}$. Your "distributivity" property corresponds to the following law in the world of matrix and vector algebra:
$$
(\mathbf{F} + \mathbf{G})\mathbf{x} = \mathbf{F}\mathbf{x} + \mathbf{G}\mathbf{x}
$$
Comment: Given the question, do you _really_ think the OP knows what a group is?
Comment: Inb4 someone writes an answer in terms of categories.
Comment: @DavidC.Ullrich: you don't need to know what a group is to get something out of my answer. The point is that $f + g$ is an object in its own right and not just something that only subsists in the rule that $(f+g)(x) = f(x) + g(x)$.
Comment: @DavidC.Ullrich: does my updated answer meet your standards for guessing what the OP knows?


Starred files in a spreadsheet

Question: My starring workflow needs some work. I thought about creating a script to run in drive that looks for starred files (docs, slides, sheets) and adds them to spreadsheet.
I'm a complete noob, so I've checked the script reference to try and find snippets that might work.
iterate through drive
if starred file found
  add to new row in spreadsheet

// Log the name of every starred file in the Designated Spreedsheet.
function addStarred() {
  var sheet = SpreadsheetApp.getActiveSheet(); //this will need to change to a designated sheet
  var files = DriveApp.getFiles();

  while (files.isStarred()) {
    var file = files.next();
    sheet.appendRow(file.getName());
  }
}

The ideal would be a list in my spreadsheet that can then be filtered to find the correct starred file.
The first error I see is:

"Cannot find function isStarred in object FileIterator. (line 6, file "Code")"

Appreciate any help.
Answer: isStarred() is a method of the Class File not of the Class Files. Change the while block to something like the following:
while (files.hasNext()) {
  var file = files.next();
  if (file.isStarred()) sheet.appendRow([file.getName()])
}

Comment: That did the trick. Thanks!! I also want to grab the URL, to save searching ,   if (file.isStarred()) sheet.appendRow([file.getName()],sheet.appendRow([file.getDownloadUrl()]))   It returned an error.
Comment: @PaulRayner: Try `if (file.isStarred()) sheet.appendRow([file.getName(),file.getDownloadUrl()]) `
Answer: This is a bit of a curve ball, but this might be a good use case for IFTTT. I looked and they support starred files as a trigger and adding a row to a spreadsheet as an output. You'll have to load the spreadsheet initially since the trigger only fires for new stars.
Comment: Pretty good curve ball. It only works on starred items after the app is turned on. So any existing files won't be added. A good backup, if I can't get this working. Thanks!!!!!!

Starred files in a spreadsheet


How to prove that two lines of a shape are parallel?

Question: ∠A=∠B, and P is a point on AB such that AD=PD. Prove that DP is parallel to CB. Please state how also ($SSS$, $ASA$, $SAS$, $CPCTC$, Isosceles Biconditional, interior angles, etc.)
Comment: Is it $AD=PB$ or $AD=PD$?
Comment: I don't think it's correct if $AD=PB$.
Answer: Using Isosceles Triangle Theorem $\overline{AD} \cong \overline{PD} \Rightarrow \angle A \cong \angle APD$. Consider $\overleftrightarrow{DP}$ and $\overleftrightarrow{CB}$. Consider the line $\overleftrightarrow{AB}$ which is a transversal to $\overleftrightarrow{DP}$ and $\overleftrightarrow{CB}$.
Using the converse of Alternate Interior Angle Theorem we see that $\angle APD \cong  \angle ABC \Rightarrow \overleftrightarrow{DP}\parallel \overleftrightarrow{CB}$.
Isosceles Triangle Theorem
Let $\triangle ABC$ be a triangle such that $\overline{AC} \cong \overline{BC}$. Then $\angle A \cong \angle B$.
Proof:
Consider the correspondence $A-B-C\leftrightarrow B-A-C$, from which we can deduce that $\overline{AC} \cong \overline{BC}$, $\angle C \cong \angle C$ and $\overline{BC} \cong \overline{AC}$. By SAS Theorem $\triangle ABC \cong \triangle BAC$, therefore, because of "parts of congruent triangles are congruent" $\angle A \cong \angle B$.
Converse of Alternate Interior Angle Theorem
Consider the figure shown in the problem as a general case. If $\angle APD \cong \angle ABC$, then $\overleftrightarrow{DP} \parallel\overleftrightarrow{CB}$.
Proof:
Suppose that $\overleftrightarrow{DP} \nparallel\overleftrightarrow{CB}$. Therefore they will intersect at a point $M$. Now consider the triangle $\triangle PMB$. By the external angle theorem $\angle APD >\angle ABC \rightarrow\leftarrow.$ Therefore  $\overleftrightarrow{DP} \parallel\overleftrightarrow{CB}$.
BTW, the question must be "...such that AD = PD..." Here is a graphical counterexample of the condition you posted.
Comment: The condition in OP is $AD=PB$
Answer: $AD=DP$ implies $\angle(DPA)=\angle(DAP)$. By assumption, the latter equals $\angle(ABC)$ so we have $\angle(DPA)=\angle(ABC)$.
Comment: The condition in OP is $AD=PB$


Identifying free variables in row-reduction

Question: For this matrix:
How do I know what the free variables are? Are they $x_4$ and $x_5$ ?
Comment: @Amzoti Hm? The lost column is what the systems of equations equal. Imagine a small line inbetween that column and the rest of the matrix
Comment: The first nonzero entry of each row flags the dependent variables. The rest will be the free variables.
Comment: @Maesumi So it would be $x_2$ and $x_4$
Answer: We have, from the bottom up:

$x_5 = 1$
$x_3 = 2 + x_4$
$x_1 = 8 + 3 x_4 + 4 x_2$

So, our free variables are $x_2$ and $x_4$.
You are 'free' to choose any values you want for those, with the observation that two of the solution are dependent on those values.
Try some examples to see what is going on.
Comment: Ah I understand! Thank you


Como passar um parametro pela URL usando HttpGet em ASP.NET CORE?

Question: tenho uma aplicação em ASP.NET CORE 2.0 onde eu fiz o seguinte método no controller <code>[HttpGet]
        public IActionResult Index(int idLeilao)
        {
            ConsultaCarrosModel obj = new ConsultaCarrosModel();
            ViewBag.ListaMarcas = obj.ListaMarcas("marcas.json");
            return View();
        }</code>
Ao clicar em um botão passando essa 'ID' na url ela é carregada com o ID que eu desejo mas o valor que chega no controller é sempre 0

Como podem ver a ID que passei na URL é 4 mas a que chegou no controller foi 0(default), como se ela não chegasse no controller antes de carregar a página
Answer: Tente utilizar o atributo Route:
<code> [HttpGet("/Home/Index/{idLeilao}")]
 public IActionResult Index(int idLeilao)
 {
     ConsultaCarrosModel obj = new ConsultaCarrosModel();
     ViewBag.ListaMarcas = obj.ListaMarcas("marcas.json");
     return View();
 }
</code>
Roteamento para ações do controlador no ASP.NET Core


Understanding a short exact sequence of sheaves associated to a divisor

Question: Let $M$ be a complex manifold and $D = \sum_i a_i V_i$ is an effective divisor where $V_i$'s are irreducible analytic hypersurfaces. Let $s_0 \in H^0(M,\mathcal{O}([D]))$ be a holomorphic section of the bundle $\mathcal{O}([D])$ in which $[D]$ is defined to be the image of $D$ under the short exact sequence of cohomology
$$H^0(M,\mathrm{Div}) \to \mathrm{Pic}(M) = H^1(M,\mathcal{O}^{\times})$$
associated to the short exact sequence of sheaves
$$0 \to \mathcal{O}^{\times} \to \mathcal{M}^{\times} \to \mathrm{Div} \to 0$$
where $\mathcal{O}^{\times},\mathcal{M}^{\times}$ are sheaves of holomorphic and meromorphic functions nonzero everywhere, respectively.
If $E$ is any holomorphic vector bundle, write $\mathcal{E}(D)$ for the sheaf of meromorphic functions on $E$ with poles of order $\leq a_i$ along $V_i$. Then, tensoring by $s_0^{-1}$ gives us an identification
$$\mathcal{E}(-D) \overset{\otimes s_0^{-1}}{\rightarrow} \mathcal{O}(E \otimes [-D])$$
In Griffiths & Harris, Principles of Algeraic Geometry, page $139$ the authors assert that

In particular if $D$ is a smooth analytic hypersurface, the sequence of sheaves
$$0 \to \mathcal{O}_M(E \otimes [-D]) \overset{\otimes s_0}{\rightarrow} \mathcal{O}_M(E) \to \mathcal{O}_D(E_{\mid D}) \to 0$$
is exact.

My question is why we need the condition of $D$ to be smooth here? In that case, could someone clarify the above sequence in more details. Any concrete example would be approciate.
Answer: This is somehow more subtle than I thought. For simplicity, consider $E$ to be the trivial bundle and $D$ irreducible. The smoothness condition on $D$ appears to guarantee that the sheaf of holomorphic functions on $D$ is well-defined (otherwise, all we could say is just its regular locus). In that case, for each open subset of $M$, consider the sequence
$$0 \to \mathcal{O}(-D)(U) \to \mathcal{O}_M(U) \to (i_*\mathcal{O}_D)(U) \to 0 $$
where $i: D \to M$ is inclusion and $i_*$ is pushforward functor. We can rewrite the above sequence
$$0 \to \mathcal{O}(-D)(U) \to \mathcal{O}_M(U) \to \mathcal{O}_D(U \cap D) \to 0.$$
Since $D$ is effective we hence can write $D = (s_0)$ ($s_0$ is irreducible) in which $s_0$ is holomorphic. The first map in the above sequence is just tensoring with $s_0$, that is, $s \mapsto s \otimes s_0 = ss_0$, the second map is just the restriction $s \mapsto s_{\mid D}$. The map $\mathcal{O}(-D) \to \mathcal{O}_M$ is clearly injective, for the exactness at the middle term, if $s_{\mid D} = 0$ then in a neighborhood of some point $p \in M$, weak nullstellensatz asserts that $s_0$ divides $s$.
For a proof of weak nullstellensatz, look at page $11$ in Griffiths & Harris, Principles of Algebraic Geometry.
A concrete example for the case of Riemann surfaces is already given here.