Troca ponteiros lista encadeada - python

Question: Criei uma função pra trocar os ponteiros de uma lista encadeada, a ideia é bem simples, troco eles e atualizo o próximo elemento pra ele não perder a referência, só que a função tá perdendo a referência, p.ex., testei uma lista l = 1, 2, 3, 4, 5, 6, e quero trocar o 2 e o 4 de posição, ele me retorna l = 1, 2, 5, 6, quando deveria ser l = 1, 4, 3, 2, 5, 6. Não sei mais o que fazer, testei várias alternativas e nada, segue o código:
def troca_teste(L):
        p = L.head
        aux = p
        while p:
            if p.element == 2:
                q = p.next
                while q:
                    if q.element == 4:
                        #swap dos ponteiros
                        aux = q
                        q = p
                        q.next = aux.next
                        aux.next = p.next
                        p = aux
                        p.next = aux.next
                        break
                    q = q.next
            p = p.next

Definição das classes:
class LinkList:

    class Node:

        def __init__ (self, element = None, next = None):
            self.element = element
            self.next = next

    def __init__ (self):
        self.head = None
        self.size = 0

Comment: Como você definiu a classe de lista? E como você definiu a classe de elemento da lista?
Comment: Você disse que quer trocar algumas coisas de posição, mas não definiu no texto da pergunta o que o 2 ou o 4 tem de especial, assim sendo fica complicado tentar dar uma resposta que realmente sane sua dúvida. Eu particularmente fiquei confuso com o código dado seu texto de pergunta
Comment: A ideia é trocar dois elementos de uma lista, adjacentes ou não, no caso, como estou apenas testando as trocas, usei uma lista l = 1, 2, 3, 4, 5, 6, minha ideia é trocar o dois e o quatro de posição
Comment: Então o resultado esperado seria `1,4,3,2,5,6`?
Comment: Sim, fiz alterações no texto pra melhor compreensão
Comment: Você deseja trocar sempre esses elementos ou os elementos da segunda e quarta posição? Por exemplo, se for troca da segunda e quarta posição, `troca_teste(l); troca_teste(l)` retornaria a lista para seu estado original
Comment: É qualquer posição, como escrevi adjacentes ou não, esse código que postei é apenas um esboço, minha ideia pra esse código é utilizar ele pra usar em algoritmos de ordenação
Comment: Ok, você deseja fazer a operação `swap`. O ideal seria passar a lista e os dois índices. Vou tentar elaborar uma resposta
Answer: Você deseja fazer uma operação de swap. O swap é uma operação que, dado um conjunto indexável e dois índices, troca de posição os elementos demorados por esses índices.
Preliminares
Chamemos a lista indexável de l. Para o seu caso, l é uma instância de LinkList.
Devido à definição de LinkList, l não está indexado. Para fazer acessos indexados, a ideia é mais ou menos a seguinte:
def acesso_nodo(l, idx):
    # se o índice for além do que está armazenado, retorna nenhum nó
    if l.size <= idx < 0:
      return None
    atual = l.head
    while idx > 0:
        atual, idx = atua.next, idx - 1
    return atual

Note que essa função vai retornar o nó (instância de Node, não o elemento dentro do nó, e isso é proposital). Assim sendo, podemos dizer que, através de um índice, obtemos o nó associado. Agora podemos tratar l como um conjunto indexado, já que transformamos sua capacidade de ser indexado em fato (antes de acesso_nodo, instâncias de LinkList eram passíveis de sofrerem indexação, portanto indexáveis; depois dessa função, transformamos essa capacidade em realidade, daí agora podemos chamar LinkList de indexado).
Fazendo a troca, mantendo estrutura
Como estamos fazendo uma operação de troca, a estrutura topológica da lista. Assim, ao obtermos os nós que apontam para os elementos de índice k e j (doravante denominados nodo_k e nodo_j), precisamos fazer apenas:
nodo_k.element, nodo_j.element = nodo_j.element, nodo_k.element

Então, fica aberto apenas identificar nodo_j e nodo_k. Sobre a função descrita na seção anterior, podemos fazer a seguinte função (relativamente não eficiente):
def swap_toplologico_1(l, j, k):
    nodo_j = acesso_nodo(l, j)
    nodo_k = acesso_nodo(l,k)
    if nodo_j != None and nodo_k != None:
        nodo_k.element, nodo_j.element = nodo_j.element, nodo_k.element
    return l

Note aqui que, para navegar até o maior índice, é necessário passar pelo menor índice. Em cima disso, podemos fazer uma otimização e diminuir o acesso a referência em pelo menos o(min(j,k)):
def swap_toplologico_2(l, j, k):
    (m, M) = (j, k) if j < k else (k, j)
    if M >= l.size or m == M or m < 0:
        return l
    atual = l.head
    while M >= 0:
        if m == 0:
            nodo_m = atual
        if M == 0:
            nodo_M = atual
        atual, m, M = atual.next, m - 1, M - 1
    nodo_m.element, nodo_M.element = nodo_M.element, nodo_m.element
    return l

Aqui, a ideia foi fazer a mesma iteração feita em acesso_nodo só que voltada para o maior elemento do índice passado, aproveitando quando se passa no menor índice para guardar seu valor. Note que, no laço, há condições para detectar quando se encontra o índice desejado e guardar nas variáveis nodo_m e nodo_M.
Para ter menos questões de ajustes condicionais, coloquei que m será o menor dos índices j e k, e M para ser o maior. Então, se j for o menor, então nodo_j é equivalente ao nodo_m; caso contrário, de j ser o maior elemento, então nodo_M que equivale a nodo_j. nodo_k fica com o outro nó em ambos os casos.
Também aproveitei e pus uma pequena tratativa para não precisar realizar nenhuma ação quando o índice passado para realizar a troca for o mesmo (ie, j == k), pois trivialmente fazer essa troca tem o mesmo efeito de não fazê-la.
Troca topológica
A outra alternativa é fazendo a troca da estrutura propriamente dita. Os nós fisicamente mudam de estrutura. Como a lista é simplesmente encadeada, não é possível acessar o elemento anterior a partir do atual. Então, precisamos obter o elemento anterior aos dos índices passados para se fazer essa troca.
Assim como na troca mantendo a topologia, é possível escrever um código mais eficiente, mas aqui vou focar mais na lógica do que na performance. Fique a vontade para fazer a versão mais eficiente.
Para acessar os elementos anteriores a j e k, precisamos acessar os elementos j-1 e k-1. Também é bom garantir que o maior elemento é um elemento válido. Outro ponto de atenção é que 0 é um caso especial, onde se faz necessário alterar l.head.
Para tratar de maneira mais simplificada quem é o maior e quem é o menor elemento, usarei a mesma lógica de m,M da função swap_topologico_2. Então verifico apenas se m é zero.
 def swap_trocando_estrutura(l, j, k):
     (m, M) = (j, k) if j < k else (k, j)
    if M >= l.size or m == M or m < 0:
        return l
    prev_M = acesso_nodo(l, M - 1)
    # tratar primeiro o caso de m ser 0
    if m == 0:
        next_head = l.head.next
        next_M = prev_M.next.next

        # trocando as referências dos elementos seguintes
        prev_M.next.next = next_head
        l.head.next = next_M

        # trocando as referências dos elementos desejados
        l.head, prev_M.next = prev_M.next, l.head
        return l
    else:
        prev_m = acesso_nodo(l, m - 1)

        next_m = prev_m.next.next
        next_M = prev_M.next.next

        # trocando as referências dos elementos seguintes
        prev_m.next.next = next_M
        prev_M.next.next = next_m

        # trocando as referências dos elementos desejados
        prev_m.next, prev_M.next = prev_M.next, prev_m.next
        return l

Note que foi necessário trocar os elementos de nodo_m.next e nodo_M.next de tal modo que fosse possível remover nodo_m e nodo_M de seus lugares atuais e manter a coerência da lista.

Leitura recomendada

Inverter Lista Simples
Como ordenar uma lista encadeada em ordem alfabética?
Qual a melhor implementação do 'Algoritmo MergeSort'?
Stackoverflow em quick sort
Na prática, qual a utilidade dos ponteiros em C?
Comentário distinguindo ponteiro e referência


Derivation of a function missing one step in Nandi & Aich, 1994

