Lyapunov function for a second order system involving trigonometric functions

Question: I am studying the stability of the following system:
\begin{aligned}
 \dot{x}_{1} &= -x_{1}^{2} - \sin x_{2}\\
 \dot{x}_{2} &= x_{1} - \frac{\cos x_{2}}{x_{1}}\\
\end{aligned}
The system itself has 2 equilibrium points:
\begin{equation}
  \begin{aligned}
 x_{1} &= -\frac{1}{\sqrt[4]{2}}\\
 {x}_{2} &= -\frac{\pi}{4}\\
\end{aligned}
\qquad
\qquad
\text{and}
\qquad
\qquad
\begin{aligned}
 x_{1} &= \frac{1}{\sqrt[4]{2}}\\
 {x}_{2} &= -\frac{\pi}{4}\\
\end{aligned}
\end{equation}
Which I confirmed by analyzing the phase portrait of the system:

Through linearization, I determined that the left equilibrium point is an unstable focus and the right one is a stable focus according to the eigenvalues of the Jacobian matrix of the system evaluated in each equilibrium point.
\begin{equation}
  \begin{aligned}
  \lambda_{1} &= 1.2613 + 1.1124i\\
  \lambda_{2} &= 1.2613 - 1.1124i\\
\end{aligned}
\qquad
\qquad
\text{,}
\qquad
\qquad
\begin{aligned}
  \lambda_{1} &= -1.2613 + 1.1124i\\
  \lambda_{2} &= -1.2613 - 1.1124i\\
\end{aligned}
\end{equation}
As far as I know, it is possible to make a change of coordinates and translate the stable equilibrium point to the origin. So, my goal consists in finding an appropriate Lyapunov function for determining the stability of the origin (after the change of coordinates), employing Lyapunov's second method.
Among others, here are some candidate functions I've tried so far without satisfactory results:
\begin{equation}
  \begin{aligned}
  V(x) &= x_{1}\sin x_{1} + \frac{1}{2}x_{2}^{2}\\
V(x) &= \frac{1}{2}x_{1}^{2} + (1-\cos x_{2})\\
V(x) &= x_{1}\sin x_{1} + (1-\cos x_{2})\\
\end{aligned}
\end{equation}
I got stuck trying to find a Lyapunov function due to the trigonometric functions involved in the original system. Could someone give me a suggestion or hint?
Comment: It is not clear what you are trying to do. If you want to show that the equilibrium points with $x_1 > 0$ are locally stable, you already have done that with your linearization. As mentioned above there are multiple equilibrium points that are stable, so you will only be able to show that they are locally stable (what you already know from the linearization). So what are you trying to do? Are you trying to find a region of convergence by using a Lyapunov function?
Comment: Note that $x_2=-\frac{\pi}{4}+k\,\pi$ gives an infinite family of fixed points.
Comment: Yes, as Miguel mentioned, this system has an infinite number of equilibrium points. All those with $x_1<0$ are unstable whereas the others are stable. So there is no hope to find a global Lyapunov function as there is no globally stable equilibrium point here. Finally, the first and third candidate Lyapunov function you consider fail to be positive for all values of the state. Why are you trying to prove this result? I am asking because it may not be that important depending on your goals.
Comment: @KBS Does this mean that I cannot determine stability using Lyapunov's second method? What about local stability?
Comment: AFAIK there is no systematic way to find Lyapunov functions. They often stem from physical considerations: the system "dissipates energy" thus it is important to know if the ODE is a model of some physical system.
Comment: @EduardoSalazarHidalgo Yes, you can establish local stability properties and possibly some estimate for the basin of attraction of the equilibrium points.
Answer: From the stable equilibrium point $\left(\frac{1}{\sqrt[4]{2}}, - \frac{\pi}{4}\right)$, the state variable transformation can be constructed as
$$
\begin{aligned}
 y_{1} &= x_{1} - \frac{1}{\sqrt[4]{2}} \\
 y_{2} &= x_{2} + \frac{\pi}{4} \\
\end{aligned}
$$
for which there is an inverse
$$
\begin{aligned}
 x_{1} &= y_{1} + \frac{1}{\sqrt[4]{2}} \\
 x_{2} &= y_{2} - \frac{\pi}{4} \\
\end{aligned}
$$
such that system model
$$
\begin{aligned}
 \dot{x}_{1} &= - x_{1}^{2} - \sin(x_{2}) \\
 \dot{x}_{2} &= x_{1} - \frac{\cos(x_{2})}{x_{1}} \\
\end{aligned}
$$
in the new coordinates has the form
$$
\begin{aligned}
 \dot{y}_{1} &= - \left(y_{1} + \frac{1}{\sqrt[4]{2}}\right)^{2} - \sin\left(y_{2} - \frac{\pi}{4}\right) \\
 \dot{y}_{2} &= y_{1} + \frac{1}{\sqrt[4]{2}} - \frac{\cos\left(y_{2} - \frac{\pi}{4}\right)}{y_{1} + \frac{1}{\sqrt[4]{2}}} \\
\end{aligned}
$$
that can be expanded to
$$
\begin{aligned}
 \dot{y}_{1} &= - y_{1}^{2} - 2^{\frac{3}{4}} y_{1} - \frac{1}{\sqrt{2}} - \sin\left(y_{2}\right) \cos\left(\frac{\pi}{4}\right) + \cos\left(y_{2}\right) \sin\left(\frac{\pi}{4}\right) \\
 \dot{y}_{2} &= y_{1} + \frac{1}{\sqrt[4]{2}} - \frac{\cos\left(y_{2}\right) \cos\left(\frac{\pi}{4}\right) + \sin\left(y_{2}\right) \sin\left(\frac{\pi}{4}\right)}{y_{1} + \frac{1}{\sqrt[4]{2}}} \\
\end{aligned}
$$
and then be simplified to
$$
\begin{aligned}
 \dot{y}_{1} &= - \left(y_{1} + 2^{\frac{3}{4}}\right) y_{1} - \left[\cos\left(\frac{\pi}{4}\right) \frac{\sin\left(y_{2}\right)}{y_{2}}\right] y_{2} + \sin\left(\frac{\pi}{4}\right) \cos\left(y_{2}\right) - \frac{1}{\sqrt{2}} \\
 \dot{y}_{2} &= y_{1} - \left[\frac{\sin\left(\frac{\pi}{4}\right)}{y_{1} + \frac{1}{\sqrt[4]{2}}} \frac{\sin\left(y_{2}\right)}{y_{2}}\right] y_{2} - \frac{\cos\left(\frac{\pi}{4}\right) \cos\left(y_{2}\right)}{y_{1} + \frac{1}{\sqrt[4]{2}}} + \frac{1}{\sqrt[4]{2}} . \\
\end{aligned}
$$
Next, the above modeling equations is represented in the nonlinear state-space format
$$
\begin{aligned}
 \dot{\mathbf{y}} &= \mathbf{F}(\mathbf{y}) \mathbf{y} + \mathbf{B} \mathbf{u}(\mathbf{y}) \\
 \begin{bmatrix}
\dot{y}_{1} \\
\dot{y}_{2} \\
\end{bmatrix} &= \begin{bmatrix}
- \left(y_{1} + 2^{\frac{3}{4}}\right) & - \frac{1}{\sqrt{2}} \frac{\sin\left(y_{2}\right)}{y_{2}} \\
1 & - \frac{1}{\sqrt{2}} \frac{1}{y_{1} + \frac{1}{\sqrt[4]{2}}} \frac{\sin\left(y_{2}\right)}{y_{2}} \\
\end{bmatrix} \begin{bmatrix}
y_{1} \\
y_{2} \\
\end{bmatrix} + \begin{bmatrix}
1 & 0 \\
0 & 1 \\
\end{bmatrix} \begin{bmatrix}
\frac{1}{\sqrt{2}} \cos\left(y_{2}\right) - \frac{1}{\sqrt{2}} \\
- \frac{1}{\sqrt{2}} \frac{1}{y_{1} + \frac{1}{\sqrt[4]{2}}} \cos\left(y_{2}\right) + \frac{1}{\sqrt[4]{2}} \\
\end{bmatrix} . \\
\end{aligned}
$$
Taking the limit of $\dot{\mathbf{y}}$ as $y_{1} \rightarrow 0$ and $y_{2} \rightarrow 0$, we have
$$
\begin{aligned}
 \begin{bmatrix}
\dot{y}_{1} \\
\dot{y}_{2} \\
\end{bmatrix} &= \begin{bmatrix}
- 2^{\frac{3}{4}} & - \frac{1}{\sqrt{2}} \\
1 & - \frac{1}{\sqrt[4]{2}} \\
\end{bmatrix} \begin{bmatrix}
y_{1} \\
y_{2} \\
\end{bmatrix} \\
 \begin{bmatrix}
\dot{y}_{1} \\
\dot{y}_{2} \\
\end{bmatrix} &= \begin{bmatrix}
- a & - b \\
1 & - c \\
\end{bmatrix} \begin{bmatrix}
y_{1} \\
y_{2} \\
\end{bmatrix} \\
 \dot{\mathbf{y}} &= \mathbf{A} \mathbf{y} . \\
\end{aligned}
$$
Since this is a linear system, we postulate there exists a quadratic Lyapunov function $V(\mathbf{y}) = \mathbf{y}^{T} \mathbf{P} \mathbf{y}$, where $\mathbf{P}$ is a real symmetric positive-definite matrix. The derivative of V along the trajectories of $\dot{\mathbf{y}} = \mathbf{A} \mathbf{y}$ is given by
$$
\dot{V}(\mathbf{y}) = \mathbf{y}^{T} \left(\mathbf{P} \mathbf{A} + \mathbf{A}^{T} \mathbf{P}\right) \mathbf{y} = - \mathbf{y}^{T} \mathbf{Q} \mathbf{y}
$$
where $\mathbf{Q}$ is also a symmetric positive-definite matrix defined by
$$
\begin{aligned}
\mathbf{Q} &= 2 (a + c) (a c + b) \begin{bmatrix}
1 & 0 \\
0 & 1 \\
\end{bmatrix} \\
\end{aligned}
$$
and $2 (a + c) (a c + b) = 9 \sqrt[4]{2} > 0$. Solving the Lyapunov equation
$$
\mathbf{P} \mathbf{A} + \mathbf{A}^{T} \mathbf{P} = - \mathbf{Q}
$$
then the unique solution, $\mathbf{P}$ is obtained
$$
\begin{aligned}
\mathbf{P} &= \begin{bmatrix}
c^2 + a c + b + 1 & a - b c \\
a - b c & a^2 + a c + b^2 + b \\
\end{bmatrix} \\
\end{aligned}.
$$
This approach can be used to establish the local stability for the stable equilibrium point.


DE of curvilinear triangle sides on sphere

Question: Can we find a common differential equation of three lines on a sphere which form a curvilinear scalene triangle with internal angle sum $=\pi ?$ (I.e., no spherical excess.)
By common differential equation we can ensure the same character of curvature for its sides.
( A special case of constant geodesic curvature  i.e.,  circles of a particular radius can always be chosen to cut meridians symmetrically at $ 30^{\circ}$ forming an equilateral triangle of angle sum $\pi $ but a general situation is sought).
The question troubled me for quite some time ...
Answer: Earlier answered by achille hui to same question from me.
Three concurrent  small circles on a sphere intersect to enclose a curvilinear triangle of three arcs with sum of vertex angles $\pi$ , or zero "spherical excess".
This can be shown in stereographic projection where point of concurrency is the North Pole... which may be shifted to any other point on the sphere.
EDIT1/2
The picture shows original lines and their three small circles ( Blue,Green,Magenta) passing through North Pole and intersection points determine vertices of a triangle with angle sum $\pi$
A differential equation of small circles is requested. For time being top view is made on inversion basis trig inverting respect to $M$ the bowl or mirror of inversion, obeying relations:
$$ NP\cdot NQ= NS^2= NR^2= NM^2= 4a^2 $$
$$ 1/u^2= 1/\rho^2+ 1/(4a^2),\, u= \frac{2 a \rho}{\sqrt{4a^2+\rho^2} },\, r_1= u \sin\alpha=\frac{4 a^2 \rho}{4a^2+\rho^2 }, \, r=r_1\sec (\theta+ \beta) $$
where $\beta$ is longitude.