Question: In Nandi and Aich, (1994) Sankhya, vol. 56, p. 129-136 (accessible here), there is a density function derived. However, there is one step where I cannot figure out how it was obtained. On bottom of p. 131, the authors go from (reported as in the paper):
$$
g(t') = \frac{1}{\sqrt{2 \pi}}
  \sum_{i=0}^\infty \frac{
    q_i ((1+\rho)\sigma^2)^{-(m+i-1)}
  }{
    2^{m+i-1} \Gamma(m+i-1)} \cdot
  \int_0^\infty \exp\left(-\frac{1}{2}\left((t'\sqrt{z} - \delta)^2+ \frac{z}{(1+\rho)\sigma^2} \right) \right) z^{m+i-3/2} \; \mathrm{d}\,z
$$
(which is checked to be ok) to this expression
$$
= \exp\left(-\frac{\delta^2}{2}\right) \sqrt{\frac{(1+\rho)\sigma^2}{\pi}}
\sum_{i=0}^\infty \sum_{j=0}^\infty \frac{q_i}{\Gamma(m+i-1)} \;
\frac{(\sqrt{2} \delta t')^j}{j!} \cdot
\frac{
((1+\rho)\sigma^2)^{j/2} \Gamma(m+i+(j-1)/2)
}{
(1+(1+\rho)\sigma^2 t'^2)^{m+i+(j-1)/2}
}
$$
for $-\infty<t'<\infty$. The parameters $\delta$, $\sigma$, $\rho$ and $z$ are all real numbers, with $\sigma > 0$, $z>0$, $-1\le \rho \le 1$. $m$ is an integer greater than 2.
Can you help filling the gap? Also, there might be an error in the second equation because when I evaluate both functions with the same values for the various variables ($m$, $z$, $\delta$, $\rho$, $\sigma$, $t'$), I get two different results...
Note. In case this is relevant, here is the definition of $q_i$ (and $\sum_{i=0}^\infty q_i = 1$):
$$\dbinom{-(m-1)/2}{i} \left(\frac{2\rho}{1-\rho}\right)^i \left(\frac{1+\rho}{1-\rho}\right)^{(m-1)/2} $$
Answer: This must be an application of $$\int_0^\infty z^{a-1}e^{b\sqrt{z}-cz}\,dz=\sum_{j=0}^\infty\frac{b^j}{j!}\frac{\Gamma(a+j/2)}{c^{a+j/2}}\qquad(a,c>0)$$ (shown using the power series of $e^{b\sqrt{z}}$ and termwise integration).
Comment: Thanks! I did not know this relation.


Folland Real Analysis 7 exercise 12 (b)

Question: There question is from Folland Real Analysis Chapter 7 Exercise 12. Let $X=\mathbb{R}\times\mathbb{R}_{d}$,where $\mathbb{R}_{d}$ denotes $\mathbb{R}$ with the discrete topology. If $f$ is a function on $X$, let $f^{y}=f(x,y)$; and if $E\subset X$, let $E^{y}=\{x:(x,y)\in E\}$.
(b) Define a positive functional on $C_{c}(X)$ by $I(f)=\sum_{y\in R}\int f(x,y)dx$ and let $\mu$ be the associated Radon Measure on $X$. Then $\mu(E)=\infty$ for any $E$ such that $E^{y}\neq\emptyset$ for uncountable any $y$.
I think $E$ is not compact here, but I do not know it is open or closed. Or this is not important. Also, I do not know how to use $I(f)=\sum_{y\in R}\int f(x,y)dx=\int fd\mu$. By the way, $\int f(x,y)dx$ means Lebesgue Measure?
Comment: First note that unaccountably many non-zero numbers will accumulate at some number different from zero. Adding numbers that accumulate to something other than zero, necessarily diverges.
Comment: Sorry! I fail to understand you
Answer: Let $E$ be a Borel set such that $E^y \ne \emptyset$ for $y\in A$, where $A$ is an uncountable subset of $\mathbb R$. By the outer regularity of $\mu$, it suffices to show that any open set containing $E$ has infinite measure.
Let $U$ be an open set containing $E$. There is $V \subseteq U$ such that $V^y = (a_y, b_y)$ with $a_y < b_y$ for $y \in A$.
Define $f : X \rightarrow \mathbb R$ so that $f^y \in C_c(\mathbb R, [0,1])$ and $\emptyset \ne \mathrm{supp}(f^y)\subseteq (a_y,b_y)$ for $y \in A$. Then $\int f(x,y)\, dx > 0$ for $y \in A$, which implies $\sum_{y\in \mathbb R} \int f(x,y)\, dx = \infty$.
Fix $M > 0$. By above, there is a finite set $F\subseteq \mathbb R$ such that $\sum_{y\in F} \int f(x,y)\, dx > M$.
Let $V_0 := V \cap (\mathbb R \times F)$ and $f_0 := \left.f\right|_{V_0}$.
By the Folland Ch 7 Exercise 12 (a), $f_0 \in C_c(X)$, and so
\begin{equation}
\mu(V_0) = \int \chi_{V_0}\, d\mu \geq \int f_0 \, d\mu = I(f_0) = \sum_{y\in \mathbb R} \int f_0(x,y)\, dx = \sum_{y\in F} \int f(x,y)\, dx > M
\end{equation}
Therefore, $\mu(U) > M$ for any $M>0$, which implies $\mu(U) = \infty$.
Comment: How do we know that $\sum_{y\in F}\int f(x,y)\,dx>M$?
Comment: @mio It follows from $\sum_{y \in \mathbb R} \int f(x, y)\, dx = \infty$.
Comment: But why is $F$ finite rather than countable?
Comment: @mio By definition, $\sum_{y \in \mathbb R} \int f(x, y)\,dx = \sup\{ \sum_{y \in F} \int f(x, y)\,dx : F\subseteq \mathbb R, F \text{ finite}\}$ (For reference, see Folland pg 11)
Comment: Oh I am really appreciated!
Answer: Note that $\mu(E)=I(\chi_E)=\sum_{y\in \mathbb R}m(E^y)$ and the sum can converge only if $S=\{y:E^y\neq \emptyset  \}$ is countable. That is, if  $S$ is uncountable, then the series (of positive terms) diverges to $\infty.$
Comment: Can we define $\chi_{E}$ on $C_{c}(X)$? I think $E$ is not compact?

Folland Real Analysis 7 exercise 12 (b)


Getting Link Title Using BeautifulSoup

Question: I am trying to parse the title of links using BeautifulSoup. I have tried various things but just can't get it to work.
The html is behind a login so here's a screenshot:

And here's my latest attempt which I was sure would work but just returns "None".
from bs4 import BeautifulSoup

soup = BeautifulSoup(driver.page_source, 'html.parser')
links = soup.find_all('ul', class_='nav list-group')
print(links)

for link in links:
    title = link.get('title')
    print(title)

Can anyone see what I am doing wrong?
Answer: This line of code:
links = soup.find_all('ul', class_='nav list-group')

Is not extracting the links, it's extracting the
 tags. Instead, you could try extracting the links with something like:
links = soup.find_all('a', class_='odds')

Then you will be able to loop over them and extract your titles:
for link in links:
   print(link['title'])

Answer: What happens?
You are selecting the
 not its  so you wont get any href value.
How to fix?
Select more specific e.g. with these css selector that will find all   that has an title attribute, in your
:
links = soup.select('ul.nav.list-group a[title]')

Example
Note: Your question needs some improvement, so you should provide specific part of driver.page_source as text and not as image - Took your code, so it is just a hint.
from bs4 import BeautifulSoup

soup = BeautifulSoup(driver.page_source, 'html.parser')

for link in soup.select('ul.nav.list-group a[title]'):
    title = link.get('title')
    print(title)

Getting Link Title Using BeautifulSoup


Is the Kernel a Maximal Ideal?

Question: In this MSE post, Artur Araujo gives an alternative proof that the preimage of a maximal ideal under a surjection is a maximal ideal:

If I may suggest, a cleaner way of proving this is by an altogether different method, bypassing elements. Since $M$ is maximal, $k:=S/M$ is a field. Since $f$ is surjective, its composition with the canonical projection $\bar{f}:R\to k$ is a surjection. This means that $\ker \bar{f}$ is a maximal ideal. Can you compute it?

I am being dumb, so I don't see how $\ker \overline{f}$ is a maximal ideal in $R$. Here is a comment I left on Artur Araujo's post:

Okay. Let $f:R→F$ be a surjective ring homomorphism, where $R$ is some (commutative?) ring and $F$ is a field. But suppose that $\ker f$ is not maximal. Then there exists an ideal $I$ in $R$ such that $\ker f \subset I \subset R$ and therefore $\{0\} \subseteq f(I) \subseteq S$. This would be a contradiction if images generally preserved strict inclusions, but I believe this is only true of injective maps. So I don't see why $\ker f$ has to be maximal in $R$.

What's going on? For instance, if $f(x) = x^2$ over the reals, then $(-1,0] \subset (-1,1)$ but $f((-1,0]) = [0,1) = f((-1,1))$, which is equality, not strict inclusion. Do images preserve strict set inclusion in this case?
Answer: In a commutative ring $R$, an ideal $I$ is maximal iff $R/I$ is a field.  Since $\overline{f}: R \to k$ is surjective, then $R/\ker(\overline{f}) \cong k$ by the First Isomorphism Theorem.
Answer:
I don't see how $\ker \overline{f}$ is a maximal ideal in $R$.

It is maximal since $R/\ker(\overline f)$ is isomorphic to a simple ring. A simple ring only has trivial ideals, so the quotient only has two ideals.

but I believe this is only true of injective map

The map between $R/\ker(\overline f)$ and it's range is injective — it's an isomorphism.  And consequently, the ideals are in correspondence , and the correspondence even respects inclusion.
$f(x)=x^2$ is not a ring homomorphism, and I'm not even sure you're considering any ring structure at all on the function's domain you chose.  At any rate, I don't think you need to pursue that line of thought. If you invest a bit of thought in the answer you are referencing you'll have a clear answer.

Is the Kernel a Maximal Ideal?


Convergence of a Sequence of functions Uniformly Mean Pointwise

Question: For each of the following, give an example of a sequence of functions $f_n(x)$ that converges to f
A. uniformly but not in the mean square sense.
B. in the mean square sense but pointwise nowhere.
I know that for part A the domain of the function cannot be bounded.
Please don't just repeat the definition of what it means to converge uniformly, in the mean square sense or pointwise.  I'm looking for clues on how to choose a $f_n(x)$ that matches the conditions
Answer: For each you need to choose functions that are small in one sense but large in the other.  So think step functions.  For a step function to be of fixed size in the square sense but nowhere point-wise you need it broad and low.  For a step function to be fixed in the pointwise sense but small in the square sense you need it fixed height but narrow.
So the answer to A can be done with a sequence of wide and low boxes.
The answer to B can be done with a sequence of boxes of height 1 but skinnier and skinnier - however managing to cover every point an infinite number of times.
Comment: I'm a bit confused by what you mean by boxes, you talk about step function but I don't see how the two connect


Book recommendation: Sobolev spaces.

Question: I have already read the standard part in Evan's PDE text book. However, in his book, the theorems like Sobolev embeddings only involve bounded domain, and it talks just a little about fractional Sobolev spaces. I want to look at a book that is deeper than this. I know the book written by Adams is a standard book, but this book is much more than what I need right now.
Can someone recommend me a book for Sobolev space that is readable? Thanks in advance.
Comment: Are there specific types of Sobolev spaces you want to use? You could look for them in Adams' book and read only that part. Stein's book Singular Integrals and Differentiability Properties of Functions also discusses many types.
Comment: Adams and Fournier is the classical reference for general results on Sobolev spaces.
Comment: There's the books "A first course in Sobolev Spaces" and "A first course in fractional Sobolev spaces" by Giovanni Leoni
Answer: G. Folland's TATA lectures on PDE give a terrific quick-intro to Sobolev spaces on $\mathbb R^n$, via Fourier transforms. That was what finally convinced me that the idea was useful. :) The possibility of using Fourier transforms "globally" is a great simplifier.
It is also possible to do "global" Sobolev theory on (products of) circles, via Fourier series. Obviously, this will be even simpler than the Fourier transform scenario.

Book recommendation: Sobolev spaces.


Lilypond - apply a repeating rhythmic pattern to all notes

Question: Assuming I have a pattern like this:
\relative c' {
  c4 d e f8 g
  d4 e f g8 a
  e4 f g a8 b
  f4 g a b8 c
}

How can a define the rhythmic pattern to be applied to all notes so I only had to input the note durations one time?
% I imagine it to look somehow like this:

definerhytmicpattern = {
  4 4 4 8 8
}

\relative c' {
  c d e f g
  d e f g a
  e f g a b
  f g a b c
}

Answer: I could not leave it and I found this on the Lilypond Snippet Repository.
Download the newest file with wget:
wget http://gillesth.free.fr/Lilypond/changePitch/changePitch.ly

then:
\version "2.18.2"

\include "changePitch.ly"

pattern = { c4 c4 c4 c8 c8 }
newnotes = \relative c' {
  c d e f g
  d e f g a
  e f g a b
  f g a b c
}

\score {
  \changePitch \pattern \newnotes
}

outputs:

you can also add articulation:
[...]
pattern = { c4-> c4-. c4-. c8( c8) }
[...]

and dynamics:
[...]
pattern = { c4-\p c4\< c4 c8( c8)-\! }
[...]

...and even fingerings! (just awesome)
[...]
pattern = { c4-1 c4-2 c-3 c8(-4 c8)-5 }
[...]

detailed documentation for this function can be found here: PDF


Conditional expectation, indication function

Question: I am given that $X,Y$ are independent Bernoulli RVs with parameter $p\in (0,1)$. I am also told $Z=1_{(X+Y=0)}$. I am asked to find $E[X\mid Z]$ and $E[Y\mid Z]$.
I can see that the expected values are going to be equivalent, but I'm not quite sure how to compute these expectations. Could someone give me a hint?
Thanks.
Harry
Comment: Hint: X and Z are $______$.
Answer: This is interesting. Can one show that,
$$
\begin{align*}
\mathbb{E}[X+Y\vert 1_{\{X+Y=0\}}] &= \frac{\mathbb{E}[(X+Y)1_{\{X+Y=0\}}]}{\mathbb{P}[X+Y=0]} \\
&= \frac{0}{(1-p)^2} \\
&= 0
\end{align*}
$$
It does not seem like $X$ and $1_{\{X+Y=0\}}$ can be independent since if the indicator is unity, we know $X$ is 0. I'm asking not stating. :)
Answer: So we are calculating
$$
E[X \mid Z] = \sum_x xP(X=x \mid Z=z)
$$
For the Bernoulli variable this will be just
$$
\begin{align}
E[X \mid Z] &= 1 \cdot P(X=1 \mid Z=z) + 0 \cdot  P(X=0 \mid Z=z)\\
 &=P(X=1 \mid Z=z)
\end{align}
$$
If $Z=1$ then clearly both $X$ and $Z$ are zero, so $P(X=1 \mid Z=1)=0$. In the other case we have
$$
\begin{align}
P(X=1 \mid Z=0) &= \frac{ P(X=1, Z=0)}{P(Z=0)}\\
 &=\frac{P(X=1 \cap  (X=1 \cup Y=1))}{P(X=1 \cup Y=1)}
 \\
&=\frac{P(X=1)}{1-P(X=0 \cap Y=0)}\\
&=\frac{p}{1-(1-p)^2}\\
&=\frac{1}{2-p}
\end{align}
$$
So final answer is
$$ E[Y \mid Z]=E[X \mid Z] = \left\{
  \begin{array}{ll}   0  & \mbox{for } Z=1 \\ \frac{1}{2-p}
 & \mbox{for } Z=0  \end{array} \right. $$


Convolution operator is compact over $L^2[0,2\pi]$

Question: Let $h:\mathbb R\longrightarrow \mathbb C$ a $2\pi$-periodic and locally integrable. Then we define the operator \begin{eqnarray}T_h: L^2[0,2\pi]\longrightarrow L^2[0,2\pi] \\ T_hf=f*h
\end{eqnarray}
I've already prove that is well-defined, bouded and linear. But I can't prove that
it is also a compact operator. I'm stuck at this point. I've tried to simplify the problem and considered h an indicator function. Also I took a bounded sequence in $L^2[0,2\pi]$ and tried to prove that its image under $T_h$ has a convergent subsequence.
Any advice is welcome!
Answer: Two hints: (i) Trigonometric polynomials are dense in $L^1(\mathbb T)$. (ii) If each $T_n$ has finite rank and $||T_n-T||\to0$ then $T$ is compact.


Disable a button if at least one input field is empty using ngDisabled

Question: I'd like to prevent the user from clicking the button "Register" if the fields are not correct. Part of that is that certain fields must be filled. But the condition is starting to get a bit long:
<button class="btn btn-success" ng-click="register()"
    ng-disabled="signInForm.$invalid || form.firstName.length==0 ||
    form.lastName.length==0 || form.email.length==0 ||
    form.password.length==0 || form.passwordBis.length==0">Register</button>

How can I simplify that?
Comment: You just need to provide `required` attribute for all your inputs and do `<button class="btn btn-success" ng-click="register()"
    ng-disabled="signInForm.$invalid>Register`
Answer: I think what you need is to provide required attribute for your input fields inside your form, so until the fields are filled in the form signInForm will be invalid. Similarly you could provide other validation attributes on the inputs as well.
Example:-
  <input type="text" ng-model="firstName" name="firstName" required />
  <input type="text" ng-model="lastName" name="lastName" required />
  <input type="email" ng-model="email" name="email" required />
  ...
  ...
  <button class="btn btn-success" ng-click="register()"
            ng-disabled="signInForm.$invalid">Register</button>

Comment: Looks like you're right : http://jsfiddle.net/mgmp6L0b/ But in my case it doesn't work... Looks like I'm not using the same framework... I have AngularJS v1.2.25, and the email : "toto@to" is valid in my code and not in the JSFiddle example above. Also required in my code doesn't change the behavior... Any thought ?
Comment: I cant access fiddle can u paste in a plunkr. I knw there used to be a bug with email validator pattern...
Comment: I understand what you are saying, your issue has more to do with the html5 email validation and angular's If you do the same in the demo in official documentation as well you will see the same. https://docs.angularjs.org/api/ng/input/input%5Bemail%5D You can use your own pattern by providing `ng-pattern`
Comment: Ok, very funny... In plunker the email validation works as in my program : http://plnkr.co/edit/YcjlZpUwOgfVC0KyEQoM?p=preview Anyway, the required thing works, I had a conflict above the button in some input ng-class that probably made the thing not working. I didn't have any error to notice it, pretty hard to guess what is wrong while using angular directives, there are no errors on the console.
Comment: I've tried to find a good email pattern on the net, but it seems to be a complicated problem, there is no unique answer to this. =/
Comment: No thats true. It completely is relative.. In my case we have our own custom pattern to include our domain as well.. So yes it differs


Multiple filed handlers in Views for a field

Question: How do I set multiple field handlers in Views on a single field.
I've applied the patch Relationship & sort for {history} to Views which brings in the user relationship on the history table. I then replaced the Views field handler for ['history']['timestamp'] in node.views.inc with this:
  $data['history']['timestamp'] = array(
    'title' => t('Node last access timestamp'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
      'help' => t('Show the timestamp a node was last accessed by user.'),
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
      'help' => t('Sort by the node last access time.'),
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
      'help' => t('Filter by the node last access time.'),
    ),
  );

because I need the timestamp as a date field. Normally it is this:
$data['history']['timestamp'] = array(
    'title' => t('Has new content'),
    'field' => array(
      'handler' => 'views_handler_field_history_user_timestamp',
      'help' => t('Show a marker if the content is new or updated.'),
    ),
    'filter' => array(
      'help' => t('Show only content that is new or updated.'),
      'handler' => 'views_handler_filter_history_user_timestamp',
    ),
  );

But ideally I would like to have both field handlers available because I do not want to remove the default handler in Views. How do I do this?
Answer: You don't. That's not possible.
But you still have options:

Define your own field handler and add support for multiple display formats using configuration options, have a look at this snippet for an example: https://gist.github.com/juampy72/5816530. The key methods to implement this are option_definition, options_form, options_submit and render.
This is more of a work-around. Copy the definition of the first field handler under different database column key, e.g. $data['history']['timestamp_as_date'] = array( .... Then implement your own filter class as before, but also override the query method in order to ensure that the timestamp column is present. Then display that as you like.

There are a lot of code examples out there.
Comment: Thank you for pointing me in the right direction. The answer was even simpler though, and has been answered before in [How do I alter the output of a field using a views handler](http://drupal.stackexchange.com/questions/62896/how-do-i-alter-the-output-of-a-field-using-a-views-handler). The magic was in adding a field alias to hook_views_data for the history table, and declaring the real field.
Comment: I didn't know about the field alias possibility. Handy information!


Como testar service worker localmente?

Question: Na minha tentativa de entender o funcionamento dos services workers estou tentando implementar o mesmo numa aplicação básica que estou servindo localmente, o problema é que o service worker falha ao se registrar, olhando mais atentamente a documentação percebo que os mesmos necessitam de HTTPS o que me leva a pergunta é possível testar um service worker localmente ou somente no server em produção? Eis meus scripts:
Meu app implementado com express.
# app.js

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.listen(8080, () => {
  console.log('Application running...');
});

Minha página inicial(e única) que quero cachear.
# index.html

<!DOCTYPE html>

  <title>Welcome to Vue</title>

{{ greeting }}

        To learn more about Vue, visit

          {{ humanizeURL(docsURL) }}

        For live help with simple questions, check out

          the Discord chat

        For more complex questions, post to

          the forum

Meu arquivo referente ao service worker.
# sw.js

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('v1').then(cache => {
      return cache.addAll([
        '/basic-pwa/',
        '/basic-pwa/index.html'
      ]);
    });
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(resp) {
      return resp || fetch(event.request).then(function(response) {
        caches.open('v1').then(function(cache) {
          cache.put(event.request, response.clone());
        });
        return response;
      });
    }).catch(function() {
      return caches.match('');
    })
  );
});

Comment: A onde viu que o SW precisa ter HTTPS?
Comment: Na documentação diz que você pode usar services workers no localhost em desenvolvimento, mas como pode ver não estou conseguindo fazer funcionar.
Answer: Service worker precisa de um ambiente seguro, e "localhost" na porta 80 é considerado um ambiente seguro.
Caso você precise realizar um teste em um ambiente não seguro, pode ligar uma flag no chrome: Insecure origins treated as secure e cadastrar o url.
chrome://flags/#unsafely-treat-insecure-origin-as-secure

obs.: lembre que não adiante apenas cachear o index.html. Precisa cachear qualquer arquivo linkado além das imagens inclusive o favicon.ico...
Nos seus exemplos acima, existe um erro no ws.js, segue arquivo sem erro...
self.addEventListener(
  'install',
  event => {
    event.waitUntil(
      caches.open('v1')
      .then(
        cache => {
          return cache.addAll(
            [
              '/',
              '/index.html'
            ]
          )
        }
      )
    );
  }
);

Como testar service worker localmente?


Copy site to another domain - XML SiteMap wrong and Theme Settings not the same

Question: I copied my productive site from www.mydomain.com to a testsite www.mytestsite.com on the same server. I did it this way:
On productive server:

Set productive site to offline
Disabled Clean URL
Emptied Cache
created backup with the "backup and migrate" tool. All tables are backuped exept all cache-table and watchdog
Copy all files

On target test server:

Create new empty DB
Import SQL script via MySQLAdmin from provider
Copy all files
change settings.php
Login as Admin, set online, enable clean url, empty cache

Now I should have an identical site. But I have two differences (maybe more, which I cannot see):

XML Sitemap: Takes still the old domain name ("www.mydomain.com"). I can delete it and rebuild, no change. Why? This means that somewhere in a file the domain name must be written
The colors of hyperlinks are blue instead green as in the original site. When I go to "Theme settings" and simply press "save", then all is ok. Also here: Why is there wrong information about theme settings? Is this not saved in the DB?

Any help appreciated, thanks
Answer:
Go to admin/config/search/xmlsitemap/settings and set the correct domain. If that does not work look at your variable table in database and make sure xmlsitemap_base_url is correct.
Make sure your folder permissions are correct. If you have caching enabled and some themes need to write temp files inside sites/default/files so make sure permissions are correct and that Drupal can write there.

If that does not work can you inspect where the styles are coming from using Firebug and also post what theme you are using and I can update my answer.
Comment: thanks for your help.  sitemap worked, I did not see the advanced settings. about folder permissions: I will test it and migrate site again. just a question: why can it be because of permissions? when I went to theme settings and pressed "save" all was ok. this seems like permissions are ok
Comment: Depending on theme some themes have to write files into sites/default/files folder depending on theme. If they are not able to save those settings it will show everything correctly but it will revert back. What theme are you using?


Auto Load next Post like qz.com

Question: How the functionality of auto loading the next post when you reach the end of a content is reached.
This functionality is seen in Quartz which is built on Wordpress. Most probably they are using the Auto Load Next Post plugin.
Is there any module or a way by which this can be replicated in Drupal (Drupal 8 if possible)?
Answer: If you want to go a site builder approach, one solution here is Views Infinite Scroll.

Views infinite scroll allows you to load and display pages of any view
  inline, using AJAX (this has been called infinite scrolling, load
  more, autopaging, endless pages and more). The pager can be triggered
  with the press of a button or automatically as the user scrolls to the
  bottom of the view's content.

The caveat with this approach is you'd need to rely on a Views page configured with an Infinite Scroll pager set with the Automatically Load Content option. In other words, a static URL showing paged full content. That's pretty close to the functionality, but not perfect replication.
Comment: yes, this is close approach. Only concern will be, the title of the page won't change.
Comment: did u find a solution

Auto Load next Post like qz.com


Enviando Model para Controller via Ajax

Question: Tenho uma View fortemente tipada com um pequeno formulário e uma função javascript com uso de ajax:
function emitir () {
    $.ajax({
        type: "POST",
        traditional: true,
        url: '@Url.Action("EmissaoRapida", "CND")',
        data: { model: @Model },
        success: function (data) {
            alert(data.mensagem);
        },
        error: function () {
            alert("Erro na tentativa de emissão!");
        }
    });
}

Quero simplesmente enviar o meu modelo de dados para meu controlador, o método que receberá o model tem a seguinte assinatura:
    public JsonResult EmissaoRapida (EmissaoCND model)
Porém acontece algum erro, utilizando o depurador do Firefox eu percebi que tem algo errado no momento da passagem do modelo, pois o problema é que não é feita a leitura da raiz do projeto conforme quando faço a tipagem na view.
    @model Pro_Certidao.Areas.Usuarios.Models.EmissaoCND
No erro Pro_Certidao fica de uma cor diferente, acredito que o problema seja ali e a mensagem que temo é este: Erro em tempo de execução do JavaScript: 'Pro_Certidao' não está definido
Existe alguma forma de consertar isso ou fazer algo de forma semelhante enviando o modelo de dados completo?
Answer: Tente passar no model o form serializado.
Supondo que seu form seja de id formxpto:
function emitir () {
    var model = $("#formxpto").serialize();
    $.ajax({
        type: "POST",
        traditional: true,
        url: '@Url.Action("EmissaoRapida", "CND")',
        data: model,
        success: function (data) {
            alert(data.mensagem);
        },
        error: function () {
            alert("Erro na tentativa de emissão!");
        }
    });
}

Ou por jQuery:
$.post("@Url.Action("EmissaoRapida", "CND")", $("#FormFinalizaOrdem").serialize()).done(function (retorno) {}

Sua controller deve receber o mesmo objeto do model, que no caso é Pro_Certidao.Areas.Usuarios.Models.EmissaoCND
Se der certo, poste para que ajude a outras pessoas.
EDIT
Sua model tem que estar com a anotação [Serializable]:
using System;

[Serializable]
public class EmissaoCND
{
      //Atributos...
}

Seu método da controller anotado com [HttpPost]:
[HttpPost]
public ActionResult EmissaoRapida(EmissaoCND EmissaoCND) {}

Comment: O erro já não acontece mais, pelo menos o navegador não reclama, porém quando chega no método do meu controller o model está null.
Comment: confira se seu método da controller está anotado com `[HttpPost]` e se sua model está com `[Serializable]`, do `System.SerializableAttribute`
Comment: Na controller estava tudo certo já, porém no Model eu adicionei o '[Serializable]' e nada ainda, mas não consigo colocar o 'using' correto, na verdade ele nem deixa eu adicionar o 'System.SerializableAttribute'
Comment: Editei o post  da resposta, dá uma conferida como seu model deve estar.
Comment: Tá basicamente igual, tanto a Model como a Controller. Única coisa diferente é que eu estou usando o EF e utilizo a DataAnnotation.Schema para relacionar melhor as coisas com o banco de dados
Comment: alterei o método `emitir()`, dá uma olhada..
Answer: Exemplo abaixo;
function DeleteUser() {
    var dados = { Id: $("#deleteuser").val() };

    $.ajax(
        {
            type: "POST",
            url: "/Usuarios/Delete",
            data: dados,
            success: function (msg) {

            },
            error: function () {

            }
        });
}

Enviando Model para Controller via Ajax


JavaScript supposed to always be called on front page, but doesn't always run

Question: I have some JavaScript that is called on the front page, and is supposed to execute.  When I go the page initially, it works fine.  Then if I go to another page, then come back, it doesn't show.  It does load, and after other JavaScript files it requires.  It just doesn't execute.  If I refresh, it loads again.
(function ($) {

    Drupal.behaviors.chartSavings = {
        attach: function (context, settings) {

            // .....

            // create the submit handler
            $('#savings-form').submit(function(event) {

                event.preventDefault();
                //alert('Form submitted xxx');

                savingsplot();

            });

            savingsplot();

        }
    }

})(jQuery);

What am I doing wrong?  I don't have any caching enabled, and in drupal_add_js(), I set cache to FALSE.
Comment: Have you checked HTTP headers to see it is really uncached? But it shouldn't matter, really. Try `console.log` maybe script runs, and it just does not do what you expected?
Comment: Where have you put your code that calls drupal_add_js()?
Comment: I moved it back to #attached in my form.  I moved it to drupal_add_js() for troubleshooting.
Answer: I think perhaps the issue stems from the browser's "BFCache" which is a browser feature that caches a page for quicker loading when a user presses the Back/Forward button. See below to understand more about this feature.
Try adding the following code inside of your attach function.
// Prevent the bfcache.
$(window).bind("unload", function() {});

The "BFCache" as taken from page:
https://stackoverflow.com/a/2218733/955858
To quote that post:

The modern browsers (Firefox, Safari/Chrome, and Opera) all support the special "back/forward" cache (I'll call it bfcache, which is a term invented by Mozilla), involved when the user navigates Back. Unlike the regular (HTTP) cache, it captures the complete state of the page (including the state of JS, DOM). This allows it to re-load the page very quickly and exactly as the user left it, which is what the user wants.
The load event is not supposed to fire when the page is loaded from this bfcache. For example, if you created your UI in the "load" handler, and the "load" event was fired once on the initial load, and the second time when the page was re-loaded from the bfcache, the page would end up with duplicate UI elements.
This is also why adding the "unload" handler stops the page from being stored in the bfcache (thus making it slower to navigate back to) -- the unload handler could perform clean-up tasks, which could leave the page in unworkable state.
For pages that need to know when they're being navigated away/back to, Firefox 1.5+ and some next version of Safari (which contains the fix for bug 28758) supports special events called "pageshow" and "pagehide".
References: http://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ and https://developer.mozilla.org/En/Using_Firefox_1.5_caching.
Comment: Your quote is out of date. In fact you shouldn't put long quotes like that from other SO pages for that very reason. Chrome doesn't have a bfcache, although it sounds like it will soon at this point.
Answer: I had Context Breakpoint installed and enabled (even though I didn't use it yet), and found a JS error.  Since I wasn't using it, I disabled it, and the problem seems to have cleared up.  Reading further, it seems there are some caching implications related to that module.  I'd love to know how exactly that happened underneath.


Calculate the probability that James' total commute is less than 25 minutes.

Question: James commutes to work by walking 5 minutes to the bus stop, then waits $X$ minutes for the bus to arrive, after which the bus journey to work takes $Y$ minutes. Supopse $X$ and $Y$ are well-approximated by normal distribution, such that we may assume $X\sim N(4,1)$, and $Y\sim N(20,4)$ with $X$ and $Y$ being independent random variables.
Calculate the probability that James' total commute is less than 25 minutes.
My attempt:
$P(\text{ total commute } < 25)$
$=P(5+X+Y<25) = P(X+Y<20)$
We know that $X$ and $Y$ are independent. Hence $Z=X+Y\sim N(20+4,1+4)=N(24,5)$. We also note that $Z>0$ since we can't have negative time.
Hence $$P(Z<20)=\int^{20}_0 f_Z(z)\mathrm{dz}=\int^{20}_0\frac{1}{\sqrt{2(5)\pi}}\frac{e^{-(z-24)^2}}{2(5)}\mathrm{dz}$$
Is this the right way to do this problem? I can't calculate this integral so I think it's wrong.
Answer: You are almost there. As you wrote,
$$X+Y\sim N(24;5)$$
Thus
$$\mathbb{P}[X+Y<20]=\mathbb{P}\left[Z<\frac{20-24}{\sqrt{5}}  \right]=\Phi\left( \frac{-4}{\sqrt{5}}\right)\approx 3.68\%$$

you cannot have a negative time because the range of your gaussian is
$$(X+Y)\in 24\pm 6.71$$
where $6.71=3\sigma$
Comment: Where did you get $\mathbb{P}\left[Z<\frac{20-24}{\sqrt{5}}  \right]$ from? Also, is the expression after that supposed to be the cumulative density function?
Comment: @user: Just standardized your gaussian $W\sim N(24;5)$ so that $\frac{W-24}{\sqrt{5}}\sim N(0;1)$. Yes, $\Phi$ is the CDF of a Standard Gaussian
Comment: @user : Use $Z$ for the standard gaussian...it is not mandatory but usually people do that


How to load some data from a Database on the first request but prevent other calls (at the same time) from doing it also in .NET?

Question: I have a class which is registered with my Dependency Injection as a SINGLETON - so only one instance / the same instance of this class is injected into my MVC Controller.
In this class, I have a single method that does this:

Load data from file/database (into RAM) on the VERY FIRST CALL to this method only. e.g. names of all the countries, or all the people in a movie, etc. whatever.
Now do some really simple text query against this collection of data in RAM.

So the main point here is that I need to only load the data once. Here's my code btw..
public string Foo(ISession dbSession)
{
    LoadDataFromFileOrDbOrWherever();

    return GetAnswer(_data);
}

You get the idea. The main point of this is that the METHOD has to provide the current database session. This is what kills me :( I was thinking of using Lazy<IList<MyData>> and doing this in the constructor ... but I need the ISession to be passed into the constructor, which I actually don't have yet.
So what is the common pattern people do here, for getting some data on the first call only, remembering that .. and then referencing that, from now on.
If two or three calls are made at the same time, I'm expecting the 2nd/3rd/etc call to BLOCK/WAIT until the first call completes the data load process.
Initially I thought of Double-Checked locking ... but that's a sorta anti-pattern these days now that .NET has the nice Lazy<T> class.
Any ideas, kind folks?
Comment: Well this sound like a perfect place to use Task and async. have a InitAsync and all the other operations wait for it to be done.
Comment: I remember the creator of [Akavache](https://github.com/akavache/Akavache) talking about a similar problem. Found the [talk](https://www.youtube.com/watch?v=j7WnQhwBwqA)
Answer: Your could use LazyCache which will execute your wished method once and will give you the cached result whenever you call it again.
using LazyCache;

IAppCache cache = new CachingService();
return await cache.GetOrAddAsync<ILoadChartStorageInformation[]>
(key, (Func<Task<ILoadChartStorageInformation[]>>) (async () =>
{
    return await someFunction();
}

Look at the LazyCache documentation to get a more detailed documentation:
https://github.com/alastairtree/LazyCache


Firebase JS Issues with Netskope

Question: My company has implemented Netskope for security and it is causing issues with my Firebase web app. I have verified Netskope is the cause of problem by having our security admins disable it on my PC. When that was done, the web app performs as expected. With Netskope enabled, users are able to log in but can't retrieve documents (and I'm assuming can't edit or delete either). Instead, there is an error in the console that says
Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds. This typically indicates that your device does not have a healthy internet connection at the moment.

Some code:
var app = firebase.initializeApp(config);
var db = firebase.firestore(app);

var docRef = db.collection("/annual meeting/Events/" + selectedDay).orderBy("time").get().then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
                eventIds.push(doc.id);
                eventDocs.push(doc.data());
            });
            addEventsToList();
        })

My security people are asking for specific URLs so they can investigate. I've sent them https://console.firestore.google.com/project/*project-name*/firestore, but I'm not sure what else to send them. They seem to think it's either a certificate pinning issue or Firebase not liking Netskope's egress IPs. They need specific URLs to redirect, but I'm not sure what to give them.
Answer: According to the Firestore documentation, the client libraries and APIs use the firestore.googleapis.com service to communicate with Firestore.

To call this service, we recommend that you use the Google-provided client libraries. If your application needs to use your own libraries to call this service, use the following information when you make the API requests.

If your security department is requesting URLs to investigate, you can try with the REST endpoints of this API. Inside the documentation, there is an API test app included (API Explorer). This feature lets you make requests to the service with appropriate authentication. For example the following endpoint is used to retrieve documents from Firestore:
https://firestore.googleapis.com/v1/{name=projects/*/databases/*/documents/*/**}

The request parameter name for this endpoint when using the API explorer would be:
projects/projectID/databases/databaseID/documents/documentPath

projectID = your project ID
databaseID = for Firestore use: "(default)"
documentPath = path of the document to retrieve (collection/document/...)

Additionally, I found other questions related to Firebase and Netskope in Stackoverflow and GitHub
Comment: Was this information useful for your issue? in case other users are finding the same issue with NetSkope

Firebase JS Issues with Netskope


Máscara para um campo datepicker em uma aplicação

Question: Possuo uma aplicação em wpf, assim existem janelas que têm campos para tipos data, coloquei esses campos com datepicker em que há um calendário para a escolha da data.
Até ai tudo bem, o que não consegui por é uma máscara para ficar assim "00/00/0000" nesse campo, aceitando somente números.
Alguém tem alguma ideia do que posso fazer?
Answer: <code><TextBlock Text="{Binding Start, StringFormat=d}" />
</code>
ou
<code> <TextBlock Text="{Binding Path=OrderDate, StringFormat='{}{0:dd.MM.yyyy}'}"/>
</code>
Comment:  eu tenho isso Fabio, coloco ai dentro?
Comment:
Comment: Tenta isso acima, estou fora do meu pc com windows... mas isso deve servir.
Comment: Error 1 Unknown build error, 'Key cannot be null.
Parameter name: key Line 114 Position 88.'  da um erro asim. Não aceita x: Static System:DateTime.Now
Comment: Desculpe, cometi um erro, a propriedade que vc tem de aplicar a mascara, é a DisplayDate, não selectedDate <DatePicker HorizontalAlignment="Left" DisplayDate="{Binding PROPRIEDADE_DATA, StringFormat='{}{0:dd.MM.yyyy}'}" SelectedDate="{Binding Path=Data}" Margin="139,58,0,0" VerticalAlignment="Top"
Comment: PROPRIEDADE_DATA o que seria?
Comment: A sua propriedade que estará selecionada. Por exemplo, no seu modelo de dados, a você tem algo do tipo DataSelecionada... Então você colocaria isso


How are the definitions of Weil divisors with subsets and subscheme equivalent?

Question: I've seen a Weil divisor be defined in two slightly similar ways and I'm not sure I understand why they are equivalent (assuming that indeed they are. They are as follows.
A Weil divisor on X is a finite linear combination with integral coefficients of:
1.irreducible closed subsets Z of X of codimension one
2.closed integral subscheme Y of codimension 1
Answer: They are equivalent because of the following. Given any closed subset $Z\subseteq X$ of a scheme there is NOT a unique scheme structure on $Z$. But, there is a unique minimal scheme structure—the one coming from the reduced structure on $Z$. Explicitly, find an ideal sheaf $\mathcal{I}$ of $X$ which cuts out $Z$ and take the scheme structure on $Z$ given by $\mathcal{O}_Z/\sqrt{\mathcal{I}}$. This is called the reduced structure on $Z$
Your answer should be pretty clear once you recall that a scheme $Z$ is integral if and only if it's reduced and irreducible. So, to a closed irreducible subset $Z\subseteq X$ of comdimension $1$, there is a unique closed integral subscheme having $Z$ as its underlying space.


mod rewrite with query

Question:
Possible Duplicate:
Query Strings & Mod ReWrite

I'm attempting to use mod rewrite to make links prettier without www and go from:
http://example.com/folder/page.html to
http://example.com/index.php?page=page&folder=folder
I've managed a basic version of this for top layer pages which are not in folders but am puzzeled how to include this rule and get folder to appear. I would also like query strings to stay so piwik analytic links work, such as:
http://example.com/folder/page.html?piwik=something goes to:
http://example.com/index.php?page=page&folder=folder&piwik=something
Any help would be most appreciated, this is what I've got so far:
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
RewriteRule ^([^/]*)\.html$ /index.php?page=$1 [L]
</IfModule>

Answer: You want the QSA flagDocs, example code below:
RewriteRule ^/([^/]+/)?(.+\.html)$ /index.php?folder=$1&page=$2 [QSA,L]

Reference:
Found this page http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
Just hit CTRL+F and search for "QSA" (without speech marks)

mod rewrite with query


back button navigation with fragments

Question: I'm building a somewhat gallery app. I use one activity to hold fragment_1 in which I display images in a recyclerview. From fragment_1 I can go to fragment_2. Both fragments have their own different toolbars. My wish is to go from fragment_2 back to fragment_1 by pressing a back arrow in the toolbar.
How I go from fragment_1 to fragment_2:
Fragment2 fragment2 = new Fragment2();
    getActivity().getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, fragment2)
            .addToBackStack(null).commit();

What I already did in fragment_2:
Toolbar toolbar = getView().findViewById(R.id.toolbar_2);
    ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);

This didn't work:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            getActivity().onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Comment: Is `Toolbar` in `Activity` layout or each `Fragment` has its own `Toolbar`?
Comment: each fragment has its own.
Answer: @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            getActivity().getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, new fragment1).commit();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    } }

Answer: If each fragment has Toolbar in own layout than you can easily access Toolbar in onViewCreated after View is inflated in onCreateView. After that you can set the navigation icon and call setNavigationOnClickListener. Inside you can choose from couple approaches either to replace exiting Fragment by new Fragment or remove existing Fragment or use popBackStack. In code that would look like this:
Toolbar toolbar = view.findViewById(R.id.toolbar) // id of your toolbar
 toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp); // set the back arrow in toolbar

    //set click listener on back arrow
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getFragmentManager().popBackStack();
 });