Most popular tags in a list as a block

Question: The Tagadelic module works very well out of the box; it is the only plug-and-play feature for a tag cloud available for Drupal 7.
I do not need to use the "cloud" format. I need the tags to be shown as  list, from the most popular to the least popular, rendered using the same font, style, and size.
How can Tagadelic be modified to achieve this? I guess it should require more than a CSS fix.
Is there any better option than Tagadelic?
Comment: Crossed to: http://stackoverflow.com/questions/6754497/drupal-7-most-popular-tags-in-a-list-as-a-block-how
Answer: You can do this with views:

create a view of terms
add a required relationship to "content using tags"
set use aggregation: yes
add the "term name" field a second time, set one of the to "aggregation type: count"
add "term name" as a sort criteria, set "aggregation type: count"

A sample view is at http://drupalbin.com/19467
Comment: Aggregation is built-in to Views 7.x-3.0!  There's no need for the additional module.
Comment: I assume you have the [Views Group By](http://drupal.org/project/views_groupby) module installed for the aggregation.
Comment: Oh, too easy! ;-)
Comment: Thanks for the solution. Don't forget to filter by node published using the relationship (if you are geting weird results).
Comment: Nice take, take into account that if you try to select "count", it will make a count distinct, so you need to mark "Number" in the aggregation settings. That will effectively count the usage of the term, without looking for distinct (which will result in a count of 1 for every single term ever used that passes the filter).
Answer: Tagadelic actually does what you want, but then uses CSS to modify the list into a cloud.
All you need, is to override the CSS in your theme:
<code>.wrapper.tagadelic {
  display: block;
  text-align : left;
  margin-right: 0;
}

.tagadelic.level1,
.tagadelic.level2,
.tagadelic.level3,
.tagadelic.level4,
.tagadelic.level5,
.tagadelic.level6,
.tagadelic.level7,
.tagadelic.level8,
.tagadelic.level9,
.tagadelic.level10 {
  font-size : 1em;
}
</code>
Answer: See the cctags module as an alternative.

flexible configuration and advanced features for theming clouds.
  (individual files of templates for tags, the names of the dictionary, pages clouds)
Comment: No idea. You'll have to hit the module's issue queue for further support on this I'm afraid.
Comment: CCtags is producing this error:

    Deprecated function: Call-time pass-by-reference has been deprecated in _theme_process_registry() (line 413 of /home/sites/site01/drupal/includes/theme.inc).
    Deprecated function: Call-time pass-by-reference has been deprecated in _theme_process_registry() (line 413 of /home/sites/site01/drupal/includes/theme.inc).

Any ideas?

Thank you for your help

Most popular tags in a list as a block


Borel $\sigma$-algebra of continuous functions

Question: Let $B(C(T,\mathbb{R}))$ be the Borel sigma algebra of continuous functions mapping from the compact metric space $T$ to $S$ defined by the canonical metric $\|\cdot\|_\infty.$
Now I was wondering whether we can write this sigma algebra also as a sigma-algebra generated by some cylinder sets?
If anything is unclear, please let me know.
Comment: A cylinder set is a set of the form $\{ f \in C(T,\mathbb{R}) : f(x_1) \in I_1,f(x_2) \in I_2,\dots,f(x_n) \in I_n \}$ where $x_1,\dots,x_n \in T$ and $I_1,\dots,I_n$ are intervals.
Comment: At least when $T$ is an interval, the answer is yes, but the story is not exactly short. You might look up constructions of the Wiener measure for some details.
Comment: @Ian could you just write down how the definition of the cylinder sets would look like or is this also tedious?
Answer: If we add the assumption that $T$ is separable then the answer is yes. Let's prove it.
Let $\cal P$ denote the $\sigma$-algebra generated by the cylinder sets, and let $\cal L$ denote the $\sigma$-algebra generated by the open sets in the uniform metric.
Note that $\cal P \subset L$, since the product topology is weaker than the uniform topology on $C(T, \Bbb R)$. This is true on any topological space, since uniform convergence always implies pointwise convergence.
The reverse direction (i.e, proving that $\cal L \subset P$) is a bit trickier.
First I claim that $C(T, \Bbb R)$ is separable (in the uniform metric). To prove this, let $\mathcal D \subset T$ be a countable dense subset. For $x \in \cal D$ and $r \in \Bbb Q_+$, define a continuous map $f_{x,r}: T \to \Bbb R$ as $f_{x,r}(y)=\max \{ 0, 1-r\cdot d(x,y)\}$. By the Stone-Weierstrass theorem, the set of all rational linear combinations of finite products of the $f_{x,r}$ forms a countable dense subset of $C(T,\Bbb R)$. Hence $C(T,\Bbb R)$ is separable.
Now, in order to show that $\cal L \subset P$, it suffices to show that any closed ball in $C(T,\Bbb R)$ lies in $\cal P$. Indeed, this would imply that any open ball lies in $\cal P$, since open balls are countable unions of closed balls. From open balls, you can conclude by separability of $C(T, \Bbb R)$ that any open set in $C(T, \Bbb R)$ lies in $\cal P$ (because open sets  in separable metric spaces are just countable unions of open balls). And from open sets, you can conclude that any Borel set in $C(T,\Bbb R)$ (i.e, any set in $\cal L$), lies in $\cal P$.
So to finish off the proof we just need to show that any closed ball $B(f, \epsilon) \subset C(T, \Bbb R)$ lies in $\cal P$. But this is easy: just write $$B(f,\epsilon) = \bigcap_{x \in \cal D} \pi_x^{-1}\big( [f(x)-\epsilon\;,\; f(x)+\epsilon] \big)$$
where the $\pi_x: C(T,\Bbb R) \to \Bbb R$ are the canonical projections $g \mapsto g(x)$, and $\cal D$ is a countable dense subset of $T$. Since $\cal P$ is generated by the $\pi_x$, and since $\cal D$ is countable, it follows that the right-hand side of the above expression is in $\cal P$, and thus $B(f, \epsilon) \in \cal P$, as desired.
Comment: Yes you are right. I guess I did not realize this when I wrote this answer as an undergraduate student. Please edit the answer if you have the time.
Comment: Any compact metric space is separable. So you don't have to assume that $T$ is separable. It's given.


União de Vetores em C

Question: boa noite. Estou com uma atividade avaliativa da faculdade para ser entregue mas não consigo pensar na lógica e resolver a primeira atividade. Alguém pode me explicar onde está o meu erro e um conselho para entender melhor índices em for. Faço uma confusão arretada com eles.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

/*DECLARAÇÃO DE VARIAVEIS*////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int main()
{
    setlocale(LC_ALL, "");
    int veta[10], vetb[10], vetu[20], vetd[10];
    int i, x, y, z, w, k;

    /*VETORES RECEBEM DADOS*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    printf("\n\t\t\tInsira os valores de VETOR A\n\n");

    for(i = 0; i < 10; i++) // Inserção dos valores ao vetor A
    {
        printf("Insira o valor do vetor A [%i]: ", i+1);
        scanf("%i", &veta[i]);

        vetu[i] = veta[i];      //ATRIBUI VALOR DO VETOR A AO VETOR C DIRETAMENTE.
    }

    printf("\n\t\t\tInsira os valores de VETOR B\n\n");

    for(i = 0; i < 10; i++) // Inserção dos valores ao vetor A
    {
        printf("Insira o valor do vetor A [%i]: ", i+1);
        scanf("%i", &vetb[i]);

        vetu[i+10] = vetb[i];   //ATRIBUI VALOR DO VETOR B AO VETOR C A PARTIR DA POSIÇÃO 10
    }

    /*VETOR B - RECEBE DADOS*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    printf("\n\t\t\tA União dos vetores A e B\n\n");

    for(x = 0; x < 20; x++)
    {
        for(y = 0; y < 20; y++)
        {
            if(vetu[y] == veta[x])
            {
                break;
            }
            else
            {
                vetu[y] = veta[x];
            }

        }
    }

    for(x = 0; x < 20; x++)
    {
        printf("%i\n", vetu[y]);
    }

}

O código deveria me mostrar (Todos os valores que contem no VETOR A e no VETOR B sem repetição. Ou seja, se o usuário digitar [1][2][3][3][4][5] E [6][5][3][7][8], o programa deveria me dar a seguinte saída: [1][2][3][4][5][6][7][8].
Mas não é isso que acontece...
Answer: O problema é que o seu código de achar a união não está correto, tanto em termos de lógica como implementação. Na verdade esta a fazer um laço/ciclo de 0 a 19 com x:
for(x = 0; x < 20; x++)

E depois testa o vetor A:
if(vetu[y] == veta[x])

Quando na verdade esse tem apenas 10 elementos, o que só por si está incorreto e pode-lhe dar um Segmentation fault. Para além disso não está a utilizar o vetb, assim como também não está a remover as repetições e sim apenas a reescrever valores.
Proponho que faça antes assim:
int tamanho2 = 20; //começa com o tamanho que definiu para a união

for(x = 0; x < 20; x++)
{
    //começa no numero seguinte ao x e vai apenas até ao tamanho2
    for(y = x + 1; y < tamanho2; y++)
    {
        //se é um elemento repetido no vetu. Note que já não uso ==veta[x] neste if.
        if(vetu[y] == vetu[x])
        {
            //quando encontra vai até ao fim a puxar os elementos uma casa para trás
            //esta lógica acaba por remover o elemento repetido
            for (k = y; k < tamanho2-1; k++){
                vetu[k] = vetu[k+1];
            }

            //depois de ajustar os elementos "diminuir" o tamanho do array resultante
            tamanho2--;
        }
    }
}

Exemplo a funcionar no Ideone
Repare que utilizei apenas o vetu que era o vetor que tinha todos os elementos, e removi as repetições dele próprio ajustando o tamanho e puxando elementos.
No final ficou em tamanho2 a quantidade de elementos sem repetições do array, que será o que deve utilizar a seguir para a escrita na consola.
Nota: Na ultima parte da escrita também tem um pequeno erro que convêm corrigir:
for(x = 0; x < 20; x++)
{
    printf("%i\n", vetu[y]);
    //------------------^ tem de ser x e não y
}

Outras alternativas
Poderia ter seguido outras soluções que garantem melhor complexidade de tempo, mas já são bastante mais elaboradas e provavelmente não vão de encontro às soluções que esperam para o exercício. Tentei usar a mais parecida com a  que estava a utilizar.
Exemplo de soluções alternativas com melhores complexidades:

Usar uma tabela de dispersão (hash table) e fazer uma inserção dos elementos nesta tabela o que irá evitar repetições e dar uma solução na ordem de O(n). Irá complicar se precisar de uma escrita na mesma ordem em que foram inseridos.
Ordenar o array resultante com um método eficiente tipo QuickSort ou MergeSort que lhe garante O(nlogn) e depois remover as repetições que será O(n²)  ou O(n) se passar os não repetidos para um novo array.
Se não precisa do array resultante (que não foi claro na pergunta) pode seguir outra implementação excluindo o vetu. Esta iria percorrer A e mostrar os que não existem em B e vice-versa, que lhe dá O(n²)

União de Vetores em C


Finiteness of intersection numbers

Question: I'm trying to understand Shafarevich's definition of intersection numbers:

By definition, "$D_1,...,D_n$ general position at $x$"  means that $\bigcap_{i=1}^n\text{Supp}(D_i)$ has finitely many points, say $P_1,...,P_k$ (one of them is $x$, say $P_k=x$).
I assume the neighbourhood $U$ is can be taken as the complement of $\{P_1,...,P_{k-1}\}$ so, by construction, $Z(f_1,...,f_n)=\{P\}$.
I don't understand how we can apply Nullstellensatz, since we are dealing with the local ring $\mathcal{O}_x$, and not the usual polynomial ring. I would get it if $f_1,...,f_n$ were polynomials, but that's not necessarily the case, so how do we justify that?
Answer: Firstly, any open set is the union of open affine sets.
[Without loss of generality, assume $U$ is open in the affine variety ${\rm Spec \ }A$. Then it is possible to express $U$ as a union of fundamental open sets of the form $D(f) := {\rm Spec \ }A \setminus V(f)$. (We say that the fundamental open sets form a basis for the Zariski topology on ${\rm Spec \ }A$.) The standard way to prove this is to note that, since $U$ is open, it must be of the form ${\rm Spec \ } A \setminus V(I)$ for some ideal $I$. So for any point $x \in U$, there exists some $f \in I$ such that $f$ does not vanish at $x$, i.e. $x \in D(f) \subset U$. Finally, note that $D(f)$ is actually affine: it is isomorphic to ${\rm Spec\ } A_f$.]
Anyway, the point is that by making the open neighbourhood of $x$ small enough, we can assume that $f_1, \dots, f_n$ are polynomials in some polynomial ring $B := k[x_1, \dots, x_m ] / J$.
Then all that remains is to observe that $x_1, \dots, x_m$ generate the maximal ideal $\mathfrak m_x$, so each $x_i$ is in $\sqrt{(f_1, \dots, f_m)}$, i.e. $x_i^{k_i} \in (f_1, \dots, f_n)$ for a suitably high power $k_i$, by the Nullstellensatz. Then take $k$ to be the maximum of these $k_i$'s.

Finiteness of intersection numbers


O nome 'Component' não existe no contexto atual

Question: Eu estou tentando criar um view component para reutilizar nas páginas, estou tentando seguir alguns tutoriais em video. Já instalei via nuget o Microsoft.AspNetCore.Mvc inteiro, mas quando eu tento chamá-lo a partir da viewpage, usando
@Component.InvokeAsync("Componente")

eu tenho o erro
O nome 'Component' não existe no contexto atual

Estou usando VS2017, asp.net mvc 5.
Alguem sabe oque pode estar faltando? Instalar alguma outra coisa que não sei?
Ou no mvc 5 é de outra forma a chamada do component?
Quando eu começo a digitar Compon e pressiono ctrl+espaço deveria aparecer a lista de opções incluindo o Component conforme a imagem a seguir, nota-se que Component não está aparecendo:
Comment: Qual a versão do asp.net? Se não me engano oViewComponent está disponível partindo do mvc core 1.1
Comment: dotnet --version
2.1.4
Answer: No seu caso o problema é porque View Components é um recurso apresentado no MVC 6 e Asp.Net 5 e a sua aplicação é na verdade um MVC5 com Asp.Net 4
Abaixo segue um exemplo da implementação no DoteNetCore (referência).
Primeiro crie um diretório, na raiz da sua aplicação MVC, chamado ComponentsView e adicione uma nova classe chamada ComponenteViewComponent
que deve herdar da ViewComponent
public class ComponenteViewComponent : ViewComponent
{

    public async Task<IViewComponentResult> InvokeAsync()
    {
        return View();
    }
}

Se você não respeitar o sufixo ViewComponent o MVC não a reconhecerá como tal e talvez aí possa estar o seu primeiro problema. Se você criou a classe chamando apenas de Componente, você precisa adicionar uma anotação para que o componente seja reconhecido por esse nome.
[ViewComponent(Name = "Componente")]
public class Componente : ViewComponent
{

    public async Task<IViewComponentResult> InvokeAsync()
    {
        return View();
    }
}

Observado os pontos acima e após a criação da classe, vá até o diretório /Views/Shared/, adicione o diretório Components e dentro dela mais uma pasta chamada Componente, que é o nome do seu componente.
Dentro da pasta Componente adicione a PartialView chamada Default, meu exemplo eu adicionei apenas o seguinte trecho de html:

Olá eu sou um componente

Por fim sua estrutura deverá estar assim:

Agora, em uma view qualquer do seu site você pode invocar o seu componente, no meu caso adicionei o trecho no topo da view Index da HomeController:

    @await Component.InvokeAsync("Componente")

E o Resultado é esse:
Comment: Muito interessante!
Comment: Ele acaba funcionando como um "MVC dentro do MVC", permite o reuso de muitos componentes com uma maleabilidade e desacoplamento maior do que com simples partials views
Comment: @LeandroAngelo refiz exatamente seguindo os passos citados, mas o continuo com problema, o problema ainda esta na chamada do componente na view. agora com o await aparece o mesmo erro da imagem que foi anexada na pergunta, agora sendo: O nome 'await' não existe no contexto atual. será q eu não tenho q instalar algo pelo nuget que eu não estou sabendo? eu instalei esse: Microsoft.AspNetCore.Mvc
Comment: Como está a sua _ViewImports.cshtml na raiz da pasta views
Comment: Na raiz da pasta Views arquivos tem só _ViewStart.cshtml e Web.config, no _ViewStart.cshtml tem o seguinte conteúdo:@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
Comment: Quando eu começo a digitar Compon e pressiono ctrl+espaço deveria aparecer a lista de opções incluindo o Component conforme a imagem  anexada na pergunta agora pouco nota-se que Component não está aparecendo.
Comment: Web.Config??? você criou o projeto como?
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/78547/discussion-between-jonas-centenaro-and-leandro-angelo).


How can i remove required field validation on click submit button?

Question: I have some radio buttons such as draft, need review, etc. I want to remove (omit) the required fields when draft is selected, and click on the submission button.
I tried with below code but it is not working.
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
 if($form_id =='catalog_node_form')
 {
  $form['#validate'][] ='remove_required_field';
 }
}

function remove_required_field($element)
{
 foreach (element_children($element) as $name)
 {
  $element[$name]['#required'] = FALSE;
 }
 return $element;
}

Comment: simple solution is  dont mark the field as required.
Comment: *["If the question is about code you wrote, for which you want to write better code, or you want to understand why it doesn't work, show the code you are using, or the part of the code that is relevant for the question."](http://drupal.stackexchange.com/help/on-topic)*
Comment: Add your code to the question body rather than adding that as a comment.
Answer: In the form_alter function you can use the limit_validation_errors property.
'#limit_validation_errors' => array(),

The above code will not perform any field validations. You can then add the individual fields that you need to validate here using the below code.
$form['actions']['next']['#limit_validation_errors'][] = array($field_key);

Where next is the action that I am using.
Comment: Good way, but possibly a bit overcomplicated.
Comment: True. It may be a little over-complicated. I wanted the control as I was building a multi-step registration form and hence it made sense in my case :)
Comment: Yea, if you want to leave evaluation to the original module, your way is better than mine. But if original module only sets `#required`, my way is simpler. So, it all depends on use-case.
Answer: Problem with your code is caused by the fact that #required is resolved before custom validation handlers. Thus, when remove_required_field() is called, it's already too late.
Instead, un your mymodule_form_alter() hook set:
$element[$name]['#required'] = FALSE;
$form['#validate'][] ='function_that_will_test_checkbox_only_if_its_needed';


Initial migrate in laravel 5 with a reference in the ConfigServerProvider fails

Question: In my ConfigServerProvider.php at boot there is a reference to the configs database table. At initial migrate this database table doesn't exist, so I am getting an error. How can I run the first time 'php artisan migrate', while leaving this boot line intact?
public function boot() {
    config([
        'version' => "1.0.2",
        'title' => Config::where('name', 'title')->first()->pluck('value')
    ]);
}

I added this around the whole config:
    if(Schema::hasTable('configs')) { }

And that seems to make all work.
Comment: You're gonna need to write some code to check if the table exists...
Answer: In my app i made this:
try {
    $configs = Config::all();
} catch (\Exception $e) {
    $configs = [];
}


Send ssh commands with a script

Question: I want to to check a Nortel Router by running ./script:
#!/bin/ksh
print "IP:"
read ip;
ping ${ip};
ssh -l default ${ip} "sho mod; en; sho int; sho node-e; sho node-a";

I can ssh normaly with
    ssh -l [user] [ip].
But not with
    ssh -l [user] [ip] '[cmd1], [cmd2]' it says automatically "Conection to [ip] closed."
Comment: What if you leave the commands off of the end? Does the ssh complete successfully then?
Comment: How are you sending in the password when you run the script? Or are you using `$HOME/.ssh/authorized_keys` (or similar). Good luck!
Answer: There's application called expect which can do that kind of interaction / terminal simulation for you. Otherwise, you could write a script using fabric or even straight in python using paramiko
Running commands this way would be better of course, but if your router doesn't accept commands this way, you'll need to simulate the standard connection.
Comment: The problem here is most likely your router as I tried your commands out. I would suggest going to Nortel's website and asking there about that specific issue.

Send ssh commands with a script


cygwin ssh connection to server port 22 connection refused on localhost

Question: I set up a ssh server through ssh-host-config.  Then I started the server.
net start sshd
The CYGWIN sshd service is starting.
The CYGWIN sshd service was started successfully.

When I try to connect I get:
ssh myusername@localhost
ssh: connect to host localhost port 22: Connection refused

I tried to allow port 22 in Windows Firewall, but that didn't change anything.  And because I'm trying to ssh locally I don't think Windows Firewall is the culprit.
I'm using Windows 7 and
What should I look for to fix this problem?
Comment: Enable `telnet` command and checking with `telnet localhost 22`?
Comment: Can you post the output from 'netstat -an | grep 22'
Comment: @EightBitTony: the original poster is using Windows 7, he should use `findstr` instead of `grep`.
Comment: $ netstat -an | grep 22
  TCP    127.0.0.1:62522        0.0.0.0:0              LISTENING
  TCP    192.168.1.4:51585      126.96.36.199:80       ESTABLISHED
Answer: From the netstat output (which you might want to move into your question), the SSHD daemon is not listening on port 22.  Which probably means although it started, it then crashed or stopped.
Try running sshd -d -d
That will run sshd in the foreground with debugging turned on, and you can see if / why it's crashing.
Answer: It is clear from the netstat output that either sshd is not listening on port 22 or the service is not running (crash on start). Best place to look for in windows would be event viewer in control panel. Also in the services.msc, see if it logging. If it is logging , logs would tell you what is happening and hence you would find the fix. Open resource monitor and see if the process sshd is running.


Capturing keyup event (JavaScript) from Drupal editors (CKeditor)

Question: I maintain the Textfield Counter module. An issue was raised that the module does not work for textareas with CKEditor enabled. I need to catch a keyup event from editors, or even just the CKEditor module, for the module to work. I haven't worked much with Drupal editors, nor CKEditor. Does anyone have any insight into how to do this, or an alternate solution?
Comment: I'd rather say this is off-topic here, but how about `editor.document.on('keyup',function(){alert('keyup')});` in your module's custom JavaScript?
Comment: I'll try that. Thanks. I know it seems off-topicish, but in the end I'll post a Drupal-relevant answer once I get this figured out. I'm hoping there is some sort of Drupal editor JS API I don't know about.
Answer: Well, once again I've come up with my own answer, though it's not really the one I wanted.
First off, it does not appear that there is any Drupal JavaScript API for interacting with editors. So I had to go directly to the CKEditor API to capture the key up event.
This is the code I was eventually able to use:
<code>CKEDITOR.on('instanceReady', function () {
  // Get the HTML ID of the textarea input that would be used if the editor were not enabled:
  var fieldID = $(".some_textarea").attr("id");
  if (CKEDITOR.instances[fieldID]) {
    // Add keyup listener.
    CKEDITOR.instances[fieldID].on("key", function () {
      // The last key pressed isn't available in editor.getData() when
      // the key is pressed. A workaround is to use setTimeout(), with no
      // time set to it, as this moves it to the end of the process queue,
      // when the last pressed key will be available.
      var editor = this;
      window.setTimeout(function () {
        var text = editor.getData();
        // Do something with the text.
        // Also note that the original textarea can be
        // retrieved from editor.element.$. So you could
        // do this:
        var originalTextarea = editor.element.$;
      });
    });
  }
});
</code>


Find an example (as small as possible) of a graph with $6$ vertices of degree $3$ and other vertices with degree $\leq 2 $ with $12$ edges

Question: How can we find an example (as small as possible) of a graph with $6$ vertices of degree $3$ and other vertices with degree $\leq 2 $, with $12$ edges. Thank you.
Answer: Since the graph must have $12$ edges, the sum of the degrees of the vertices must be twice that: $24$. Notice the $6$ vertices of degree $3$ contribute $18$, and thus we are still short by $24-18 = 6$. We are allowed to add vertices whose degree is at most $2$; in order to minimize the amount of vertices needed, we'll try to only add vertices whose degree is $2$. Since there are $6$ degrees left to account for, then we want $3$ vertices of degree $2$.
In order to arrange these vertices into a graph, I believe it is possible to construct a graph with the desired properties if the vertices of degree $3$ and the vertices of degree $2$ belong to two different connected components.
Answer: Just a graph that fits your requirement and is "as small as possible". A construction and calculation approach is already given by the other answers (@Andrei Kalunchakov, @benguin).
Answer: It turns out 9 vertices is the minimum possible.  It must be at least 9, since the number of edges (which equals 12) is half the sum of the degrees (by the Handshaking Lemma).  (With fewer than 9 vertices we have degree sum at most $3+3+3+3+3+3+2+2=22$, allowing only 11 edges.)
Using geng which comes with Nauty, we can generate all the $12$-edge $9$-vertex graphs, then filter out those with degree sequence $(3,3,3,3,3,3,2,2,2)$.  A simple example is $K_{3,3} \cup C_3$.
It turns out there are 68 non-isomorphic examples, and they are drawn below (with the vertices marked with their degrees):
Answer: Take a look at the Petersen's graph.

Delete 3 successive outer edges. You will receive the second graph. It already satisfies your conditions.
But, as benguin stated in the answers, this is not minimal according to the number of vertices.
Denote $N$ as a number of vertices with degree $\le 2$. We have
$$12 \le \frac12\left(6\cdot3 + N\cdot 2\right).$$
So, we have $N \ge 3$.
Finally, note the two outer vertices could be merged and the resulted graph will be optimal.
Comment: Then 3rd one is our required graph?
Comment: @MatheMagic, yes


Safely getting card number for payment gateway

Question: I have a payment gateway api for BluePay.  My application is in PHP.  I am able to process a transaction with code similar to this:
bp->process(1111111111111111,.....)
with 111111111111111 being the card number.
the process function posts the card number to bluepay's site using PHP's CURL wrappers.
How can I safely get a card number from the user?
where I substitute 111111111111111 with a variable that is filled in from the user.
Comment: Your question is a little bit vague.
Answer: You'll need to ensure that both receiving the card number (from the user) and sending the card number (to your gateway) is done over an SSL connection. I assume your gateway wouldn't allow it any other way, so that side of the transaction is * probably* already safe.
It's also important not to store the CC data anywhere, simply pass it onto the gateway.
So you need to purchase an SSL certificate for your web server, and make sure all sensitive information sent is encrypted (https://). You can generate the SSL certificate yourself, but that won't give your users a warm fuzzy secure feeling. It also wouldn't verify that your site is who it claims to be.
Comment: By "store", do you mean on the disk or as a variable? Also, how can you generate the SSL certificate yourself?
Comment: By 'store' I mean anything outside of the (temporarily executing) script. Flat file, Database, Cache, any long term storage (so yes, on disk). Self signed certificates can be generated without a signing CA, but lack the authenticity check a CA provides.
Answer: Give them a form over an encrypted connection?
Answer: You can get a cheap single domain SSL signed certificate at namecheap
In addition to this I would also recommend hashing the number before sending it. SSL is not perfect: Defeating SSL
Answer: Don't forget, if you are hosting a page which gathers credit card information, this system then becomes 'in-scope' as far as the PCI-DSS (Payment Card Industry Data Security Standard) is concerned, which comes with a whole world of grief if you have to comply to it!
You may be better off using a 'hosted' solution for your payments. i.e. the user is redirected to a page hosted on, say, Worldpay.com, to actually enter their card details, and then redirected back to your site afterwards.
Comment: Hosted pages aren't your only option if you want to eliminate credit card information from your environment. With Braintree's transparent redirect API ( http://bit.ly/braintree-api ), you host the form that gathers the credit card information, but it gets submitted directly to Braintree. You retain control over the checkout process, but your PCI scope is tremendously reduced. Disclosure: I work for Braintree.


Como salvar um trabalho em python pra não precisar rodar tudo cada vez que abre o script?

Question: Estou trabalhando em um projeto de análise de dados no jupyter, trabalho com cerca de 5 data frames diferentes (quais são importados de CSVs) e relacionados através de uma chave ou outra, a partir desses DFs e suas relações, dentro do jupyter, começo a verificar a consistência dos dados, fazer análises, criar novos datas frames e assim por diante.
Meu problema é: cada vez que fecho o jupyter e vou retomar o trabalho, só fica salvo os outputs e os scripts de cada notebook, mas para obter os objetos gerados eu preciso sempre rodar tudo de novo desde o início.
Pesquisei um pouco e vi alguns meios de serialização pra ir salvando um a um, objeto por objeto (num pickle, feather ou algum outro meio), e depois importa-los também um a um, mas isso me parece extramente trabalhoso, tanto quanto rodar tudo de novo...
Gostaria de saber se há alguma outra forma de salvar o trabalho, algo como uma imagem, tipo o .rdata para R, pra quando abrir o jupyter, ter um fácil acesso ao que vinha sendo desenvolvido.
Qualquer informação, ou compartilhamento de como vocês salvam seus trabalhos já vai me ajudar muito. Obrigado
Answer: Sim - o caminho é de fato usar uma serialização como Pickle, mas não é tão trabalhoso assim -
(na verdade,  Jupyter tem um atalho para executar todas as células em sequência - você está usando isso? Não deveria dar trabalho)
O fato é que a forma de trabalhar com o Jupyter é mio que um itnermediário entre programação tradicional e uma planilha - ao fazer análize de dados, muitas das células você vai usar como rascunho, mudar parâmetros e expressões, não vai quere rrodar de novo - e vai ter outras células como base, onde você está lendo suas fontes de dado, montando os dataframes, etc... que provavelmente são o que você quer executar toda vez. Então dá pra entender por que simplesmente "executar todas as células" pode não ser prático - já que as células usadas para rascunho e experimentação serão processadas também.
Uma saída, antes de partir para precisar serializar as coisas, é colocar elementos mais próximos de "programação", com o uso de funções.
As células do Notebook, podendo ser re-executadas a qualquer momento fazem alguns dos papeis que temos em funções - e aí tendemos a deixar todo o código "solto" nas células - e isso leva a essa necessidade de re-executar tudo.
No entanto, se você colocar todo o código para criar os dataframes que você precisa em funções, e amarrar tudo numa função única de inicialização, vai precisar executar só essa função - sem ficar selecionando células para executar, etc...
Então, de forma mais concreta, vamos dizer que você tenha
cel 1:
import pandas as pd, numpy as np
# outros impots

df1 = pd.read_csv(...)
# outros passos para estruturar o df1

cel 2:

df2 = pd.read_csv(...)
# passos para estruturar o df2

E assim por diante -
Você pode colocar as chamadas dessas células em funções - ficando com algo como:
cel1
# isole todas as importações numa única celula

cel2
def cria_df1():
    global df1
    df1 = pd.read_csv(...)
    # demais passos

...
cel n:

def inicializa():
     cria_df1()
     cria_df2()
     cria_df3()
     cria_df4()
     cria_df5()

Pronto, agora ao começar o trabalho, só é necessário executar as importações,
e, na própria célula em que você vai começar a trabalhar executar
inicializa()  -  (a chamada também pode estar na mesma célula em que a função
inicializa está definida, claro - aí você executa só aquela célula)

Agora, se o problema não for só a quantidade de passos e ter que executar todos clicando nas células, mas sim, que haja tanto processamento envolvido que a inicialiação demora mais que alguns segundos, pode valer a pena serializar os dataframes e carregar de volta os dados já processados.
Para isso, o módulo pickle do Python é o suficiente. Sugiro estruturar o salvamento e o carregamento dos serializados em funções, pelos mesmos motivos acima.
cel m:
def salva_tudo():
    import pickle
    pickle.dump((df1, df2, df3, df4, df5),  open("dados_mastigados.pickle", "wb"), protocol=-1)

def carrega_tudo():
    global df1, df2, df3, df4, df5
    import pickle
    df1, df2, df3, df4, df5 = pickle.load(open("dados_mastigados.pickle", "rb"))

Pronto - basta você chamar  a função carrega_tudo() para os dados dos datframes serem restaurados em memória no ponto em que estavam quando salva_tudo()  foi chamada em uma sessão anterior.

Modularizar parte do código com funções é fundamental - mas além disso, o próprio Jupyter notebbok tem várias funcionalidades, independentes do Python, que permitem melhorar o fluxo de trabalho também - incluindo executar programas em Python inteiros que estão em arquivos, marcar células para não serem executadas quando se manda "executar tudo", etc ---
Este artigo cobre bastante dessas funcionalidades:
https://towardsdatascience.com/how-to-effortlessly-optimize-jupyter-notebooks-e864162a06ee
Comment: Muito obrigado, ajudou muito! De fato sou novo em python, e apesar de estar no início das análises e os processos não estarem demorando tanto pra rodar denovo, estava preocupando quando de fato fosse haver muitas transformações e procedimentos que demorassem mais no processamento.

Sinto muito isso que disse do código desorganizado, já que muitas células realmente são usadas somente para teste/rascunho, você tem alguma sugestão para organiza-los melhor? Ou recomendaria algum outro software?
Comment: Para o tipo de exploração de dados que tem que se fazer com dataframes, o notebook é  a melhor coisa mesmo.

O melhor é ganhar familiaridade com funções, como mencionei na resposta - mas há várias outras funcionalidades do Jupyter em si, inclusive macros, e diretivas para não executar algumas células automaticamente quando executar tudo - vou colocar o link para um bom artigo sobre isso na resposta.


Check if input number is valid in Codeigniter Form Validation

Question: Can you help me to validate if my input number is valid.
It can be a whole number
It can also be a decimal number but interval is 0.5, So 0.5, 1.5 , 2.5 is ok but .2,1.3,2.6 is not valid.
if ((preg_match('/^\d+\.\d+$/',$bkpoints))  || (preg_match('/^\.\d+$/',$bkpoints)))
{       {
    if ($bkpoints % 0.5 !== 0)
    {
          $this->form_validation->set_message('is_bk_decimal','Bk points decimal value should be incremented by 0.5');
          return false;
    }

 }
 return true;

Answer: You can validate it with one single regex ^\d+(?:\.[05]0*)?$ :
if(preg_match('#^\d+(?:\.[05]0*)?$#', $bkpoints)){
    echo 'valid';
}

Explanation:

^ : begin of line
\d+ : match a digit one or more times
(?: : start of non-capturing group

\. : match a dot
[05] : match 0 or 5
0 : match 0 zero or more times

): End of non-capturing group
? : make the group optional
$ : end of line

online regex demo
Comment: Thanks much, Actually We are almost there but when I input 0.5 it also gave invalid. 0.5 should also be accepted
Comment: @user2046410 impossibruuuu [regex demo](http://regex101.com/r/bS1yB9) | [php demo](http://ideone.com/jaC5mP). Make sure you don't have spaces etc...
Comment: I edit it like this  if((preg_match('#^\d+(?:\.[05]0*)?$#', $bkpoints)) || (preg_match('#^(?:\.[05]0*)?$#', $bkpoints))){ and it works fine for. Thank you very much for the idea HamZa
Comment: @user2046410 You could wrap everything in one single regex `^\d+(?:\.[05]0*)?$|^(?:\.[05]0*)$` [demo](http://regex101.com/r/tS8hM7). What you have will even match empty strings.
Answer: Try the is_numeric() function in PHP:
http://php.net/manual/en/function.is-numeric.php
It'd return true if the number is an valid number, and return false if it isn't.
Comment: ah yes but it will not check if its interval of 0.5
Comment: I'm sorry, check my other answer below ;)
Answer: Or you could also use the ereg() function:
if(ereg("^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,2})?$", "0.9")){
  echo "number";
}else{
  echo "not a number";
}

Comment: Update your existing answer, don't post a second one... also: `ereg` is _DEPRECATED_, use `preg_match` instead. Lastly: regular expressions to check if a value is a float is just total overkill


How to "transfer" first responder from one UIView to another?

Question: I have a UIView subclass (CustomView for purposes of this question) that has its own handling of all touches events (Began, Moved, Ended, Cancelled). I also have a UIButton that is a sibling of CustomView that overlaps it.
For example, my view hierarchy looks like this:

UIView (Controller's view)

CustomView with frame (0, 0, 300, 300)
UIButton with frame (0, 0, 100, 50)

I would like the CustomView to capture touch events once the user has dragged out of the UIButton. Through debug logging, it appears that the UIControlEventTouchDragExit event is the one to intercept (though it doesn't fire until the touch is around 100 pixels away from the button, but that is not important to this question).
Ideally, when the drag exit event is fired, the button would stop receiving touch move events, the CustomView would get a touchesBegan event (even if I need to fake one myself somehow), and all future touch events (touchesMoved, etc) would be sent to the CustomView.
I have tried the following, and it doesn't have any effect:
-(void)btnTouchDragExit:(id)sender
{
    UIButton * btn = sender;
    [btn resignFirstResponder];
    [customView becomeFirstResponder];
}

I think the underlying UITouch object (which is consistent across touch events) is not being retargeted to point at the CustomView. How can I achieve the desired effect?
Answer: Just use hitTest:withEvent: to figure out what view "should" be receiving the event, then forward on the event to the appropriate view.  You might have to do a little bit of dancing around to intercept events before they go to the button, but this is what hitTest:withEvent: was made for.
Comment: That works, but it's what I was trying to avoid, namely because this requires subclassing, and by doing that I can only have this behavior on Custom buttons (not Rounded Rect or any others). I've also seen odd things happen when forwarding touch events to things like UIScrollViews and UIWebViews, so it may not be a completely generalized solution.

I'll leave the question open for a while to see if there are any other suggestions.
Comment: By subclassing UIButton and overriding touchesMoved, I've been able to do this (walk the superview tree calling hitTest until it finds one that has the touch point in it).. However, I have to manually forward (from that point on) the touch events to that view. Isn't there a system call so that Cocoa/UIWindow/UIApplication sends the touches to that new view? In Win32, it's ReleaseCapture/SetCapture(newWnd)..
Comment: Call hitTest:withEvent: on the superview, and it'll tell you which of its subviews would be the first responder to the event.  Once you figure that out, just call `touches(Began|Moved|Ended):withEvent:`
Answer: you have to override canBecomeFirstResponder to return YES otherwise becomeFirstResponder does nothing.  This is already done on UIControls, but not on UIViews
Comment: Adding that to my UIView subclass did not help. Subclassing UIButton and forcibly redirecting touch events was still needed. From a conceptual standpoint, it seems like in order to get this to work, I wouldn't be calling `[customView becomeFirstResponder]` anyway, but should be calling something like `[UIApplication assignFirstResponder:customView]` or some other static/global function.


Dynamic TextField width based on user input

Question: By default, a TextField has a bottom border underneath it. The only way to control its width is by setting the width of the TextField itself (or wrapping in a Container). However, both of these involve hardcoding the width. How do I dynamically change the width of the TextField so that the underlining bottom border is only the width of the inputted text (or the hint text)?
Here are some examples.
The first image is a TextField with hint text. Its width is equal to the screen width.
<code>  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: TextField(
          decoration: InputDecoration(hintText: "Enter title"),
        ),
      ),
    );
  }
</code>
That produces the following:

Now, I constrain the width with a Container:
<code>  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: Container(
          width: 70,
          child: TextField(
            decoration: InputDecoration(hintText: "Enter title"),
          ),
        ),
      ),
    );
  }

</code>
Which produces the following:

When I use a container and set its width, it will never change after that. How do I have the width dynamically change based on the length of the text input?
Comment: I found https://pub.dev/packages/auto_size_text_field/example package. but I didn't check it package.
Comment: any update for this question?
Comment: Yes, sorry, I haven't been able to try it until now. Using a wrap did not seem to change anything. Its width still remains the same. I updated my question to clarify possible confusion.
Comment: please post your code.
Comment: I updated my post with code and better screenshots
Answer: <code>IntrinsicWidth(
  child: Container(
    decoration: BoxDecoration(
      border: Border(
        bottom: BorderSide(
          width: 1.0,
        ),
      ),
    ),
    child: TextFormField(),
  ),
);
</code>
Comment: While this code may solve the problem,
[including an explanation](//meta.stackexchange.com/q/114762)
really helps to improve the quality of your answer. Remember that you are
answering the question for readers in the future, and those people might
not know the reasons for your code suggestion. Please also try not to crowd
your code with explanatory comments, as this reduces the readability of both
the code and the explanations.


What do the different kinds of arrows between classes and interfaces in this Hibernate diagram mean?

Question: I am trying to understand the following diagram from http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html for relationships between Hibernate's classes.

I am not quire sure what the different kinds of arrows mean, and I guess they are not following UML diagram specifications. Could someone explain what the different kinds of arrow mean? Thanks.
Comment: I'd guess those were made with some Eclipse tool :-/
Answer: The circled Is and C (likely for interface and class) are no UML standard. However, you can adorn stereotyped classes with icons at your wish. Though I doubt that the standard classes here need a stereotype to mark them as "standard class".
I'd guess that the

dotted arrows with filled triangles should be Realizations (since they point to interfaces). These would need an unfilled triangle in UML to be correct.
The same goes for the solid lines with filled triangle which are likely generalizations. UML needs unfilled triangles here.

Anything else (which isn't much) seems fine.

Dependency with dashed line and open triangle
Directed associations with composite shown by filled diamond.
Comment: @Gholamali-Irani Yes, it is. See also https://www.uml-diagrams.org/association.html
Comment: Thanks, Is **Directed Association with Composite** a standard UML notation?
Comment: @Thomas Kilian: The term "Directed Association" is not a UML standard term. In fact, UML only defines navigability arrows, but no concept of "directionality" as needed for uni- and bi-directional associations.
Comment: @GerdWagner Yes, you are right. I was using it more in a colloquial sense to say that they Indians were using the right arrows here.
Answer: If i understand it, it is not an UML diagram.

The arrow between SessionFactory and SessionFactoryImpl coudld be a generalization, but in UML the arrow is empty not filled as in your diagram
The arrow between Transaction and TransactionImpl seems to be a realization relation, but in UML there is no composition but a dash line with an empty arrow
The arrow between TransactionImpl and EntityTransaction may be a dependency but in UML this is an open arrow.
Comment: @Gholamali-Irani I'd say it's an UML diagram with syntactical errors ;-) Like you wouldn't say "this sentence not is English" is not English but wrong English.


Having trouble compiling and recreating a JAR file using Eclipse

Question: I have a Java JAR file that was developed to run in the browser. It works fine. There doesn't appear to be any sort of build file associated with the source code I've been given and I'm attempting to create a project and/or build script.
The source code references some third party code. What I've done is unzipped the JAR file into a folder that has this structure:
<code>\App\src\com
\App\src\META-INF
\App\src\applet
</code>
The "com" folder contains subfolders which contain the .CLASS files for the third party libraries. "applet" contains the .JAVA source code files (one folder, maybe 15 files).
The code appears to be written in 1.4 syntax (I manually attempted to compile some of the .JAVA files and it complained that some things were deprecated and/or required the older version).
I created a Java Project in Eclipse and pointed it to the \App folder. Then I went into the Properties for the project and went to Libraries and and clicked on "Add Class Folder" and added the \App\src\com folder. Then I went to "Order and Export" and moved this to the top.  I also set the Java Compiler version to 1.4.
I am getting a large number of compiler errors, all of which seem to stem from the fact that it says it can't resolve an import. This import is the set of .CLASS files contained in the "com" subfolders. The namespace matches the directory structure.
This seems like it should be really straightforward, but I've tried various things and don't seem to be making any progress. Based on what I've read I'm sure it has something to do with the pathing but I'm at a loss at this point on how to fix it.
(I'm sure it goes without saying that I'm not a Java dev.)
Any thoughts or ideas as to where I'm going wrong?
Answer: Can you please try to right click on Eclipse's Navigator. Select Import>General>archive file> (Jar file that you want to import).
You should be getting the jar file correctly imported at this point. Do tell me if you face any problems.
Comment: OK, I imported from the JAR into a new folder. Then I copied in the .java files into the directory that currently only has the .CLASS files. How do I get it to compile a new JAR if I make changes to the .java files? I checked the output folder (bin) and it seems like it's set-up to auto-compile, but their isn't any output file/JAR being created.
Comment: You would not need to manually copy the .java files into any directory. The IDE should place it correctly when importing the JAR file. Once you complete your development and testing within Eclipse of the changes that you made to the Source code you extracted from the jar file. You can create a the Jar file by right clicking on folder which contains your jar project, select 'Export>Java>JAR>'. In the next page you would fill in the path that you want the Jar to be placed in etc.
Comment: The original JAR file only included the .CLASS files - no .java files. When I export it I'm getting a few errors like "MyApplet [in MyViewerApplet] is not on its project's build path. Unable to get package fragment root /MyViewerApplet/MyApplet/MySource.java.


Heteroscedasticity in residuals vs. fitted plot

Question: I am testing whether price per ounce of beer (continuous variable, range of values mostly between 0.1 and 0.5 dollars) and the presence of promotion, advertisement, and display (all binary) have effect on the total amount of ounces purchased (continuous variable).
Here is my residual vs. fitted plot before the log transformation of y:

This is the residuals vs. fitted plot after the log transformation of y:

Heteroscedasticity is very high (White's general t statistics is nearly 800).
This is the histogram of the transformed y:

Any ideas or suggestions on how to improve my model or where to look for errors in order to improve the problem of heteroskedasticity are greatly appreciated.
Answer: Your response variable isn't really continuous.  It is presumably discrete (you can't buy .5 ounces, and moreover, beers only come in certain ounce sizes).  In addition, no one can buy less than 0 ounces (you can clearly see the floor effect in your top--untransformed--residual plot).  As a result, using an OLS regression (that assumes normal residuals) is likely to be inappropriate.  You should probably try to use Poisson regression.  In fact, a zero-inflated Poisson, negative binomial, or zero-inflated negative binomial are more likely what you will end up needing.
Comment: The fact that you were able to get the exact number is nice, but those numbers only come in certain possible increments (eg, no .5's & no -3's). You would still be better served by using a count model.
Comment: You can even see this behavior in the log-transformed response histogram:  you have "spikes" and deep valleys that arise because the response variable, while not necessarily integer-valued, is also not truly continuous because beer is typically sold in standardized volumes, so certain values are much more common than others.
Comment: Here is a correction: My response variable is in fact continuous because I was able to calculate total ounces purchased per transaction regardless of size or form of beer packages. Any more suggestions?
Answer: Not only is your variable apparently discrete it clearly shows lack of fit at the left and right ends

Discreteness (red arrows) and lack of fit (green ellipses) apparent in residual plot.
You can't properly assess heteroskedasticity with a test statistic that assumes that the model for the mean is correct ... when it plainly isn't. Further, the fact that the t-value is large is unsurprising, since the sample size is huge. [A large t-statistic isn't saying "the heteroskedasticity is dramatic", it's saying "the sample size is big, so the standard error is tiny". The impact on your inference is more related something like an effect size.
There may be hetero in that plot, but it's not terribly severe; there are more important issues to deal with first.
I'd suggest considering a gamma glm rather than fitting the logs with a linear model (presuming there are no exact zeros). Taking logs tends to make the discreteness in the low end perhaps "loom larger" than it would with a model on the original scale.
You should then work on the lack of fit problem, and then assess the degree of the hetero issue, but don't rely on a test statistic to assess the size/importance of it.


Category Theoretic Proof that $Lie(GL(n, \mathbb{C}))$ is isomorphic in the category of Lie Algebras to $\mathfrak{gl}(n,\mathbb{C})$

Question: Trying to follow the reasoning in Lee's Smooth Manifolds book that $Lie(GL(n, \mathbb{C}))$  is isomorphic in the category of Lie Algebras to $\mathfrak{gl}(n,\mathbb{C})$.
He ends up with the following commutative diagram
$\require{AMScd}$
\begin{CD}
Lie(GL(n, \mathbb{C})) @>{\cong}>> \mathfrak{gl}(n, \mathbb{C})\\
@V{\beta_*}VV @V{\alpha}VV\\
\beta_*(Lie(GL(2n, \mathbb{R}))) @>{\cong}>> \alpha(\mathfrak{gl}(n, \mathbb{C}))
\end{CD}
Where the maps $\beta_*$ and $\alpha$ are the standard injective lie algebra homorphism from $M(n, \mathbb{C}) \rightarrow  M(2n, \mathbb{R})$.
We have proven earlier that the bottom map is a Lie Algebra isomorphism and that the vertical maps are also Lie Algebra isomporphisms.
He then concludes that since the the top map is a vector space isomorphism, it is also a Lie Algebra isomorphism.
I must be missing something obvious, because I am not seeing how this follows. For one, we haven't even shown that it is a Lie Algebra homomorphism.
Comment: The map $\alpha$ is clearly an isomorphism, and hence we see that all of the spaces have the same dimension, so all the maps are bijective. Thus, the sought for isomorphism is just a matter of composing with the inverse of $\alpha$.
Comment: Thanks Tobias. The answer seems obvious in retrospect. I am pretty new to category theoretic reasoning, so your answer was helpful.
Answer: You've written the top map as a composite of three Lie algebra isomorphisms, so it's a Lie algebra isomorphism. Notice that this is not exactly an isomorphism between $GL(n\mathbb C)$ and $\mathfrak{gl}(n,\mathbb C)$, since the former is not in the category of Lie algebras. The application of the functor $Lie$ is doing something!
Comment: Corrected the error you mentioned. More explicitly, reworded to mention an isomorphism between $Lie(GL(n,C))$ and $\mathfrak{gl}(n, C)$.


What's the expected number of empty boxes if we place k distinguishable balls into n distinguishable boxes?

Question: Harvard Statistics 110: see #30, p. 30 of  pdf

Randomly, k distinguishable balls are placed into n distinguishable boxes, with all possibilities equally likely. Find the expected number of empty boxes.

I'm not convinced by the solution because, as illustrated by the picture of balls and boxes, there are $n^k$ different ways of filling the boxes by the balls, and there are $k$ different ways of one box being filled. One box can be filled by $1, 2, \dots k$ balls. Then, $P(I_j=0)=k/n^k$, and $P(I_j=1)=1-k/n^k$. But this will give weird results for $n=9, k=13$. I don't know but I feel there's something missing. May someone help?
Answer: The flaw in your reasoning is that there are many more than $k$ ways for a particular box to be filled.
Take the concrete example of $n=2$ boxes and $k=3$ balls. You are correct that there are $n^k=8$ different ways to fill the boxes. These $8$ ways can be enumerated by specifying the box where ball 1 lands, the box where ball 2 lands, and the box where ball 3 lands as a vector of three slots. The possibilities are: $$(1,1,1), (2,1,1), (1,2,1), (1,1,2), (2,2,1), (2,1,2), (1,2,2), (2,2,2).$$ Read $(1,1,1)$ as: "ball 1 lands in box 1, ball 2 lands in box 1, ball 3 lands in box 1". Let's focus on how box 1 can be filled or not filled. By inspection we see that there are $7$ ways for box 1 to be filled, not $3$, and in only one of these possibilities is box 1 empty.  Moreover, $1 = (2-1)^3=(n-1)^k$; that is, the only way box 1 can be empty is if each ball lands in a box other than 1, which means each slot in the $3$-vector can be filled only with one of  $n-1$ choices.
Answer: Consider there are k balls marked 1,2,3,4,.....k
and boxes marked as 1,2.....n
So to find the ways in which balls can be filled can be calculated as

When box 1 is filled with 1 ball. The no of ways in which this can happen is by choosing 1 ball out of k balls and then each remaining k-1 balls will have n-1 choices to go into n-1 boxes = $ \binom{k}{1}*(n-1)^{k-1}$
When box 1 is filled with 2 balls. The no of ways in which this can happen is by choosing 2 ball out of k balls and then each remaining  k-2 balls will have n-1 choices to go into n-1 boxes = $ \binom{k}{2}*(n-1)^{k-2}$
......... and so on.
till $ \binom{k}{k}*(n-1)^{k-k}$

Total no of ways to be filled = $\binom{k}{1}*(n-1)^{k-1} + \binom{k}{2}*(n-1)^{k-2} ..... + \binom{k}{k}*(n-1)^{k-k}$
$ = [\binom{k}{1}*(n-1)^{k-1} + \binom{k}{2}*(n-1)^{k-2} ..... + \binom{k}{k}*(n-1)^{k-k} + \binom{k}{0}*(n-1)^{k-0}] - \binom{k}{0}*(n-1)^{k-0}$
$ = (1+(n-1))^k - \binom{k}{0}*(n-1)^{k-0}$
$ = n^k - (n-1)^k$


Checking array item convert from jsonPath to JUnit hamcrest matcher

Question: Hardly trying to check that json has array with two items:
{
  "sections" : [
    {
      "name" : "A",
      "description" : "aaa"
    },
    {
      "name" : "B",
      "description" : "bbb"
    }
  ]
}

But only came with
.andExpect(jsonPath("$.sections[?(@.name=='A' && @.description=='aaa')]", hasSize(1)))

Any way to convert this to Harmcrest matchers with hasItem/hasProperty/containInAnyOrder ?
Answer: I think de-serializing the Json array to a list of Section objects will be easy to use Hamcrest Matchers. You have to override the equals() method in order to check whether Section object is available in the created Section list.
Section.java
public class Section {
    private String name;
    private String description;

    public Section(String name, String description) {
        this.name = name;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        if (obj.getClass() != this.getClass()) {
            return false;
        }

        final Section other = (Section) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }

        if (!this.description.equals(other.description)) {
            return false;
        }

        return true;
    }
}

Then use any Hamcrest Matcher you prefer.
RestAssured.baseURI="https://run.mocky.io/v3/bc929050-35ba-42a1-86b1-58f3fd1ead83";

List
 sections =  RestAssured.given()
        .when()
        .get()
        .then()
        .extract().jsonPath().getList("sections", Section.class);

Section sectionA = new Section("A", "aaa");
Section sectionB = new Section("B", "bbb");

List
 sectionList = new ArrayList<>();
sectionList.add(sectionA);
sectionList.add(sectionB);

assertThat(sections, hasItem(sectionA)); // pass
assertThat(sections, hasSize(2)); // pass
assertThat(sections, hasItem(hasProperty("name", equalTo("B")))); // pass
assertThat(sections, equalTo(sectionList)); // pass
assertThat(sections, containsInAnyOrder(sectionList.toArray())); // pass


An exercise about Lebesgue measure.

Question: let $\{E_{n}\}_{n\in\Bbb N}$ be a sequence of measurable subsets such that $E_n \subseteq (0,1)$and let $\limsup_{n\to\infty}  m(E_{n})=1$, prove that exists a subsequence {$E_{n_{k}}$} such that $m(\bigcap_{k=1}^{\infty} E_{n_{k}}) > 0$, where m is the measure of Lebesgue.
We are in a metric space so by the definition of limsup i know (thanks to Bolzano-Weierstrass theorem) that exists a subsequence $E_{n_{k}}$ such that $\lim_{k\to\infty}m(E_{n_{k}})=1$, that means that $\forall\epsilon>0, \exists h\in \Bbb N : \forall k>h,  1-\epsilon<m(E_{n_{k}})<1+\epsilon$.
I thought it was a good starting point but i don't know how to go on. Any ideas?
Answer: Let $\epsilon>0$ and choose $E_{n_k}$ such that $m E_{n_k} \ge 1-\frac{1}{2^k} \epsilon$.
Then we see that $m E_{n_k}^c \le \frac{1}{2^k} \epsilon$, and so
$m (\cup_k E_{n_k}^c) \le  \epsilon$. This means that $m (\cup_k E_{n_k}^c)^c \ge  1-\epsilon$, and since $(\cup_k E_{n_k}^c)^c = \cap_k E_{n_k}$, we can take any $\epsilon<1$ to get the desired result.

An exercise about Lebesgue measure.


Subscribe to REST API with retrofit

Question: I have a list of object that constantly changed at my local server, I need to get notified whenever this list is changed, can I use retrofit to do this?
I user firebase before, but now I'm working on local network using local wifi connection (not connected to internet)
Answer: You cannot use Retrofit for real-time database monitoring. Use Firebase Cloud Messaging (FCM) instead (e.g. send notification from server to device when some change occurs).
There are some other libraries like MQTT that you could use, but they all follow same procedure of sending messages from server to device.

Subscribe to REST API with retrofit


Postgresql Performance - Adjusting SHMMAX and SHMALL

Question: I've read just about everything there is online about improving postgres performance, but the "right" values for SHMMAX and SHMALL still elude me.
The consensus seems to be SHMMAX = total_memory/4 and SHMALL = total_memory/2 are safe starting values.
However, SHMALL can be measured in pages or bytes and I can't find any info about which is used on Ubuntu.
Does Ubuntu (or more generally Debian) use pages or bytes for SHMALL?
Answer: For all Linux systems which I used SHMALL is measured in pages and SHMMAX is measured in bytes. I think you may check your system using ipcs command, which always converts above parameters in KBytes while output, and compare it with sysctl values:
[aseryozhin@centos ~]$ ipcs -l

------ Shared Memory Limits --------
max number of segments = 4096               // SHMMNI
max seg size (kbytes) = 524288              // SHMMAX
max total shared memory (kbytes) = 8388608  // SHMALL
min seg size (bytes) = 1

[aseryozhin@centos ~]$ sysctl -e kernel.shmmax
kernel.shmmax = 536870912

[aseryozhin@centos ~]$ sysctl -e kernel.shmall
kernel.shmall = 2097152

[aseryozhin@centos ~]$ getconf PAGE_SIZE
4096

SHMMAX: 524288 * 1024 = 536870912
SHMALL: 8388608 * 1024 / 4096 = 2097152
Answer: These variables are measured in bytes as stated in the documentation. I think it is more important to look at the postgresql configuration parameters. You need to look at the SHMALL/SHMMAX values when needed. For example, if you want to increase the maximum number of connections, you may need to increase these limits.
Tuning the database server depends on your usage pattern such as the number of simultaneous connections and the database size. Increasing a config parameter is not always good.
Comment: SHMMAX need to be increased in order to increase shared_buffers which is the lowest hanging fruit when it comes to postgresql performance. Can you add a link to the documentation?
Comment: You can look at http://manpages.ubuntu.com/manpages/jaunty/man2/shmget.2.html


Can you play harmonics on a harp?

Question:

This video seems to suggest to me you can. What is the technique called and how is it played?
Comment: Video link is dead.
Answer: Yes.  There's a lesson on how to do it on YouTube.  For the right hand, place the back of finger 2 on the centre of the string.  Pluck with the thumb (finger 1), and immediately remove the whole hand to allow the string to vibrate.  For the left hand, the technique is a bit different - the palm of the hand blocks the string instead.
You end up with a note one octave up from normal, but with a distinctive sound.
If you're not sure where the centre of the string is, here's a trick I found.  Keep plucking the string with a finger of one hand, while gently sliding finger 2 on the other hand up and down the string.  Most of the time you get a dull thud, but at the exact centre, the string will start to ring.
Comment: There's no need to immediately remove anything. As the small section touched doesn't vibrate - a node, you can in fact touch at that point again, without stopping the string sounding. Move a millimetre either way and touch - sound's dead.
Comment: @Tim- that's true if the width of your finger touching the string is zero.  But because it isn't, the string will ring longer, as a rule, if you remove your finger after plucking.  Try it yourself.  The difference is especially noticeable on the higher strings.
Answer: Harmonics can be played on any stringed instrument. It involves touchng the string at a node. The simplest is the octave, which is exactly half way along the string. This gives a sound an octave above the open string, as it divides the string into two vibrating parts, which vibrate twice as fast as the original. Easy to do on guitar, as is the one third touch, making a sound one fifth above the original. Obviously, there are two nodes for this. If you want to do this on guitar, they're above the 7th and 19th fretwires.
Comment: @ToddWilcox - good point. I can only guess, that natural harmonics work, due to them being played using open strings, but artificial ones won't work. However, since all notes are available open natural ones will suffice. On guitar it's different, as there's only 6 strings, but each can be fretted, so artificial ones are simple to produce. On the violin family, natural ones are, I think , the only ones available.No doubt somebody will verify, or not.
Comment: To answer the practical question: yes, one can and does play harmonics on the harp.  I do.
Comment: It might be worth clarifying the difference between natural and artificial harmonics and then confirming whether or not it is possible to play artificial harmonics on a harp. I suspect it is not possible to play artificial harmonics, but I'm not at all experienced in playing a harp so there may be some technique that is not intuitive to me that would make it possible.
Comment: @Tim I think you meant the 12th - i.e. a fifth higher than the first harmonic -  when you touch at one third distance rather than the fifth.
Comment: @JimM - 12th fret= one octave higher. 7th fret = a fifth, like 19th fret.
Comment: @Tim  Sorry I was unclear.  I was not talking about frets.  I meant that touching at a third of the string length gives a pitch a 12th above the fundamental, rather than a fifth above it.
Comment: @JimM - o.k. so you're calling the interval that's a fifth above the octave a 12th, I suspect. Found above the 7th and 19th frets.
Comment: @Tim Yes.  Isn't that the standard term?
Comment: One could play artificial harmonics on a violin by fingering a note with one finger and using another to touch the intended node. The violin scale length is short enough for that. I'm not sure that's ever actually done but it is possible.
Comment: @JimM - yes, it is. It's just that intervals in chords don't feature 12ths. Plenty of 9ths, 11ths and 13ths!
Comment: @ToddWilcox - I suppose that would be possible, although violins are rich in harmonics, so a lot (but not all) could maybe be played as natural ones. Trouble is, they get out of tune after the fifth or sixth. Interesting idea, though!
Comment: @ToddWilcox There is quite a lot of use of 'artificial harmonics' in violin playing.  A good example is towards the end of Czardas by Vittorio Monti where the entire theme is played in that way.
Answer: Yes, harmonics are beautiful on the harp, and quite common.
The symbol in sheet music for a harmonic is a small circle placed above or below the note head, usually opposite the stem. There has been some variation in how the harmonics are noted, as the legendary Carlos Salzedo liked to write the harmonic in the octave where it will sounds rather than where it is played. However, most composers now put the harmonic note where it is played and it will sound one octave higher. If a composer wishes to use Salzedo's method it is customary to inscribe "Harmonics are written where they sound and played an octave lower" in the preface notes for the performer.
Learning to play harmonics well in both hands is a significant topic in harp lessons. The hand position for left hand harmonics is quite different from that of right, and there are stylistic differences for both hands among different teaching methods. Double and even triple harmonics can be played, depending on which notes are desired and which hand is playing them. Playing harmonics on different harps will require adjustment because there is so much variation in the physical dimensions of different brands and styles of harp.
Comment: If anyone's interested in the use of both octave and twelfth harmonics (on a six-stringed lyre, but the principle is the same as on the harp), check this out:  https://soundcloud.com/scott-wallace-189088488/slippages
Comment: I should point out that the harmonics In this recording are produced differently than the classical method- I pluck with one hand and stop the node with the other- but the physical basis of the sound is the same.

Can you play harmonics on a harp?


Finding (closed or approximated) forms of $S(t), I(t)$ and $R(t)$ in SIR Model

Question: I'm studying the SIR Model:

$$\left\{\begin{aligned}
&\frac{dS}{dt} = -\beta S(t)I(t)\\
&\frac{dI}{dt} = \beta S(t)I(t)-\gamma I(t)\\
&\frac{dR}{dt} = \gamma I(t)\\
\end{aligned}\right.$$

In particular, I am trying to deduce the exact equation for $S(t)$, $I(t)$ and $R(t)$. I have:
$$S(t)=S_0\cdot e^{\frac{R(t)-R_0}{\gamma}}$$
From the inegration of $$\frac{dS}{dR}=-\frac{S(t)}{\gamma}$$
Now, $S(t)$ is written still in terms of the function $R(t)$, so we want to find $R(t)$. In particular, we know that:
$$\frac{dR}{dt}=\beta\cdot I(t)=\beta\cdot(N-R(t)-S(t))$$
And, from what I have said:
$$\frac{dR}{dt}=\beta(N-R(t)-c_0\cdot e^{\frac{R(t)-*R_0}{\gamma}}$$
Here I am stuck and I don't know how to proceed. I think we have to use Taylor expansion of $e^{-x}$ in $I_{\delta}(0)$. Is it correct? Or we just have a trascendental equation, so we can't solve it?
Also, if we don't know about $S(t)$ or $R(t)$, how can we compute the number of infected or susceptible people at the end of the epidemic. In other words, how can we compute:
$$\lim_{t\rightarrow +\infty} S(t)$$ and $$\lim_{t\rightarrow +\infty} R(t)$$
Knowing only $I(S_{(t)})$ and $I(R_{(t)})$, how can do this? Here a graph of what I mean:

Thank you.
Comment: Exact closed forms for $S,I,R$ are not known.
Comment: [This paper](https://www.aimsciences.org/article/doi/10.3934/dcdsb.2016105) goes through the long time behavior of the SIR model. This is not a trivial problem.
Comment: @K.defaoite: yeah, I know. But can we derive approximate forms? And how can we compute those limits?
Comment: @K.defaoite: is there a free copy? I don't want to pay 30$ for that paper.
Comment: [This paper](https://arxiv.org/pdf/1403.2160) might help.
Answer: The problem is that there's a complicated integral no matter how you spin it. Using The first and third ODE's we can find $R(S)$
\begin{align}
\dot R&=-\frac{\gamma \dot S}{\beta S}\\
R&=-\frac{\gamma}{\beta}\ln\left(\frac{S}{S_0}\right)\ \ \ \ \ \  \text{(taking $R_0=0$).} \tag{*}
\end{align}
Then, using the chain rule and the first and second ODE's
\begin{align}
\frac{\mathrm dS}{\mathrm dt}=\frac{\mathrm dS}{\mathrm dI}\frac{\mathrm dI}{\mathrm dt}=I(\beta S-\gamma)\frac{\mathrm dS}{\mathrm dI},
\end{align}
so that
\begin{align}
\frac{\beta S-\gamma}{S}\frac{\mathrm dS}{\mathrm dI}+\beta=0\\
\beta (S-S_0)-\gamma\ln\left(\frac{S}{S_0}\right)+\beta(I-I_0)=0\\
I=N+\frac{\gamma}{\beta}\ln\left(\frac{S}{S_0}\right)-S.\tag{**}
\end{align}
So if you could get $S(t)$ you'd have all three unknown functions. Substituting $I(S)$ into your first ODE gives that
\begin{align}
\frac{\mathrm dS}{\mathrm dt}=S\left[\beta(S-N)-\gamma\ln\left(\frac{S}{S_0}\right)\right],\end{align}
and
\begin{align}
\int\frac{\mathrm dS}{S\left[S-\frac{\gamma}{\beta}\ln\left(\frac{S}{S_0}\right)-N\right]}=\beta t+c,
\end{align}
or in terms of $R$ instead, using equation (*),
\begin{align}
\int\frac{\mathrm dR}{R+S_0\text{exp}\left(-\frac{\beta R}{\gamma}\right)-N}=-\gamma t+c_2. \tag{$\dagger$}
\end{align}
there is no elementary solution to this integral, and in my meager ODE experience, if you reduce your ODE to an integral, there are no more tricks to be had to get around them.
You can use the Taylor series expansion of the integrand in equation ($\dagger$) to get an answer. Then the challenge becomes inverting the resultant power series (can't imagine you can do this analytically) to get $R(t)$, which you can substitute into equations (*) and (**) (finding $I(t)$ would involve the Lambert-W function) to get your solutions (numerically).
Edit
You need one functions limit to get the others. Thankfully you put that graph up, as I believe it's fair to say that $\lim_{t\rightarrow\infty}I(t)=0$.
Taking the limit as $t\rightarrow\infty$ of equation (**) gives
\begin{align}
\lim_{t\rightarrow\infty}I(t)=\lim_{t\rightarrow\infty}\left(N+\frac{\gamma}{\beta}\ln\left(\frac{S}{S_0}\right)-S.\right)\\
0=N+\frac{\gamma}{\beta}\ln\left(\frac{S_{\infty}}{S_0}\right)-S_\infty.
\end{align}
where I've denoted $\lim_{t\rightarrow\infty}S(t)=S_{\infty}$.
Solving for $S_\infty$ gives that
\begin{align}
\lim_{t\rightarrow\infty}S(t)=-\frac{\gamma}{\beta}W\left(-\frac{\beta}{\gamma}e^{\frac{\beta}{\gamma}(\ln S_0-N)}\right)
\end{align}
where $W(x)$ is the Lambert-W function, and assuming the argument is greater than $-1/e$, or put another way,
\begin{align}
S_0<\left(\frac{\gamma}{\beta}\right)^{\gamma/\beta}e^{N-\gamma/\beta}
\end{align}
which seems reasonable.
$\lim_{t\rightarrow\infty}R(t)$ can be found using equation (*),
\begin{align}
\lim_{t\rightarrow\infty}R(t)=-\frac{\gamma}{\beta}\ln\left(-\frac{\gamma}{S_0\beta}W\left(-\frac{\beta}{\gamma}e^{\frac{\beta}{\gamma}(\ln S_0-N)}\right)\right)
\end{align}
Hopefully assuming $\lim_{t\rightarrow\infty}I(t)=0$ wasn't false!
Comment: Thanks for your answer. if we know $I(S_{(t)})$ and $I(R_{(t)})$ can we derive the $\lim_{t\rightarrow +\infty} I(t)$ and $\lim_{t\rightarrow +\infty} R(t)$?
Comment: @Matteo see my edit!


Quesion about creation of subspace with some properties

Question: Let $V$ be a vector space with finite dimension and $K, H$ are subspaces of $V$. Prove that  there is subspace $M$ of $V$ s.t $M+K=M+H$ and $M\cap K=M\cap H=\{0\}$.
Comment: I think you need $\dim(K)=\dim(H)$ for this to be true. Indeed, if $M\cap H=\{0\}$, then $\dim(M+H)=\dim(M)+\dim(H)$, so that is a simple proof that if such an $M$ exists, then $\dim(K)=\dim(H)$.
Comment: it would be helpful if we know what your attempt was.
Comment: I am agree to @MarioCarneiro . Also pay attention with condition $dim(K)=dim(H)$ , it will be a question on Iran mathematical competition for University students in the helical year 1368, that you can find its answer in the book was written by "Mr. Bamdad YaHaghi" and also in Linear Algebra written by "Mr. Nikookar".
Answer: Assume (as was shown to be necessary) $\dim(H) = \dim(K)$.  Let $L = H \cap K$.
We can write $H = L \oplus N$ and $K = L \oplus P$ for some subspaces $N$ and $P$,
and $\dim N = \dim H - \dim L = \dim K - \dim L = \dim P$.  So there is a linear
map $T$ from $P$ onto $N$.  Let $M = (I+T) P = \{p + Tp: p \in P\}$.
To show $M \cap H = \{0\}$: if $h \in M \cap H$, we can write $h = p + Tp$ for some $p \in P$, but also $h = u + n$ for some $u \in L$ and $n \in N$.  Thus $n - Tp = p - u$.
But $n - Tp \in N \subseteq H$ while $p - u \in P + L = K$, and $H \cap K = L$ but $N \cap L = \{0\}$.  Thus $p - u = 0$.  But $p = u \in P \cap L = \{0\}$, so $p = 0$
and $h = 0 + T 0  = 0$.
The proof of $M \cap K = \{0\}$ is similar.
To show $M + K \subseteq M + H$: take any $y \in M + K = M + L + P$.  Then $y = p + T p + r + q$ where
$p \in P$, $r \in L$ and $q \in P$.  Now write this as
$y = (p + q) + T(p+q) - T q + r$.  We have $p+q \in P$ so $(p+q) + T(p+q) \in M$,
$-Tq \in N$ and so $-Tq + r \in N + L = H$, and thus $y \in M + H$.
But since $M \cap H = \{0\}$ and $M \cap K = \{0\}$, $\dim(M+H) = \dim M + \dim H
= \dim M + \dim K = \dim(M+K)$, so $M + K = M+H$.
Answer: Assume $\dim(H)=\dim(K)$. Let $\{e_1,\dots,e_a\}$ be a basis for $H\cap K$, and let $\{e_1,\dots,e_a,h_1,\dots,h_b\}$ and $\{e_1,\dots,e_a,k_1,\dots,k_b\}$ be bases for $H$ and $K$, respectively (where $a+b=\dim(H)=\dim(K)$). Then $h_i\notin K$, because if it was, then $h_i\in H\cap K$ implies $h_i$ is a linear combination of the $e_i$, so $\{e_1,\dots,e_a,h_1,\dots,h_b\}$ is not a linearly independent set. Similarly, $k_i\notin H$. Thus, let $M=\operatorname{span}(\{h_1+k_1,\dots,h_b+k_b\})$. If $x\in M\cap H-\{0\}$, then
$$x=A_1e_1+\dots+A_ae_a+B_1h_1+\dots+B_bh_b=C_1(h_1+k_1)+\dots+C_b(h_b+k_b)$$
$$A_1e_1+\dots+A_ae_a+(B_1-C_1)h_1+\dots+(B_b-C_b)h_b=C_1k_1+\dots+C_bk_b:=y$$
which expresses $y\in H\cap K=\{0\}$. Thus $C_i=0$, and so $x=0$, a contradiction. Thus $M\cap H=\{0\}$. Similarly, $M\cap K=\{0\}$. But if $x\in H+M$, then
$$\begin{align}
x&=A_1e_1+\dots+A_ae_a+B_1h_1+\dots+B_bh_b+C_1(h_1+k_1)+\dots+C_b(h_b+k_b) \\
&=A_1e_1+\dots+A_ae_a+(B_1-C_1)h_1+\dots+(B_b-C_b)h_b+C_1k_1+\dots+C_bk_b\in H+K,
\end{align}$$
so $H+M\subseteq H+K$. Conversely, if $x\in H+K$, then
$$\begin{align}
x&=A_1e_1+\dots+A_ae_a+B_1h_1+\dots+B_bh_b+C_1k_1+\dots+C_bk_b \\
&=A_1e_1+\dots+A_ae_a+(B_1-C_1)h_1+\dots+(B_b-C_b)h_b+C_1(h_1+k_1)+\dots+C_b(h_b+k_b)
\end{align}$$
so $H+M=H+K$. Similarly, $K+M=H+K$.
Note that I had to assume $\dim(H)=\dim(K)$ at the start. Conversely, if $M\cap H=\{0\}$ and $M+H=M+K$, then $\dim(M)+\dim(H)=\dim(M+H)=\dim(M+K)=\dim(M)+\dim(K)$, so $\dim(H)=\dim(K)$ is a necessary and sufficient condition for this construction to exist.
Answer: Not true.  Take $K = \{0\}$ and $H = V$.
Comment: Also $V\neq\{0\}$.


Can't remove company informations from stock.picking report QWEB

Question: Good morning, please help me, I'd like to remove all company informations from report but it occurs an error.
Here is my code:
<template id="empty_report" inherit_id="web.external_layout_standard">
    <xpath expr="//div[@class='header']" position="replace">

    </xpath>
    <xpath expr="//div/div/ul[@class='list-inline mb4']" position="replace">

    </xpath>
    <xpath expr="//div/div/div[@name='financial_infos']" position="replace">

    </xpath>
</template>

Here is the error:
Odoo Server Error

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py", line 1671, in report_download
    response = self.report_routes(reportname, docids=docids, converter=converter)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 519, in response_wrap
    response = f(*args, **kw)
  File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py", line 1612, in report_routes
    pdf = report.with_context(context).render_qweb_pdf(docids, data=data)[0]
  File "/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_actions_report.py", line 716, in render_qweb_pdf
    bodies, html_ids, header, footer, specific_paperformat_args = self.with_context(context)._prepare_html(html)
  File "/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_actions_report.py", line 346, in _prepare_html
    body_parent = root.xpath('//main')[0]
IndexError: list index out of range

But it work perfectly when I access to PDF from this url:
http://localhost:8069/report/pdf/stock.report_deliveryslip/1
But it dosn't work when I try to access from Print button and give me the error above.
Thank you for helping!
Regards
Answer: If you don't want to use the company information on the report header/footer than simply used with
        web.basic_layout instead of
        web.external_layout_standard
or you can do with by your own customer header/footer. As with your code, it will be the effect on another link report too.


Sum by year and total_vehicles pandas dataframe

Question: I have the following dataframe lrdata3 and I would like to sum the total_vehicles for every year instead of having multiple separate for the same year.

year total_vehicles
0 2000 2016
1 2000 1483
2 2000 1275
3 2000 1086
4 2000 816

When I do this
lrdata3.groupby('year')['total_vehicles'].sum()

I get this which is not even a dataframe

year
2000    419587299
2001    425832533
2002    430480581
2003    434270003
2004    442680113
2005    443366960
2006    452086899
2007    452280161
2008    445462026
2009    443333980
2010    438827716
2011    440461505
2012    440073277
2013    441751395
2014    451394270
2015    460050397
2016    470256985
2017    474693803
2018    473765568

Any help please?
Thanks
Comment: Your implementation seems fine to me. If the sum per year according to you is correct, you can do `df=df.reset_index()` to make it into a dataframe
Answer: You can do it in one line and get a df with this syntax.
Some sample data:
year    total_vehicles
0   2000    2016
1   2000    1483
2   2000    1275
3   2000    1086
4   2000    816
5   2001    2016
6   2001    1483
7   2001    1275
8   2002    1086
9   2002    816

df = pd.read_clipboard()

gb = df.groupby('year').agg({'total_vehicles': 'sum'})

print(gb)

    total_vehicles
year
2000    6676
2001    4774
2002    1902

print(type(gb))

<class 'pandas.core.frame.DataFrame'>

Answer: lrdata3.groupby('year')['total_vehicles'].sum().to_frame()

or groupby and transform
lrdata3['yearlytotal_vehicles']=lrdata3.groupby('year')['total_vehicles'].transform('sum')

Answer: Your code is fine, just add a .reset_index() to it. Like this:
lrdata3.groupby('year')['total_vehicles'].sum().reset_index()

This will get you what you want.


how to read and play a turn in music when it is inbetween 2 notes?

Question: for example in this Mozart piece, there is a turn in bar 7, and in bar 10

how are you suppose to play these turns rhythmically? how else could the notes be notated?
Comment: I voted to reopen, because the dup question is about a turn between _the same two pitches_, but this turn is between _two different pitches_. I assume the turn will be pitches above and below the second, target pitch, the `A`. But, that isn't completely clear. I think an answer making that clear would be helpful for the community.
Comment: @MichaelCurtis Actually I would assume the opposite, "F E D# E"
Answer: The difference between writing it above a note and after (between) the note is that in the "after" case, the principal note is played first. There is leeway in the exact execution, but two possibilities are notated below.

In the first, the principal note and the note above form a dotted rhythm on the first half of the beat with a triplet forming the second half. Alternatively, the first half of the beat can be the principal note and the second half containing the entire turn.
Another possibility, not notated, is to divide the beat into three parts: 1) the principal note, 2) a triplet of the upper neighbor, principal, and lower neighbor, and 3) the principal note.
In measure 10, Demus uses the second option, above. The principle note takes up half the time allotted to it, then the turn takes up the other half. The is typical.


ffmpeg: need for speed

Question: I am using ffmpeg to convert a set of images (bmps) with an audio track into Web ready video. Target formats are h.264 mp4, webm and flv.
This is on a Windows Azure extra-large instance (8 proc) using the prebuilt zeranoe static builds ( http://ffmpeg.zeranoe.com/builds/).
Suppose I'm willing to sacrifice quality and size for raw speed. What options for each format will yield the quickest result?
My "baseline" command looks like this (swap the extension for the other formats):
ffmpeg -y -i frames%5d.bmp -i audio.mp3 -r 23.97 out.mp4

I can change the inputs to other formats if needed (jpg images, aac audio, etc).
Comment: This is more general FFMPEG question, than Azure question. One hint though, use the 32bit ffmpeg executable. I was having issues with the 64bit one and found out that the 32bit works perfactly and stable.
Comment: Have you looked at the Media Services? THese won't give you raw throughput on a single request, but will allow some fairly large scaleout of jobs.
Comment: @bdcm I'm building a custom video per user. I need individual requests to be hella fast
Comment: @astaykov I see no perf difference between 64 and 32 bit, but thanks for the suggestion.
Comment: @roufamatic I had no perf, but stability/codecs issues using the 64bit version, random errors, unrecognized codecs, once convert clearly, once fail, etc.
Answer: The major "knob" you change the quality/encoding speed balance for any format is the bitrate.  In testing just now, a video that takes 97 seconds to encode with default settings, bitrate ~900k, took less than half that with the bitrate dialed down to 100k.  The output video was much smaller, and the quality was noticeably worse.
In your case, coming from images, you can probably get a major speedup from turning off motion estimation as mentioned in FFmpeg's encoding tips:

If your computer is not fast enough, you can speed up the compression at the expense of the compression ratio. You can use '-me zero' to speed up motion estimation, and '-g 0' to disable motion estimation completely (you have only I-frames, which means it is about as good as JPEG compression). [Note that more recent versions of FFmpeg use -me_method in place of -me.]

In testing, the 97-second encode finished in 20 seconds with -g 0.  There was much less compression, 63% the original size versus 25% with default settings, but the quality remains good unlike low-bitrate encodings.
Here are the complete results from my quick testing, time is real time used for encoding:
Baseline, 27M MOV to mp4, bitrate ~900k: 97s
with -me_method zero: 84s
with -flags2 fast: 84s
with -b 500k: 75s
with -b 100k: 43s
with -g 0: 20s
with -flags2 fast and -b 100k and -g 0: 12s (the output looks terrible)
There might be other format-specific tweaks, but I wouldn't expect significant speedups from those compared to the methods listed above..
Answer: What is the resolution of these images? Using as low as a resolution as possible will give you better performance. Also use the -threads option in ffmpeg to use the 8 cores optimally.
Comment: I can't control the resolution (760x442). Ffmpeg adds in -threads 0 by default, causing it to use 12 threads on an 8 proc box. I actually saved a second of rendering time by using -threads 8. It's a start!

ffmpeg: need for speed