To use this approach you need to add Fragment with no null in addToBackStack. For example:
getFragmentManager().beginTransaction()
        .add(R.id.container, your fragment here)
        .addToBackStack("BackStack").commit();

Answer: If you want onOptionsItemSelected to be triggerd from a fragment you need to set setHasOptionsMenu to true, for example from onViewCreated :
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
   setHasOptionsMenu(true);
}

Answer: Use popBackStack() method from removing fragment from back stack.
Try using this code:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            getActivity().getSupportFragmentManager().popBackStack();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

back button navigation with fragments


is there any solutions for react-scrollable-picker in reactjs with type script?

Question: I am using a react-scrollable-picker from the https://ayame30.github.io/react-scrollable-picker/
but it shows an error like
Could not find a declaration file for module 'react-scrollable-picker'. '/directory/node_modules/react-scrollable-picker/lib/react-scrollable-picker.js' implicitly has an 'any' type.     Try npm i --save-dev @types/react-scrollable-picker if it exists or add a new declaration (.d.ts) file containing declare module 'react-scrollable-picker';
again i try npm i --save-dev @types/react-scrollable-picker but looks like registry not found, how i can resolved this issue.?
Answer: You could add you own declaration file as per plan C in this post.
Also check out this post on stackoverflow.


Error when accessing keychain with Firebase iOS 10

Question: I'm having issues with keychain on iOS 10 devices. Failed to retrieve saved users, only happens with iOS 10 users, authentication is with Firebase. This is the error:

Error loading saved user when starting up: Error Domain=FIRAuthErrorDomain Code=17995 "An error occurred when accessing the keychain. The @c NSLocalizedFailureReasonErrorKey field in the @c NSError.userInfo dictionary will contain more information about the error encountered" UserInfo={NSLocalizedDescription=An error occurred when accessing the keychain. The @c NSLocalizedFailureReasonErrorKey field in the @c NSError.userInfo dictionary will contain more information about the error encountered, error_name=ERROR_KEYCHAIN_ERROR, NSLocalizedFailureReason=SecItemCopyMatching (0)}
Comment: Are you trying this on an actual device or in the simulator? There is a Keychain bug with the iOS 10 simulator. The error code is different, but it might still be related: https://openradar.appspot.com/27844971
Comment: @JordanBondo On the device
Comment: did you solve this? I seem to be having the same issue
Answer: As mentioned in the link of the first answer there is a workaround:

Go to your *.xcodeproj
Go to the tab "Capabilities"
Activate "Keychain Sharing"

Btw, is there an issue tracker for xcode?
Comment: My keychain is enabled, but I'm still getting the same error as OP, does anyone know where `@c NSError.userInfo dictionary` is? I have no idea how to even check that.
Comment: This doesn't work. Are you leaving some other important detail out?
Comment: This may be a glitch when using a simulator as pointet out in this github comment: https://github.com/firebase/FirebaseUI-iOS/issues/818#issuecomment-587928935
Comment: @metamonkey This is the important detail left out!
Answer: Building on @bash0ne's answer:
First, do what @bash0ne said, namely (modified for the newer version of Xcode):

Go to your app target
Go to the tab "Signing & Capabilities"
Click the plus in the top right corner
Search "Keychain Sharing" and select it to activate it

Then, add a Keychain group. To do so, in Signing & Capabilities (same section as before) scroll to the "Keychain Sharing" section. There is a table for "Keychain Groups," and you can add to this table.
As this answer says, the keychain group needs to have this format:
<TEAM_ID>.<APP_NAME>.<GROUP_NAME>
If you click "+", Xcode adds the default group, and the default that Xcode added worked for me.
Final, somewhat separate note. Users in the comments asked how to check "userInfo" for the error. You have to cast the error as NSError and then check, as such (assumes error is of type Error?):
print((error! as NSError).userInfo)
Comment: Do you mean it should literally have the string value `..` or we should replace the strings in angle brackets with their values (`` etc)?
Answer: My issue (same as above) was fixed by simply removing the$(AppIdentifierPrefix) string which is added to the entitlements file (if you use Xcode UI to add the keychain sharing group).
Comment: That can cause your app to crash.
Answer: This worked for me, but I'm not sure if it will work for everyone. Go to your target and click on the "signings & capabilities" tab. Click "+Capability" in the upper left and add "App Group". Add your group.member.project or whatever your keychain is there and delete the keychain capability. If you get an error regarding your entitlements file clear your build folder (Product > Clear Build Folder) and see if you can build it again!


Impressão de resultado da estrutura de repetição For não ocorre mas não apresenta erro, como resolver?

Question: import java.util.Scanner;

public class Contador{

    public static void main(String[] args) {
        Scanner terminal = new Scanner(System.in);

        System.out.println("Digite o primeiro um número de 1 a 20: ");
        int numeroUm = terminal.nextInt();

        System.out.println("Digite um segundo número de 1 a 20: ");
        int numeroDois = terminal.nextInt();

        try{
            contar(numeroUm, numeroDois);

        }catch (ParametrosInvalidosException e ) {
            System.out.println("O segundo número precisa ser maior que o primeiro!");

        } finally {
            terminal.close();
        }

    }

    public static void contar (int numeroDois, int numeroUm) throws ParametrosInvalidosException{
        if (numeroUm <= numeroDois)
            throw new ParametrosInvalidosException();

            int contagem = numeroDois - numeroUm;

            for(int resultado = 1; resultado < contagem; resultado++){

                System.out.println("Contando o resultado: " + resultado);
            }
    }
}

Comment: O problema é que no teu método `contar` você nomeou os parâmetros de uma maneira confusa. dando a entender o que o `numeroum` e `numerodois` lido no main, parecem ser os mesmos no método contar, mas não são, então ele nem entra no for, pois o valor é um número negativo acarretando que ele nem entra no for. (se usar os valores 1 e 5).
Comment: Problemas como este podem ser encontrados debugando a aplicação. Este [link](https://pt.meta.stackoverflow.com/questions/7785/como-debugar-programas-pequenos) pode ajudar
Answer: Seu codigo não tinha um else, então quando não atendia a cláusula valida simplesmente não fazia nada, sua conta de menos para calcular o for também estava invertida, além da contagem também estar incorreta segue o código ajustado:
package br.com.claudemir;

import java.util.Scanner;

public class Contador {

    public static void main(String[] args) {
        Scanner terminal = new Scanner(System.in);

        System.out.println("Digite o primeiro um número de 1 a 20: ");
        int numeroUm = terminal.nextInt();

        System.out.println("Digite um segundo número de 1 a 20: ");
        int numeroDois = terminal.nextInt();

        try {
            contar(numeroUm, numeroDois);

        } catch (ParametrosInvalidosException e) {
            System.out.println("O segundo número precisa ser maior que o primeiro!");

        } finally {
            terminal.close();
        }

    }

    public static void contar(int numeroDois, int numeroUm) throws ParametrosInvalidosException {
        if (numeroUm <= numeroDois) {
            throw new ParametrosInvalidosException();
        } else {
            int contagem = numeroUm - numeroDois;

            for (int resultado = 1; resultado <= contagem; resultado++) {

                System.out.println("Contando o resultado: " + resultado);
            }
        }
    }
}


Proving that a function is not injective.

Question: The proof asks for a function $f: \mathbb{R} \rightarrow \mathbb{R}$ given by $$f(x)=\frac{1}{x^2+1}$$ prove that it is neither injective nor surjective.
My thoughts are to approach this using a proof by contradiction, and say I will prove that the function is injective. I can get to the step where $a^2=b^2$ and I know the square root of a variable is $\pm$ that variable. So would my final step be to say that $\pm a \neq \pm b$?
Comment: I think it's easier to exhibit $x\neq y$ with $f(x)=f(y)$.  All you need is one such pair to prove $f$ isn't injective.
Comment: Did you ever see an injective even function?
Comment: I think stating "$\pm a = \pm b$" is ambiguous.  It means $a$ *could* equal $b$ and therefore this isn't a proof that there exist any that don't.  I'd prefer it if you specifically pointed out: and therefore if $b =-a\ne a$ we have $f(b)=f(a)$.
Answer: The easiest way to prove that a function is not injective is to explicitly name distinct elements of the domain that map to the same place.
The easiest way to prove that a function is not surjective is to explicitly name an element of the codomain that is not mapped to.
In this case, $$f(1) = \frac{1}{1+1} = \frac{1}{2}\ \ \ \text{and} \ \ \  f(-1) = \frac{1}{1+1} = \frac{1}{2},$$ and there is no $x \in \mathbb{R}$ such that $$ \frac{1}{x^2 +1} = -5,$$ so $-5 \in \mathbb{R}$ is not mapped to.
Answer: A counterexample suffices: $1 \neq -1$ but $f(1) = f(-1)= \frac12$ so $f$ is not injective.
Also, $f(x)$ never assumes the value $0 \in \mathbb{R}$, so $f$ is not surjective, and moreover all $f(x) >0$, so all negative values are also never assumed.
$f$ would be bijective as a function from $(0,\infty) \to (0,1)$..
Answer: Look at $f(1)=f(-1)$. These are the same, therefore, f cannot be injective.
To prove it is not surjective, try to find an x such that $f(x)>1$, say 2. Then f(x)=2 means solving $x^2=-1/2$ which has no real solution.
Answer: It would be easier to just demonstrate that there is some element $y$ in $\mathbb R$ such that $f(x)\neq y$ for all $x\in \mathbb R$, and also find two numbers $x_1\neq x_2$ such that $f(x_1)=f(x_2)$.
Could you do this for the function $x\mapsto x^2$ (just think of the graph)? If so the how about for the function $x\mapsto x^2+1$? What about the function $x\mapsto 1/x$? Moving from these functions to $f$ should then be fairly simple.
Answer: I'm assuming your proof is something like:
Let $f(a) = f(b)$ so
$\frac 1{a^2 +1} = \frac 1{b^2 + 1}$
.....
$a^2 = b^2$
so $\pm a = \pm b$,
and you are asking if that completes the proof.
Well, not really but mostly, in my opinion.  You need to explicitely state $a \ne b$ IS a possibility.  "$\pm a = \pm b$" seems as though you are solving an equation and have found multiple pontential solutions but nothing definite.  We aren't actually trying to solve something but prove that something could definite happen.
So if you concluded with the statement:
"and so if $b = -a \ne a$ we'd have a case where $f(a) = f(b)$ but $a \ne b$"
then it would be adequate, in my opinion.
.....
However I also think it'd be more direct to simply say from the start:
For any $a \ne 0$ then $a \ne -a$.  But $f(a) = f(-a)$ so $f$ is not injective.
....
or as others have pointed out a single specific counter example would do.


Independence of Bernoulli Variables if Bernoulli Parameters are Dependent?

Question: I have a conceptual question about the effect that dependent random variables have on the independence of other random variables if the dependent random are used as parameters of the other random variables.
For concreteness, suppose we have a sequence of random variables $p_1, p_2, ...$ that follows a random-like walk of $p_n = \min(\max(p_{n-1} + \epsilon_n, 0), 1)$ where $\epsilon_n$ is some small i.i.d. noise e.g. $\epsilon \sim N(0, 0.001)$ and the min and maxes act to ensure $p_n \in [0, 1]$. I then use this sequence of random variables as the parameters for another sequence of binary random variables $q_1, q_2, ...$ where $q_n \sim Bern(p_n)$. My questions are:

Are $q_i$ and $q_j$ for $i \neq j$ independent from one another?
Are $q_i$ and $q_j$ for $i \neq j$ conditoinally independent from one another given $p_i, p_j$?

Intuitively, it feels like the answers are no and yes, respectively. Is this correct?
Answer: To facilitate this analysis, I will use upper and lower-case notation to distinguish random variables and their outcomes.  Consequently, I will depart slightly from your notation.
Whether or not the values are conditionally independent given the underlying probability is up to you --- you need to specify this as part of your model.  Usually, when we write $q_i \sim \text{Bern}(p_i)$ this is a shorthand for a model where we take the values to be conditionally independent given the underlying probability vector, so usually that is what you would be assumed to mean if you write that.  If we assume conditional independence then (formally) we have:
$$\mathbb{P}(Q_1 = q_1,...,Q_n = q_n | \mathbf{P} = \mathbf{p}) = \prod_{i=1}^n \text{Bern}(q_i|p_i) = \prod_{i=1}^n p_i^{q_i} (1-p_i)^{1-q_i},$$
where  $\mathbf{p} = (p_1,...,p_n)$ denotes the vector of probability values for the observable values.  Now assuming you specify that there is conditional independence here, the dependency in the underlying probabilities will still lead to a situation where the observable values are not independent (they will generally be positively correlated).  To get an expression for the joint probability of the observable values, suppose we let $\pi(p_1)$ denote the marginal density of the first probability and let $\eta(p_i|p_{i-1})$ denote the conditional probability density for each subsequent probability.  Applying the law of total probability gives:
$$\begin{align}
\mathbb{P}(Q_1 = q_1,...,Q_n = q_n)
&= \int \mathbb{P}(Q_1 = q_1,...,Q_n = q_n | \mathbf{P} = \mathbf{p}) \cdot \mathbb{P}(\mathbf{P} = \mathbf{p}) d \mathbf{p} \\[6pt]
&= \int \Bigg( \prod_{i=1}^n p_i^{q_i} (1-p_i)^{1-q_i} \Bigg) \Bigg( \pi(p_1) \prod_{i=2}^n \eta(p_i|p_{i-1}) \Bigg) d \mathbf{p} \\[6pt]
&= \int \pi(p_1) p_1^{q_1} (1-p_1)^{1-q_1} \prod_{i=2}^n p_i^{q_i} (1-p_i)^{1-q_i} \eta(p_i|p_{i-1}) d \mathbf{p}. \\[6pt]
\end{align}$$
In the special case where $\eta(p_i|p_{i-1}) = \pi(p_i)$ this expression will reduce down to a product of terms for $q_1,...,q_n$ (establishing independence), but in the general case it does not.


Asymptotic expansion of Erfi(x)

Question: I know that the imaginary error function, $\mathrm{Erfi}(x)=(2/\sqrt{\pi})\int_0^x \exp{t^2} \mathrm{d}t$, has the asymptotic expansion given in the answer to this question: Asymptotic order of $\frac{\mathrm{erfi}(\sqrt{x})}{\exp(x)\sqrt{x}}$ .
My question is about deriving this expansion, which I think is based on integration by parts. For example, if we use integration by parts once we can rewrite the function as
$\mathrm{Erfi}(x) = \frac{2}{\sqrt{\pi}} \left[\frac{1}{2t}\mathrm{e}^{t^2}|_0^x+\frac{1}{2}\int_0^x\frac{\mathrm{e}^{t^2}}{t^2} \mathrm{d}t\right]$,
and then keep on doing this procedure for the leftover integral. This indeed produces the terms in the expansion mentioned above. However, what happens to the terms evaluated at $t=0$? For example, in the first term of the RHS above, we get a blow-up when we plug $t=0$.
How do we formally justify ignoring these blowing-up terms?
Answer: Note that
$$ \operatorname{erfi} (\mathrm{i} \infty) = \frac{2}{\sqrt{\pi}} \int \limits_0^{\mathrm{i} \infty} \mathrm{e}^{t^2} \, \mathrm{d}t = \frac{2 \mathrm{i}}{\sqrt{\pi}} \int \limits_0^\infty \mathrm{e}^{-s^2} \, \mathrm{d}s = \mathrm{i} \, . $$
Therefore we can write
$$ \operatorname{erfi}(x) = \mathrm{i} + \frac{2}{\sqrt{\pi}} \int \limits_{\mathrm{i} \infty}^x \mathrm{e}^{t^2} \, \mathrm{d} t \, .$$
Now we can integrate by parts without any problems and since $\mathrm{i}$ is completely negligible compared to $\operatorname{erfi}(x)$ in the limit $x \to \infty$ , we obtain the desired expansion (with $(-1)!! \equiv 1$):
$$ \operatorname{erfi}(x) \sim \frac{\mathrm{e}^{x^2}}{\sqrt{\pi} \, x} \sum \limits_{k=0}^\infty \frac{(2k-1)!!}{(2 x^2)^k} \, , \, x \to \infty \, . $$
Comment: It does not have one. In every step of the derivation the imaginary part of the remaining integral is $-\mathrm{i}$, so the exact expression for $\operatorname{erfi}(x)$ remains real at all times.
Comment: I know you are saying that $i$ is negligible compared to erfi($x$), but how can erfi($x$) have an imaginary part for real $x$?

Asymptotic expansion of Erfi(x)


Trend stationary and difference stationary simultaneously

Question: Can a time series be both trend stationary and difference stationary at the same time? In this situation how do we approach the problem?
Comment: Michael Chernick notes correctly that differencing removes polynomial trends, but it also introduces unit root MA terms, which should be avoided. Thus polynomial (including linear) trends should not be removed by differencing. Differencing should only be used for removing stochastic trends (unit roots).
Comment: What are the definitions?  If you mean, stationary after removing trend and stationary after differencing then the answer is yes.  If you have a series n the ARIMA class kth order differencing can remove a kth order polynomial trend. The operation (transformation) can make the resulting model stationary and it does remove trends of a certain kind. But I am not familiar with your terminology and others may be also.  Please clarify.
Answer: It certainly is possible that we may have a process that has both a deterministic time trend and a unit root, for example:
$$y_t = \delta t + y_{t-1} + u_t \tag{1}$$
with $u_t$ being white noise, $u_t \sim WN(0, \sigma^2_u)$.
To achieve second-order stationarity in the above case, we first subtract the first lag from both sides (and we do not apply the Diferrence operator on both sides), so we get
$$\Delta y_t = \delta t  + u_t \tag{2}$$
(NOTE: that if we have applied the first-diference operator in the first step instead of just subtracting $y_{t-1}$ from both sides we would obtain the expression
$$\Delta y_t = \Delta\delta t + \Delta y_{t-1} + \Delta u_t = \delta + \Delta y_{t-1} + (u_t-u_{t-1}) \tag{3}$$
which may remove the deterministic time trend but it leaves us with a unit root in first-differences and introduces an MA term complicating matters. So this approach is to be avoided.)
After obtaining $(2)$ (which does not involve estimation) one can visually check whether the series appears to contain a deterministic time trend. If it does, we then de-trend by estimating the $\delta$ coefficient and use the residuals from this estimation step as our second-order stationary series... which, strictly speaking, it is not second-order stationary, due to the fact that we have to estimate $\delta$. But the deviation from stationarity is bearable.
Assume we do it by applying OLS to $(2)$ with a sample of size $T$. Then we will get
$$\hat \delta = \delta + \sum_{s=1}^T\left(\frac{s}{\sum_{s=1}^T s^2}\right)u_s$$
and the residual series will be
$$\hat u_t = u_t - t\cdot  \frac {\sum_{s=1}^Tsu_s}{\sum_{s=1}^Ts^2} = \left (1-\frac {t^2}{\sum_{s=1}^Ts^2}\right)u_t - t\cdot  \frac {\sum_{s\neq t}^Tsu_s}{\sum_{s=1}^Ts^2}$$
The variance of the residual will then be
$$\text{Var}(\hat u_t) = \sigma^2_u\cdot \left[\left(1-\frac {t^2}{\sum_{s=1}^Ts^2}\right)^2 + \frac{t^2\sum_{s\neq t}^Ts^2}{\left(\sum_{s=1}^Ts^2\right)^2}\right]$$
which thankfully simplifies to
$$\text{Var}(\hat u_t) = \sigma^2_u\cdot \left(1-\frac {t^2}{\sum_{s=1}^Ts^2}\right) $$
So the variance of the residual series is not constant but depends on $t$. The relative difference in the variances of each element of the series depends also on the sample size. For example for a sample size of $T=50$ observations, the variance of $u_{50}$ is approximately $6$% lower than the variance of $u_1$ (the latter being the closest to the true variance of the white noise term). For a sample size of $T=1000$ it is just $0.3$% smaller.
Also the term involving $t$ converges to zero rather fast (since the denominator is one power of $T$ greater than the numerator).  Analogous results hold also for pair-wise covariances.
We conclude that treating the residual series as second-order stationary will not lead to misleading inference, because the deviation from actual stationarity is small (except perhaps for very small samples).
Comment: @jmb You may want to consult pp 64-67 of Hamilton's Time Series Analysis. In the case above we have introduced an MA(1) component with coefficient equal to 1, which makes the MA(1) non-invertible, meaning that there is no AR($\infty$) representation for it. But then, how are you going to forecast the series based on its past realizations?
Comment: This is good and supports Richard Hardy's statement. My comment was meant to be prefaced by the time series being in the ARIMA class. So the deterministic linear term in your example would eliminate  the series from being ARIMA. If the process is ARIMA the proper number of differences will remove stochastics trend and can make the model stationary (at least 2nd order stationary). Now my mistake is that I am inconsistent in my claim.  There was no deterministic trend to remove from my ARIMA model so it doesn't do both.
Comment: @AlexcosPapadopoulos Your example shows a time series model which is initially nonstationary because of a first order autoregressive term with the AR parameter =1.  The first step is just an algebraic manipulation.  The second step takes the model which has the form of a linear regression in t.  Delta can be estimated by least squares. Then you say that the series becomes the estimated residuals from the detrending.  Does that make it stationary? The key demonstration is to take a first difference before doing anything else. But does that actually give you the last equation that you display?
Comment: i am now not sure that your example achieves what Richard Hardy claimed.
Comment: @MichaelChernick Thanks for the feedback. I am looking into it to see what may need to be changed in my answer.
Comment: @MichaelChernick Thank you for insisting on this one. I have modified my answer and gained a few insights while doing it.
Comment: @AlexPapadopoulos I think you filled in the gaps and answered my questions. Since in my answer I made the restriction that the process was in the ARIMA class I am pointing out that your examples are not ARIMA models.  But the question never made that restriction so this answer is fine and probably adds a lot for the OP as well as explaining Richard Hardy's point.
Comment: @MichaelChernick and Alecos, I am glad I could contribute my two cents to this discussion. Alecos, your answer is great -- as always!
Comment: @RichardHardy Thanks Richard, I do appreciate your kind words.
Comment: @Alecos Papadopoulos Could you explain a bit more why introducing the MA-term "complicates matters"? I tried to read about this and found it might render the process "non-invertible" which can create issues with identifiability, but I don't really understand this. Thanks!
Comment: @Alecos Papadopoulos Excellent, thank you so much for the swift reply!


request with json data and multipart using afnetworking

Question: I am using AFNetworking 2.0 and need to construct the request to my server with json data and multi images at the same time.
What i could image is the request will be in the following structure:
Content-Type    multipart/form-data;boundary=abc

--abc

{"title":"Product discussion","attendee":[{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"}]}

--abc

Content-Disposition: form-data; name="img"
Content-Type: image/png

...image data...

--abc--

Here is only the simplified structure. The real meeting data is much more complex with more hierarchies, so i think it's better to use json.
However I don't know how can build such data structure using afnetworking e.g.
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];

[parameters setValue:meeting.title forKey:@"title"];

NSMutableArray *attendeeList = [[NSMutableArray alloc]init];
for(Attendee *attendee in meeting.attendeeList)
{
    NSMutableDictionary *attendeeDictionary = [[NSMutableDictionary alloc]init];
    [attendeeDictionary setValue:attendeeID forKey:@"id"];
    [attendeeList addObject: attendeeDictionary];
}
[parameters setValue:attendeeList forKey:@"attendee"];

httpClient.requestSerializer = [AFJSONRequestSerializer serializer];

[httpClient POST:@"createappointment.php" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    UIImage *image = [UIImage imageNamed:@"image.png"];
    NSData *imageData = UIImagePNGRepresentation(image);
    [formData appendPartWithFileData:imageData
                                    name:@"img"
                                fileName:@"img.png"
                                mimeType:@"image/png"];
    }

 } success:....

but the code seems to ignore the AFJSONRequestSerializer and puts the meeting title and attendee IDs in the form of the POST array.
On the server side is PHP. Normally I can get the image from $_FILE and the json data from php://input + json_decode, but in this case i don't know, what the the best way to parse the above structure?
Is there anyone also met such requirement and how to solve it correctly on iOS as well as server side?
Answer: So in this case you get it from $_POST instead of $_FILES or you can use file_get_contents("php://input")
Comment: I cannot put the json data in $_POST, and "php://input is not available with enctype="multipart/form-data"(http://php.net/manual/en/wrappers.php.php)


how to make user choose from one value in a list

Question: In line 5, how do I make it in such a way, that if preference == one of the fruits and not all? Also, the input returns a string right? How can I make the user choose a value from the variable? I'm quite new so forgive me if i'm making dumb mistakes, thanks!
fruits = ['banana', 'pineapple', 'strawberry', 'mango']
preference = input('What fruit would you like?')
if preference == 'nothing':
    print('Sorry to hear that, goodbye!')
elif preference == fruits:
    print('That\'s great! I\'ll be back in a moment with your order.')
    if preference == preference[0]:
        print(f'Here you go! That would be {len(preference[0])} dollars')
    elif preference == preference[1]:
        print(f'Here you go! That would be {len(preference[1])} dollars')
    elif preference == preference[2]:
        print(f'Here you go! That would be {len(preference[2])} dollars')
    elif preference == preference[3]:
        print(f'Here you go! That would be {len(preference[3])} dollars')
    print('Thank you for your purchase! Goodbye!')
else:
    print(f'Here\'s our menu! We have {fruits[1:3]} and {fruits[-1]} here.')

Answer: Use the keyword in:
elif preference in fruits:

And you should also check each preference to each value in fruits. Not to itself. Same thing applies to printing the length of your preference. You indexed your preference which means if your preference was "banana" it would take the 0th index or "b". Which will always have a value of 1. Corrected code:
fruits = ['banana', 'pineapple', 'strawberry', 'mango']
preference = input('What fruit would you like?')
if preference == 'nothing':
    print('Sorry to hear that, goodbye!')
elif preference in fruits:
    print('That\'s great! I\'ll be back in a moment with your order.')
    if preference == fruits[0]:
        print(f'Here you go! That would be {len(preference)} dollars')
    elif preference == fruits[1]:
        print(f'Here you go! That would be {len(preference)} dollars')
    elif preference == fruits[2]:
        print(f'Here you go! That would be {len(preference)} dollars')
    elif preference == fruits[3]:
        print(f'Here you go! That would be {len(preference)} dollars')
    print('Thank you for your purchase! Goodbye!')
else:
    print(f'Here\'s our menu! We have {fruits[1:3]} and {fruits[-1]} here.')

That means your don't need to check which fruit it was at all! That will make it simpler for you. Like this:
fruits = ['banana', 'pineapple', 'strawberry', 'mango']
preference = input('What fruit would you like?')
if preference == 'nothing':
    print('Sorry to hear that, goodbye!')
elif preference in fruits:
    print('That\'s great! I\'ll be back in a moment with your order.')
    print(f'Here you go! That would be {len(preference)} dollars')
    print('Thank you for your purchase! Goodbye!')
else:
    print(f'Here\'s our menu! We have {fruits[1:3]} and {fruits[-1]} here.')

Comment: Why doesn't it work still? It doesn't display the price
Comment: I have updated my answer for another bug.
Comment: oh my god! Thank you so much! That is so much more shorter and simpler, thanks!!<3
Comment: Oops, I almost forgot, 1 last question if you don't mind. The last line returns
Here's our menu! We have ['pineapple', 'strawberry'] and mango here.
Why? And how do I make it not display the brackets?
Comment: To join the list with a separator, let's say ", ", we need to do this: ```", ".join(list)```. This will return 'pineapple, strawberry'.
Comment: So for your code, ```", ".join(fruits[1:3])``` instead of ```fruits[1:3]```
Comment: Ah I see! Thank youu!
print(f"Here\'s our menu! We have {', '.join(fruits[1:3])} and {''.join(fruits[-1])} here.")
Comment: Yes, but not completely. You don't need to join ```fruits[-1]```, because that is referring to a single item in the list, which would print out normally.
Answer: # your code goes here

fruits = ['banana', 'pineapple', 'strawberry', 'mango']
preference = input('What fruit would you like?')
if preference == 'nothing':
    print('Sorry to hear that, goodbye!')
elif preference in fruits:
    print('That\'s great! I\'ll be back in a moment with your order.')
    if preference == fruits[0]:
        print(f'Here you go! That would be {len(fruits[0])} dollars')
    elif preference == fruits[1]:
        print(f'Here you go! That would be {len(fruits[1])} dollars')
    elif preference == fruits[2]:
        print(f'Here you go! That would be {len(fruits[2])} dollars')
    elif preference == fruits[3]:
        print(f'Here you go! That would be {len(fruits[3])} dollars')
    print('Thank you for your purchase! Goodbye!')
else:
    print(f'Here\'s our menu! We have {fruits[1:3]} and {fruits[-1]} here.')

you need to use in to check if value is inside a list or not.
also, fruits is a list where you are checking the preference, so use fruits instead of preference
Comment: So I change the 5th line to 'fruits in preference' ? I did this but it said 'Expected type 'str', got 'list[str]' instead'.
Also why isn't the price displayed?
Comment: you are checking if the input preference is inside a fruits list or not.  so use `if preference in fruits` not `fruits in preference`
Comment: Ah, I see. Thank you so much!


É possível usar um Strings.xml específico para a versão do Android?

Question: Eu apliquei uma cor diferente a determinadas palavras dentro de algumas TextViews com a TAG .
Consegui chegar a este resultado depois de uma busca pela internet. O problema é que este recurso só funciona para versões mais atuais do Android, em versões mais antigas a palavra sequer é exibida.
Tentando evitar isto, pensei em fazer uma versão do strings.xml para versões mais novas e uma para versões mais antigas do Android.
Seria algo assim:
Versão mais nova strings.xml:
<string name="txt_fone">Informe seu telefone com DDD</string>
<string name="txt_email">Informe seu email</string>

Versão mais antiga strings.xml:
<string name="txt_fone">Informe seu telefone com DDD</string>
<string name="txt_email">Informe seu email</string>

É possível carregar um XML específico para a versão do Android, ou se existir, algum comando ou TAG condicional que opte por um ou outro código?
Answer: Sim, é possível.
Os strings declarados em strings.xml são resources e tal como qualquer resource eles podem ter declarações alternativas por versão/características do dispositivo.
Crie um novo strings.xml para a versão(API) a partir da qual quer usar .
Dispositivos com API inferiores usarão o strings.xml padrão, os com API igual ou superior usarão o novo strings.xml.


Why is it that triggering a function from within a view updates the @State variable, but triggering that same function from another view does not?

Question: As I understand it has something to do with the fact that @State variables cannot be updated from outside a view. But I'm triggering a function within that same view, just from another view.
In my head this should work, but keen to understand why it doesn't and best way to update myValue from View2.swift
View1.swift
struct View1: View{
...

@State var myValue:Double

func myFunc(){

//Chang value of myValue
}

var body: some View{

Button{

myFunc() //clicking this updates myValue

}

...

View2.swift
...

Button{

View1().myFunc() //doesn't update value even though runs same function?

}

...

Comment: Since SwiftUI views are structs, and therefore immutable, new instances are created all the time. Whenever your state property changes, SwiftUI creates a new view instance to show the updated value.  However, you would never create a new view instance outside of the view hierarchy. Ie when you say `HStack { View1() }` you are creating a new instance of the view in the view hierarchy and this is completely normal. Creating a new instance in a button action closure is pointless; the view isn't shown and will be discarded as soon as the closure exits
Comment: You are creating a new *instance* of the view `View1()` and calling the function on that. This is not the same instance of the view that you are seeing. You probably need a model object with an observable property that you can share between the two views.
Comment: Thanks @Paulw11, I'll look into models. To help my understanding, in what scenario might one want to create a new instance of a view?
Answer: This was solved using ObservableObjects.
Comment: That's ok for model data but for view data I recommend sticking with `@State` and learning about `@Binding`, these give object-like semantics to structs.
Comment: I was really struggling to get @Binding working with TabView.


if statement that skips over a field if it has a string in it. Netsuite/ javascript

Question: This is a Netsuite sales order. I created a loop that cycles through a list of line items and a variable that grabs the value of a certain field. I just need to create an if statement that will "continue" the script over if the field already has a string in it. Here is what I have so far. This is a portion of a larger script for context.
var duplicateOrder = loadRecord.getlineItemValue('custcol_transfer_order_sale', itemCounter);
      //if transfer order field is already populated then there doesn't need to be a second transfer
    if ((duplicateOrder) !== null || (duplicateOrder) !== ""){
        continue;
    }

Answer: You're currently checking if duplicateOrder is empty and then continuing. If I'm understanding correctly, you'd like to continue when it's not empty.
For that, you just need to check if duplicateOrder is "truthy", like so:
if (duplicateOrder) {
    continue;
}

See also "falsy"
Comment: I forgot to add the ! in:                                                                                if ((duplicateOrder) !== null || (duplicateOrder) !== ""){
        continue;
}
Comment: And what is the problem you're seeing now?
Comment: TypeError: Cannot find function getlineItemValue in object nlobjRecord.
Comment: JavaScript is case-sensitive. The function is `getLineItemValue`, not `getlineItemValue`
Comment: You will also need to make sure you are passing in the required arguments for the call. `objRec.getLineItemValue(sublistId, fieldId, lineNumber)`.


Power Series Solution for an ODE which has trigonometric coefficient functions

Question: The ODE for which we seek a power series solution is:
$$y''+ \cos(x)y' + x\sin(x)y = 0,\hspace{0.4cm} y(0) = 1,\hspace{.1cm} y'(0) = 0$$
I need to find the partial sum up to five, from the initial conditions I know $a_0=1$ and $a_1=0$, I also know I need to find the recurrence relation to get the coefficients but therein lies my issue.
I'm as far as:
$$\sum_{n=2}^{\infty}n(n-1)a_n x^{n-2} + \cos (x)\sum_{n=1}^{\infty} n a_n x^{n-1} + x\sin(x)\sum_{n=0}^{\infty}a_nx^n = 0$$
I believe I need to use the power series representation of cosine and sine then take the Cauchy product to simplify. Is this the right track? If so could someone help me understand how exactly the algebra of the Cauchy product in this case works out, I've only ever used it in the simple cases before.

So I figured I'd update this post so anyone who may have a similar question somewhere down the line isn't left hanging. Thanks again to Ian for helping with this.
First of all rather than using the full series representation of sine and cosine you really only need:
$$\cos (x) = 1 - \frac{x^2}{2} + \frac {x^4}{24} + ..., \hspace{0.4cm} x\sin (x) = x^2 - \frac {x^4}{6}+ ...$$
You only need these terms because you're looking for the partial sum up to five. Now bear with me the next part is long. Substitute this along with the power series for $y =\sum_{n=0}^{5}a_nx^n$ again just use the first five terms. Then:
\begin{align}
y & = (2a_2 +6a_3 +12 a_$x^2 + 20a_3x^3)\\
&\hspace{.4cm} +(1 - \frac{x^2}{2} + \frac {x^4}{24})(2a_2x+3a_3x^2 +4a_4x^3+5a_5x^4)\\
&\hspace{.4cm} +(x^2-\frac{x^4}{6})(1+ a_2x^2+a_3x^3+a_4x^4+a_5x^5)
\end{align}
Now just collect the constants on like-ordered terms, for example:
$$x^0 \to 2a_2 = 0 \Rightarrow a_2 = 0 $$
or
$$x^2 \to 12a_4 +3a_3 +1 + a_2 = 0 \Rightarrow a_4 = \frac {-1}{12} $$
Just remember to do them in order since the constants "build". That is $a_0, a_1, \text{and } a_2 \text{ are needed to get } a_3 $. Finally just stick the constants into $y = \sum_{n=0}^{5}a_nx^n$ and then you can use it to approximate some value for $y(x)$.
Sorry about the sort of messy formatting, I'm not overly familiar with MathJax formatting.
Comment: Formally you need the Cauchy product but informally this just means distributing the multiplication and collecting all terms of a given order. Doing this by hand for a few orders would probably help you guess a recurrence.
Comment: Okay, I'll give that a try! Thanks for the suggestion.
Comment: That worked, wasn't able to derive the formula for the recurrence as nicely as other problems but I got the necessary coefficients for the partial sum. Thanks again Ian.
Answer: Consider:
$$\ddot{x}=k\sin(t)\,x - f\dot{x}$$
What I found was to rewrite $\sin$ from its usual power series, then take the Cauchy product. That is,
$$\sin(t) = \sum_{n=0}^\infty\frac{(-1)^n\,t^{2n+1}}{(2n+1)!} = \sum_{n=0}^\infty\frac{(-1)^{\frac{n-1}{2}}\,t^{n}}{n!}\cdot\frac{1-(-1)^n}{2}$$
So our ODE becomes
\begin{align}
\sum_0^\infty(n+2)(n+1)a_{n+2}\,t^n + f\sum_0^\infty(n+1)a_{n+1}\,t^n - k\left(\sum_{n=0}^\infty\frac{(-1)^{\frac{n-1}{2}}\,t^{n}}{n!}\cdot\frac{1-(-1)^n}{2}\right)\left(\sum_{m=0}^\infty a_{m}\,t^m\right) &= 0 \\[2em]
\xrightarrow{\text{Cauchy product}} \sum_{n=0}^\infty\left[(n+2)(n+1)a_{n+2} + f(n+1)a_{n+1} - k\sum_{i=0}^na_ib_{n-i}\right]t^n &= 0 \tag{1}
\end{align}
where $b_j$ is the coefficient in the sine sum,
$$b_j = \frac{(-1)^{\frac{j-1}{2}}}{j!}\cdot\frac{1-(-1)^j}{2}$$
Then the recurrence relation is had from $(1)$:
$$a_{n+2} = \frac{k(\sum_{i=0}^n a_ib_{n-i}) - f(n+1)a_{n+1}}{(n+2)(n+1)}$$
Explicitly,
\begin{align}
n&=0:\quad a_2 = \frac{-fa_1}{2}\\[1em]
n&=1:\quad a_3 = \frac{ka_0-2fa_2}{6}\\[1em]
n&=2:\quad a_4 = \frac{ka_1-3fa_3}{12}\\[1em]
n&=3:\quad a_5 = \frac{k(a_2-a_0)-4fa_4}{20}\\[1em]
&\dddot\\
\end{align}


rank$({A-\lambda I_n})^k$=rank$(B-\lambda I_n)^k$ iff $A$ is similar to $B$

Question: Let $A,B \in M_n(\mathbb{C})$. Prove that rank$({A-\lambda I_n})^k$=rank$(B-\lambda I_n)^k$ for every $k \in \mathbb{N}$ and $\lambda \in \mathbb{C}$ iff they are similar.
I know that every matrix has a Jordan form since it's over the field of complex numbers and that they are similar to their Jordan form, but I do not know where to go from there. Any hints on where to start?
Answer: Hints:

Show that $(A-\lambda I_n)^n$ and $(B-\lambda I_n)^n$ are similar.
Show that $\text{rank}(U)=\text{rank}(V)$ if $U$ and $V$ are similar.


Adding composer to update core

Question: I'm using a site created on Pantheon and now I'm not using pantheon.
So the core is not installed with composer.
Now I want to upgrade core with composer but I don't understand how.
I've some modules installed with composer, so I try to add drupal/core :
compose require "drupal/core"

It's ok, but if I try to this, the aren't upgrades:
composer update drupal/core --with-dependencies

I've core 8.6.1 and I wanto to update to 8.6.2.
Thanks
Comment: `So the core is not installed with Composer. Now I want to upgrade core with Composer.` What about installing it with Composer again?
Comment: What do you mean? I try to add drupal/core but, after this, it does not find upgrades
Comment: What do you mean with `it does not find upgrades`?
Comment: That is if i run "composer update "drupal/core" it tells me that there is nothing to install or upgrade
Answer: It is probably due to how the drupal/core line in your composer.json file is defined.  It probably has the version locked to 8.6.1.  So the update is saying: You are already at the version you requested.  There are no updates.
I would try doing the following:
composer require drupal/core:8.6.2 --update-with-dependencies

This will tell composer to use that version and ignore the version info in the composer.json file.
Comment: It doesn't work. If I run that command, composer returns me: Nothing to install or update
Comment: What does the entry for drupal/core in your composer.json line say? Also, do you have the drupal repository added in your composer.json file.  E.g.:
 "repositories": {
    "drupal": {
      "type" : "composer",
      "url" : "https://packages.drupal.org/8"
    },
Comment: yes, repo is there, because I've installed some modules with composer. Here is the compose.json: require": {  "drupal/core": "8.6.2" },
    "replace": {
        "drupal/core": "^8.6"
    },
Comment: Hmm, I would remove the replace statement since this is not a forked version and change the 8.6.2 version to 8.6.1.  Composer does not use Drupal version info just the composer version.  Since it says 8.6.2, I think it assumes you have 8.6.2 installed.  Then try the version specific require command.
Comment: Removing the replace statement I've upgrade the core. Thanks a lot. Some guide suggests to upgrade also symfony: have I to do this?
Comment: If you used one of the with-dependencies options, this should have updated the symfony and other components.  You can check this with the composer show command.  I think it should be V3.4.17 for most symfony.things.
Comment: I've 3.4.14. Is it wrong? If I remove vendor and then run "composer install", it remains on 3.4.14

Adding composer to update core