Particle filter for estimation of static parameters

Question: I am considering particle filtering methods for the estimation of static and dynamic parameters. For the static parameters $\theta$, Liu and West (page 7, equation 3.1) describe an "artificial" perturbation:
$$
\theta_{t+1} = \theta_t + \zeta_{t+1}
$$
$$
\zeta_{t+1} \sim N(0, W_{t+1})
$$
in order to generate a sample from $p(\theta_{t+1} | D_t)$ before updating the sample based on the likelihood of the new data at time $t+1$ to obtain a sample from $p(\theta_{t+1} | D_{t+1})$. Note that the notation $\theta_t$ is used to mean that it denote the time $t$ posterior of $\theta$ and not that $\theta$ is a time-varying parameter.
Now adding this artificial perturbation increases the variance of the sample and so the estimate of the true posterior is over-dispersed. They describe a method in which you may perturb the samples without increasing the sample variance. That is, so:
$$
V(\theta_{t+1} | D_t) = V(\theta_t | D_t) + W_{t+1} + 2C(\theta_t, \zeta_{t+1} | D_t) = V(\theta_t | D_t)
$$
which implies:
$$
C(\theta_t, \zeta_{t+1} | D) = -W_{t+1}/2
$$
(this is all from page 9 of Liu and West). They then state that approximating joint normality of $(\theta_t, \zeta_{t+1} | D_t)$ then implies:
$$
\theta_{t+1} | \theta_t \sim N(A_{t+1} \theta_t + (1-A_{t+1}) \bar{\theta_t}, (1-A_{t+1}^2)V_t)
$$
where:
$$
A_{t+1} = I - W_{t+1}V_t^{-1}/2
$$
and the idea is that if $p(\theta_t | D_t)$ has finite mean $\bar{\theta}_t$ and variance matrix $V_t$, then the mean and variance matrix of $p(\theta_{t+1} | D_t)$ is also $\bar{\theta}_t$ and $V_t$.
My question:
How do you derive this form of $\theta_{t+1} | \theta_t$? It makes sense but is not obvious (to me) how to get there, any advice whatsoever would be appreciated.
Answer: Answering my own question based on the help from @Taylor. A very nice proof of the results used is here, from which I have taken some notation.
For a multivariate normal vector $\boldsymbol{Y} \sim N(\boldsymbol{\mu}, \boldsymbol{\Sigma})$, consider partitioning
$\boldsymbol{\mu}$ and $\boldsymbol{Y}$ into:
\begin{equation}
\begin{aligned}
\boldsymbol\mu =
\begin{bmatrix}
 \boldsymbol\mu_1 \\
 \boldsymbol\mu_2
\end{bmatrix}
\end{aligned}
\qquad \text{and} \qquad
\begin{aligned}
\boldsymbol{Y}=
\begin{bmatrix}
\boldsymbol{y}_1 \\
\boldsymbol{y}_2
\end{bmatrix}
\end{aligned}
\end{equation}
with a similar partition of $\boldsymbol{\Sigma}$ into:
$$
\begin{bmatrix}
\boldsymbol{\Sigma}_{11} & \boldsymbol{\Sigma}_{12} \\
\boldsymbol{\Sigma}_{21} & \boldsymbol{\Sigma}_{22}
\end{bmatrix}.
$$
The conditional distribution of the first partition given the second is then:
$$
\boldsymbol{y}_1 | \boldsymbol{y}_2 \sim
N(\boldsymbol{\mu}_1 + \boldsymbol{\Sigma}_{12} \boldsymbol{\Sigma}_{22}^{-1} (\boldsymbol{y}_2 - \boldsymbol{\mu}_2),
\boldsymbol{\Sigma}_{11} - \boldsymbol{\Sigma}_{12}{\boldsymbol{\Sigma}_{22}}^{-1} \boldsymbol{\Sigma}_{21}).
$$
In this problem:
$$
\begin{aligned}
C(\boldsymbol{\theta}_{t+1}, \boldsymbol{\theta}_t | D_t)
&= E(\boldsymbol{\theta}_{t+1} \boldsymbol{\theta}_t^\intercal | D_t) - E(\boldsymbol{\theta}_{t+1} | D_t)E(\boldsymbol{\theta}_t | D_t)^\intercal \\
&= E((\boldsymbol{\theta}_t + \boldsymbol{\zeta}_{t+1}) \boldsymbol{\theta}_t^\intercal | D_t) - \bar{\boldsymbol{\theta}_t}\bar{\boldsymbol{\theta}_t}^\intercal \\
&= E(\bar{\boldsymbol{\theta}_t}\bar{\boldsymbol{\theta}_t}^\intercal + \boldsymbol{\zeta}_{t+1} \boldsymbol{\theta}_t^\intercal | D_t) - \bar{\boldsymbol{\theta}_t}\bar{\boldsymbol{\theta}_t}^\intercal \\
&= E(\bar{\boldsymbol{\theta}_t}\bar{\boldsymbol{\theta}_t}^\intercal | D_t) + E(\boldsymbol{\zeta}_{t+1} \boldsymbol{\theta}_t^\intercal | D_t) - \bar{\boldsymbol{\theta}_t}\bar{\boldsymbol{\theta}_t}^\intercal \\
&= (\mathbf{V}_t + \bar{\boldsymbol{\theta}_t}\bar{\boldsymbol{\theta}_t}^\intercal ) + (-\frac{1}{2} \mathbf{W}_{t+1} + 0) - \bar{\boldsymbol{\theta}_t}\bar{\boldsymbol{\theta}_t}^\intercal \\
&= \mathbf{V}_t -\frac{1}{2} \mathbf{W}_{t+1} \\
\boldsymbol{\mu}_1 &= \boldsymbol{\mu}_2 = \bar{\boldsymbol{\theta}}_t \\
\boldsymbol{\Sigma}_{11} &= \boldsymbol{\Sigma}_{22} = \mathbf{V}_t \\
\boldsymbol{\Sigma}_{12} &= \boldsymbol{\Sigma}_{21} = \mathbf{V}_t -\frac{1}{2} \mathbf{W}_{t+1}
\end{aligned}
$$
and so the conditional normal evolution is:
$$
\boldsymbol{\theta}_{t+1} | \boldsymbol{\theta}_t \sim N(\bar{\boldsymbol{\theta}}_t + (\mathbf{V}_t -\frac{1}{2} \mathbf{W}_{t+1}) \mathbf{V}_t^{-1} (\boldsymbol{\theta}_t -\bar{\boldsymbol{\theta}}_t),
\mathbf{V}_t - (\mathbf{V}_t -\frac{1}{2} \mathbf{W}_{t+1}) \mathbf{V}_t^{-1} (\mathbf{V}_t -\frac{1}{2} \mathbf{W}_{t+1}))
$$
which simplifies to:
$$
\boldsymbol{\theta}_{t+1} | \boldsymbol{\theta}_t \sim N(\mathbf{A}_t \boldsymbol{\theta}_t + (\mathbf{I} - \mathbf{A}_t) \bar{\boldsymbol{\theta}}_t,
(\mathbf{I} - \mathbf{A}_t^2) \mathbf{V}_t)
$$
where:
$$
\mathbf{A}_t = \mathbf{I} - \frac{1}{2} \mathbf{W}_{t+1} \mathbf{V}_t^{-1}.
$$
Answer: This follows from a property of multivariate normal random vectors. Here's a link:
https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Conditional_distributions
Comment: Didn't know/forgot about that result. I've worked it all out now - thanks!


Finding limits of integration for polar equations

Question: I'm learning how to find the area within polar equations. I know that the integral is: $\frac12\int^{\beta}_{\alpha}f(\theta)^2\ d\theta$. But, how are $\alpha$ and $\beta$ found? Is it something that there is only one method for? Or, are there different strategies to use?
If the answer is that there is just one way, what is it? And, if there is no one-fits-all method, but multiple things to look at - what are they?
Or, is there no good answer for this - and you just need to think about what they could possibly be each time?
Answer: Well, what you choose for $\alpha$ and $\beta$ is like asking what you should choose for $a$ and $b$ in a normal Cartesian integral $\int_{a}^{b} f(x)dx$. It depends on what section of $f(\theta)$ you want to integrate, that is, find the area of.
If you want to integrate around the unit circle, integrating from $0$ to $2\pi$ should be suitable. If you want to integrate, for instance, the area contained between two functions, you'd find $\alpha$ and $\beta$ where the functions intersect and integrate that.
Hope this helps


Let $A$ be $m\times n$ and $B$ be $n\times m$ matrix over real number with $m<n$.

Question:
Let $A$ be $m\times n$ and $B$ be $n\times m$ matrix over real number
  with $m<n$. Then

$AB$ is always nonsingular.
$AB$ is always singular.
$BA$ is always nonsingular
$BA$ is always singular.

False, Since $A=0$, $B=0$ $\implies$ $AB=0$.
Need not be true. Let $x$ be $1\times n$ matrix. Since, $x x^T\ge 0$
Using the same reasoning 3 can be false.

What is the guarantee that $BA$ is always singular? If $A=x\neq 0, B=x^t.$ Then $BA$ is singular. How do I prove In general?
Answer: $BA \in \mathbb{R}^{n \times n}$,
but $rank(BA)\le \min\{rank(A) ,rank(B) \} \le m<n$
Hence it must be singular.
Answer: Alternatively, $A$ is $m \times n$ and $m<n$ implies $Ax=0$ has a non zero solution, say $x_0$. The same non zero $x_o$ is the solution of $(BA)x=0$ as well! So $BA$ must be singular


Sonar-Runner talks to the local database

Question: I am trying to understand the sonar-runner http://docs.sonarqube.org/display/SONAR/Installing+and+Configuring+SonarQube+Runner. I have a central sonar server that has a database in the same host. As expected I run the sonar-runner from my clients in numerous boxes and expect them to upload data to the sonar cube.
My sonar-project.properties looks something like below
# Required metadata
sonar.projectKey=a:b
sonar.projectName=b-1.0
sonar.projectVersion=1.0

# Comma-separated paths to directories with sources (required)
sonar.sources=lib

# Language
sonar.language=py

# Encoding of the source files
sonar.sourceEncoding=UTF-8
# Host of the sonar url
sonar.host.url=http://myserver:9000/msde/sonar/webapp

I was expecting that my client would perform some analysis and upload data directly to the server using some web services meant for upload. I however see the following in my logs
10:42:00.678 INFO  - Apply project exclusions
10:42:00.682 WARN  - H2 database should be used for evaluation purpose only
10:42:00.682 INFO  - Create JDBC datasource for jdbc:h2:tcp://localhost/sonar
10:42:00.755 INFO  - Initializing Hibernate

Question

Should I be configuring the details of the database in the sonar-project.properties? I was expecting it to use some webservice from the sonar url to upload metrics but there are several problems with exposing the database details. I wanted the database to be internal to the server and not accessed by various clients.
This also means that I should place the database details in various property files in several projects so the cost of changing the central database details is huge.
Answer: You need to edit the $SONARQUBE_RUNNER_HOME/conf/sonar-runner.properties file to point to the correct database instance. And this is the only file you need to do that for all your projects.
Comment: The SonarQube Runner needs to talk to both the database and the web server.
Comment: So why does it need both the sonarhosturl and the dburl? If it is directly talking to the db, why does it need sonar.host.url?
Answer: If you are using MySQL, in the HOME_SONAR_RUNNER\conf\sonnar-runner.properties file, you have to uncomment the line that relates with MySQL, leaving the line as this:

sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8

In the same file, don't forget to comment next:

#sonar.host.url=http://localhost:9000

Save the file and run again.


trace of the product of two projection matrices

Question:
If $P_{i}=\frac{\alpha_{i}\otimes\beta_{i}}{(\alpha_{i},\;\beta_{i})}=\frac{\alpha_{i}\beta_{i}^{T}}{\alpha_{i}^{T}\beta_{i}}$, where $P_{i}$ are rank-1 projection matrices and $(\alpha_{i},\;\beta_{i})\neq0$, then how we can find $\text{Tr}(P_{1}P_{2})$?

As I understand
$$
\text{Tr}(P_{1}P_{2})=\text{Tr}\left(\frac{\alpha_{1}\beta_{1}^{T}}{\alpha_{1}^{T}\beta_{1}}.\frac{\alpha_{2}\beta_{2}^{T}}{\alpha_{2}^{T}\beta_{2}}\right),
$$
but the answer should be
$$
\text{Tr}(P_{1}P_{2})=\frac{(\alpha_{1},\;\beta_{2})(\alpha_{2},\;\beta_{1})}{(\alpha_{1},\;\beta_{1})(\alpha_{2},\;\beta_{2})}.
$$
Comment: What have you tried? This is not hard if you are able to compute $P_1 P_2$ first.
Answer: Using the cyclic property of the trace, that is $\text{Tr}(AB) = \text{Tr}(BA)$ (choose $A = \alpha_{1}\beta_{1}^{T}\alpha_{2}$ and $B = \beta_2^T$. (The denominator is just a scalar $k =\alpha_{1}^{T}\beta_{1}\alpha_{2}^{T}\beta_{2} $ so it doesn't affect the trace
$$\text{Tr}(P_{1}P_{2})=\text{Tr}\left(\frac{\beta_{2}^{T}\alpha_{1}}{\alpha_{1}^{T}\beta_{1}}.\frac{\beta_{1}^{T}\alpha_{2}}{\alpha_{2}^{T}\beta_{2}}\right)$$
Notice each term in the numerator and denominator is a scalar, so the whole quantity inside the trace is a scalar and we know that $\text{Tr}(x) = x$ for a scalar $x$, hence we can omit the trace,
$$\text{Tr}(P_{1}P_{2})=\frac{\beta_{2}^{T}\alpha_{1}}{\alpha_{1}^{T}\beta_{1}}.\frac{\beta_{1}^{T}\alpha_{2}}{\alpha_{2}^{T}\beta_{2}}$$
and that's about it.


Correlation of $X$ and $Y$ and Correlation of $\frac{1}{X}$ and $Y$

Question: Assume the two random variables $X$ and $Y$. The correlation of these two variables is given by the formula:
$\rho_{X,Y} = \frac{Cov(X,Y)}{\sigma_{X}\sigma_{Y}}$
Assume now that the two random variables become $\frac{1}{X}$ and $Y$. In this case the correlation becomes:
$\rho_{\frac{1}{X},Y} = \frac{Cov(\frac{1}{X},Y)}{\sigma_{\frac{1}{X}}\sigma_{Y}}$
My question is what is the relationship between $\rho_{X,Y}$ and $\rho_{\frac{1}{X},Y}$?
Does it hold that $\rho_{X,Y}= -\rho_{\frac{1}{X},Y}$? And if yes then what's the proof?
Comment: In general, it doesn't hold (this can be seen by trying a few examples that have support on more than two points). Indeed it's possible for both of them to have the same sign or even to be equal.
Comment: If you do not know any thing about the distribution of $X$, you can't say anything about the $Var(\frac{1}{x})$ (https://stats.stackexchange.com/q/41896/144441).
Answer: You can also make a simulation in R for 1000 samples and see that your relation doesn't seem to hold:
<code>rm(list=ls())
set.seed(42)

cor_xy=c()
cor_invxy = c()
n=1000

for (i in 1:1000){
  x = rnorm(n)
  y = x+rnorm(n)/2
  cor_xy = cbind(cor_xy,cor(x,y))
  cor_invxy = cbind(cor_invxy,cor(1/x,y))
}
mean(cor_xy)
[1] 0.8941694
mean(cor_invxy)
[1] 0.02236089
</code>
By printing one sample of $X\sim N(0,1)$ and $Y = X + \frac{N(0,1)}{2}$:
$$\hat{\rho}_{X,Y} = 0.8999498$$

$$\hat{\rho}_{\frac{1}{X},Y} = 0.009259998$$
Answer: For example, If $X$ be Rademacher distributed, since $X$ and $1/X$ are the same, the two correlations are even equal, i.e. $\rho_{X,Y}=\rho_{1/X,Y}$.
If $X=\{1,2\}$ uniform and $Y=X$, you'll have $\rho_{X,Y}=1=-\rho_{1/X,Y}$ as well.
If $X=Y$, it won't be hard to find an example satisfying, $1=|\rho_{XY}|>|\rho_{1/X,Y}|$. For the same case, letting $Y=1/X$ would reverse inequality.
There is no general relation.
Comment: Not quite. If $X$ is constant, the correlation isn't defined,
Comment: @NickCox You're right, I've given another example for (-) equality case. My mind slipped towards covariance.


If every bounded set is finite dimensional, every absorbent set is a bornivore.

Question: I stumbled across the following exercise in Wilansky - Modern methods in topological vector spaces:

Let $(X, \mathcal{T})$ be a TVS in which every bounded set is finite-dimensional. Show that every absorbing set is a bornivore.

So far I had one idea of how to approach the problem, but this doesn't seem to work:
Let $B \subseteq X$ be a bounded set in the sense of the von Neumann Bornology such that for every neighbourhood of zero $U$, there exists a $\epsilon > 0$ with $t B \subseteq U$ for every $|t| \leq \epsilon$ and let $A \subseteq X$ be a absorbent set.
For neighborhoods of zero, this statement is clear.
Since $B$ is finite dimensional there exist $n \in \mathbb{N}$ and $b_1, \ldots, b_n \in X$ such that $\mbox{span}(\lbrace b_1, \ldots, b_n \rbrace) = B$ which is a closed linear subspace of $X$. Also $A$ is absorbent, so for each $i = 1, \ldots, n$ there exists $r_i > 0$ with $r_i b_i \in A$ or $b_i \in \frac{1}{r_i} A$ and $\mbox{span}(b_i) \in \mathbb{C}\frac{1}{r_i} A$. But from this on I can't seem to find any $\epsilon > 0$ such that $A$ absorbs $B$.
Edit: I noticed that the definition of a absorbent set differs from our definition. In the book the definition of an absorbent set is: For every $x \in X$ there exists a $r > 0$ such that $t x \in A$ for every $|t| < r$. Where the definition that I use is: For every $x \in X$ there exist a $r > 0$ such that $r x \in A$.
Both definitions are equivalent if $A$ is balanced or convex.
I would be thankful for every hint.
Answer: Hint: reconsider what you mean by "finite dimensional bounded sets". When is a subspace $V \subseteq X$ bounded?
Hint2: let $B \subseteq V$ be bounded. By assumption, it is contained in a finite dimensional subspace $\operatorname{span}(v_1, \ldots, v_n) \subseteq V$. Assume that each of the subspaces $\operatorname{span}(v_i)$ is unbounded. Argue that there is a $c > 0$ such that we have $|\lambda^i| < c$ for every $v \in B$ with basis decomposition $v = \sum_{i=1}^n \lambda^i v_i$.
Comment: A subspace $V \subseteq X$ of a TVS $(X, \mathcal{T})$ is bounded iff $V \subseteq \bigcap_{U \in \mathcal{N}(0)}U$, where $\mathcal{N}(0)$ denotes the set of all neighbourhoods of zero. Since I consider the TVS to be Hausdorff $\bigcap_{U \in \mathcal{N}(0)}U = \lbrace 0 \rbrace$, so every bounded subspace is trivial, every finite set is bounded and from the condition bounded sets are contained in finite dimensional subspaces of $X$, which implies that all bounded sets are trivial and absorbent set contain $0$.
Comment: Your statement on boundedness of subspaces is correct. However, not every bounded set needs to be trivial! Being finite dimensional only means it is contained in a finite dimensional subspace, which itself needs **not** be bounded. Moreover, there is no need to assume the Hausdorff property. I have added another hint.


convert pandas dataframe column of dtype object to date type

Question: I have a dataframe df and has a column by name timeframe of dtype object

column_a
timeframe

One
nov-21

Two
jun-90

I would like to convert timeframe column to date type but this conversion fails with error Out of bounds nanosecond timestamp: 1-11-21 00:00:00
df['timeframe'] = pd.to_datetime(df['Date'])

Answer: Specify the format:
df['timeframe'] = pd.to_datetime(df['timeframe'], format="%b-%y", errors="coerce")

Comment: I get ValueError: unconverted data remains: -1900
Comment: You have values in your dataframe that do not match the "nov-21" format. See the edit. Include the "errors=coerce" to force the invalid values to `NaN`


pthred_exit return variable static vs global scope

Question: I am seeing different behaviors when variable used to get return values using pthread_join is defined gloabal vs static scope. I have included code_snippet here.
Static variables
int main()
{
 static int r1,r2;
 pthread_t t1, t2;
 int i1[] = {1,2};
 int i2[] = {3,4};

 r1 = pthread_create( &t1, NULL, myfn, (void*)i1);
 r2 = pthread_create( &t2, NULL, myfn, (void*)i2);

 pthread_join( t1, (void *)&r1 );
 pthread_join( t2, (void *)&r2 );

 printf("Thread 1 returns: %d\n",r1);
 printf("Thread 2 returns: %d\n",r2);

 return 0;
}
void *myfn( void *intarray )
{
 pthread_t t=pthread_self();
 int *g = (int *) intarray;
 int i=0;
 int d=1;

 for (i=g[0];i<=g[1];i++)
    d*=i;
 fprintf(stderr, "TID=%u %d\n",t, d);
 pthread_exit((void *)d);
}

Return value
TID=3425117952 12
TID=3433510656 2
Thread 1 returns: 2
Thread 2 returns: 12

Global variables
int r1,r2;
int main()
{
 same as above
}
void *myfn( void *intarray )
{
same as above
}

Return value
TID=3425117952 12
TID=3433510656 2
Thread 1 returns: 0  <<<<< it returns 0
Thread 2 returns: 12

Could someone please explain why it behaves differently ?
Answer: Almost certainly it's because the size of int and void * differ on your platform, so when pthread_join() writes a void * value through the int * pointer you gave it, it overwrites adjacent memory.
The different declaration of r1 and r2 changes the layout of the variables enough to change the effect you see.
Casting an int to void * in order to return it is messy; you're better off either allocating space for a result in the main thread and passing that to the thread when it starts, or have the thread allocate the result and return a pointer to it when it finishes.
However, if you insist on the cast to void method, you can fix it by passing the address of an actual void * object to pthread_join and then casting from that to int:
int main()
{
 static int r1,r2;
 void *result;
 pthread_t t1, t2;
 int i1[] = {1,2};
 int i2[] = {3,4};

 r1 = pthread_create( &t1, NULL, myfn, (void*)i1);
 r2 = pthread_create( &t2, NULL, myfn, (void*)i2);

 pthread_join( t1, &result );
 r1 = (int)result;
 pthread_join( t2, &result );
 r2 = (int)result;

 printf("Thread 1 returns: %d\n",r1);
 printf("Thread 2 returns: %d\n",r2);

 return 0;
}


Let $N= \langle(2,(123))\rangle \triangleleft \mathbb{Z}_4 \oplus S_3$ is the factor group cyclic.

Question: Let $N= \langle(2,(123))\rangle  \triangleleft \mathbb{Z}_4 \oplus S_3$
a) What is the order of the factor group
b) Find the order of the element $(3,(12))N$ in $\mathbb{Z}_4 \oplus S_3)/N.$. Is $\mathbb{Z}_4 \oplus S_3/N$ cyclic?
My attempt
For the first part I know the order of the group is $24$ and I belive the order of $N$ would be the order of the lcm of its elements which would be $6$ so then the order would be $\frac{24}{6}=4$
For the second part $(3,(12))N$ I thought it would be $4$ which would be the lcm of the orders after multiplying by N. I concluded that it would not by cyclic since $S_3$ is not abelian thus the group is non abelian so its factor group would not be cyclic. Any help would be appreciated.
Answer: First, let's compute the order of $(2,(1\ 2\ 3))$.
$(2,(1\ 2\ 3))^2 = (2+2,(1\ 2\ 3)^2) = (0,(1\ 3\ 2))$.
$(2, (1\ 2\ 3))^3 = (2+2+2,(1\ 2\ 3))^3 = (2,e)$.
$(2, (1\ 2\ 3))^4 = (2+2+2+2,(1\ 2\ 3)^4) = (0,(1\ 2\ 3))$.
$(2, (1\ 2\ 3))^5 = (2+2+2+2+2,(1\ 2\ 3)^5) = (2,(1\ 3\ 2))$.
$(2, (1\ 2\ 3))^6 = ((2, (1\ 2\ 3))^3)^2 = (2,e)^2 = (2+2,e^2) = (0,e)$, so $(2, (1\ 2\ 3))$ has order $6$.
So you are correct, $|N| = 6$, and thus $(\Bbb Z_4 \times S_3)/N$ has order $4$.
We now compute the order of $(3, (1\ 2))N$ in $(\Bbb Z_4 \times S_3)/N$:
$[(3, (1\ 2))N]^2 = (3, (1\ 2))^2N = (2,e)N = N$ (since $(2,e) \in N$).
Thus $(3, (1\ 2))N$ has order $2$.
To decide if $(\Bbb Z_4 \times S_3)/N$ is cyclic (we know it is abelian, since any group of order $4$ is), we compute the order of another coset. To do this, let's explicitly list the elements of $(3, (1\ 2))N$, so we don't duplicate our effort.
$(3, (1\ 2))N = \{(3, (1\ 2)),(1, (2\ 3)),(3, (1\ 3)),(1, (1\ 2)),(3, (2\ 3)),(1,(1\ 3))\}$
So we can choose $(2, (1\ 2))N$ as another distinct coset, and compute its order:
$[(2, (1\ 2)N]^2 = (2, (1\ 2))^2N = (0,e)N = N$, so it has order $2$ as well.
Thus the factor group is not cyclic, for a cyclic group of order $4$ has but one element of order $2$.
By the way, non-abelian groups can have cyclic factor groups, for example $S_3/A_3$ is cyclic of order $2$.


Tem como capturar um value do radio button via ajax

Question:

            <button type="radio" name="tipoTransacao" id="tipoTransacao" value="1" class="btn btn-success" >Entrada</button>
            <button type="radio" name="tipoTransacao" id="tipoTransacao" value="2" class="btn btn-danger">SaídaSaída</button>

e estou tentando fazer a captura assim:
function salvar(e){
e.preventDefault();
var fk_idConta = $(this).find('select[name=fk_idConta]').val();

var tipoTransacao =  $("button[name='tipoTransacao']:checked").val();
var demo8 = $(this).find('input[name=demo8]').val();
var dataTransacao = $(this).find('input[name=dataTransacao]').val();
var meioTransacao = $("input[name='meioTransacao']:checked").val();
var descTransacao = $(this).find('textarea[name=descTransacao]').val();

Answer: Elementos <button> não possuem value. Mesmo que você declare os valores no HTML, eles não existirão no JavaScript. A forma "correta" de se utilizar radio buttons, é dar name diferentes para eles, e então validar pelo nome, não pelo valor.
Porém, se você absolutamente precisa trabalhar dessa forma, você pode pegar o valor de value diretamente do atributo declarado no HTML com $("button[name='tipoTransacao']:checked").attr('value')


Windows Registry to VBS

Question: I have this registery (.reg) file that I use to modify screensaver properties:
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Control Panel\Desktop]
"ScreenSaveActive"="1"
"ScreenSaveTimeOut"="900"
"ScreenSaverIsSecure"="1"
"SCRNSAVE.EXE"="C:\\windows\\system32\\scrnsave.scr"

The registry works fine.
My Question: is it possible to make this registry to Visual Basic Script .vbs file? If yes how, please advice.
PS this is my first question in this forum.
Comment: I completely understand, I've got several perfectly working vbscripts hanging around that are on the list of things to fix with a deadline of *eventually*. I highly recommend learning Powershell. It's not only available in 2003 up to version 2, but each successive version gets more and more powerful in its management capabilities, and in Windows 7+, you can even run your logon scripts asynchronously, so that the users don't have to wait for scripts to finish executing before their environment continues to load.
Comment: Check out [this article](http://www.atumvirt.com/index.php/2013/11/dramatically-reducing-logon-time-to-desktop-by-moving-from-group-policy-preferences-to-powershell-logon-script/) for a nice hybrid approach of GPO and scripted login.
Comment: This sounds suspiciously like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What is it that you're trying to accomplish? Where will this script run? If it's in an AD environment, you can probably use group policy to accomplish your goal.
Comment: @austinian true, I use it in AD environment and yes under group policy. It was a temporary solution, and I was thinking to make it as vbs.
Comment: @austinian I disagree with you regarding XY problem, this reg is working fine. We are going move every thing to VBS so we have master VBS for login script as vbs, but I wanted to start testing .reg and see how it works as vbs, and quietly convert the rest of the login script. If you think this is the wrong way to go, I would like to hear your opinion.
Comment: First off, [VBScript is in maintenance mode, and may soon disappear](http://blogs.technet.com/b/heyscriptingguy/archive/2010/04/16/hey-scripting-guy-april-16-2010.aspx). So, learning VBScripting now may not be the best use of your time. As for logon scripts vs gpo, I'd recommend typing in exactly that into google to see a broader array of opinions, the first page has links to good articles and discussions. If you're converting a script to a GPO, and the script has conditional logic in it, then you can use item level targeting in most cases to apply the policy in the same manner the script does
Comment: OK @austinian That was useful, thank you I have just been out of date with my old day vbs we still running windows 2003/2008 servers, I am a bit old school, I need to update my self.
Answer: This was answered to a degree here at Super User but I recommend using reg query, reg import and reg add in MS-DOS/Command Prompt.
EDIT: To elaborate, you can manually add the keys one by one or you can import a .reg file with a simple batch script (if not a one liner)
If this is in an AD environment, it can be done, perhaps more reliably, with group policy. In an environment where there's remote management but no AD, personally what I'd do is host the .reg file on a network share and either copy it or import it directly if possible (I'm not sure if reg import supports that.
EDIT: Let's make this a bit more complete. You'd import the reg key with

reg import \\Sharename\regkey.reg

In command prompt/batch.
Here's an example I tested this solution with.
FINAL EDIT:
It's been brought to my attention there's an off chance someone comes here and, in their right mind, actually wants to do this with VBS. I linked two links, but here's one of the solutions
Vbs Script:
Set oShell = CreateObject("Wscript.Shell")

'Your .Reg file and path goes here as in the example below
sRegFile = "C:\Temp\MyFile.Reg"

'This line runs Regedit in silent mode
oShell.Run "regedit.exe /s " & Chr(34) & sRegFile & Chr(34), 0, True

Comment: I don't know enough to say. I think if this is for your personal machine or for a single machine basis, it's better in Super User. Server Fault is generally for managing larger information systems.
Comment: It's already accepted but God forbid someone comes and somehow can't use powershell and batch, I'll include the content of one or two of those links.. I understand where you're coming from.
Comment: @maytham I improved my answer in a much more catch-all manner.
Comment: https://jagspage.wordpress.com/2013/08/09/importing-reg-file-silently-using-vbscript/ and http://webcache.googleusercontent.com/search?q=cache:PnPr1Mx7yloJ:myitforum.com/cs2/blogs/dhite/archive/2006/09/01/Using-Vbs-To-Silently-Import-Reg-Files.aspx+&cd=1&hl=en&ct=clnk≷=us both explain how to do it in VBS in multiple ways, most of which invoke ShellRun, which will literally run as you would run in Command Line.
Comment: To make the answer more complete and less reliant on the link as an answer and more as a source, you should include the vbs objects that can be used to modify the registry. For instance, GetObject("winmgmts:\\.\root\default:StdRegProv") if you use WMI to modify the registry, or CreateObject("WScript.Shell") if you want to use a shell object to modify the registry.
Comment: I actually intentionally didn't add that because I don't want to promote vbs as a solution to this person's use case. I will add example syntax for cmd however.
Comment: @austinian how's this look? See OP
Comment: The issue I have with this is that the OP specifically asked for VBS. While I 100% agree with you that VBS is not the right course to pursue, especially [since it's in maintenance mode now and may become deprecated at any time](http://blogs.technet.com/b/heyscriptingguy/archive/2010/04/16/hey-scripting-guy-april-16-2010.aspx), the OP is asking for a VBS solution. Fixing the question first is the best approach, IMHO.

Windows Registry to VBS


Offline tile caching using MapBox Android SDK

Question: I have a working iOS prototype using the iOS tile-caching technique as shown below (Objective-C code):
RMTileCache  * tileCache = [[RMTileCache alloc] initWithExpiryPeriod:0];
[tileCache setBackgroundCacheDelegate:self];
RMMapboxSource * tileSource = [[RMMapboxSource alloc] initWithMapID:mapID];
[tileCache beginBackgroundCacheForTileSource:tileSource southWest:southWest northEast:northEasth minZoom:minZoom maxZoom:maxZoom];

What this basically does is download the map, cache the tiles permanently and make it possible for the app to run offline in the future. Since we're going through the official payed API, this is of course not violating any of the legal restrictions.
Now I'd like to achieve the same on Android. I have the SDK running in Android Studio and a working project with a remote map using the Map ID, basically this (Android Eclipse layout XML):
<com.mapbox.mapboxsdk.views.MapView
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    mapid="my_map_id" />

This works fine, but the solution has to be completely offline once the caching is done. My question is: is there a Java equivalent of the iOS source code above in the MapBox SDK? I attempted to look in the API, but could not find a solid reference to the tile caching system. And after some painful time trying to get it running based on the method names and code documentation, I gave up.
I'm running the latest GitHub distribution of MapBox along with the latest Android Studio, everything's up and running fine, but can't find the code to accomplish this. I don't necessarily need an API reference, a few lines of code showing how it's done would be enough.
Answer: Offline Tile Caching support is now available in the Mapbox Android SDK as of version 0.5.1.  It was released on 20-December-2014.  Here's a basic example of how to get started:
OfflineMapDownloader offlineMapDownloader = OfflineMapDownloader.getOfflineMapDownloader(getActivity());
BoundingBox boundingBox = mapView.getBoundingBox();
CoordinateSpan span = new CoordinateSpan(boundingBox.getLatitudeSpan(), boundingBox.getLongitudeSpan());
CoordinateRegion coordinateRegion = new CoordinateRegion(mapView.getCenter(), span);
offlineMapDownloader.beginDownloadingMapID("MapboxMapID", coordinateRegion, (int) mapView.getZoomLevel(), (int) mapView.getZoomLevel());

To load a previously saved map:
ArrayList<OfflineMapDatabase> offlineMapDatabases = offlineMapDownloader.getMutableOfflineMapDatabases();
OfflineMapDatabase db = offlineMapDatabases.get(0);
OfflineMapTileProvider tp = new OfflineMapTileProvider(getActivity(), db);
offlineMapOverlay = new TilesOverlay(tp);
mapView.addOverlay(offlineMapOverlay);

Comment: How should one use this with the MapView? Does it check if there is an offline version automatically? Or do you have to specify in the mapview that you want to use a offline version.
Comment: I just updated the answer with instructions on how to load it back.  Hope this helps!
Comment: I already figured it out from the source :) however I'm have a small issue with downloading the map. I think there is a bug in the SDK when converting the lat/lng numbers. I posted the issue on github [isssue #607](https://github.com/mapbox/mapbox-android-sdk/issues/607)
Comment: @BradLeege I keep having out of memory exceptions, is there a proper documentation as to how to make those maps offline ? I am not using the mapview for bounds but using the data coming back from the webapi /v4/MAPID.json ... it seems like the bounds and min and max zoom just blow the memory when it generating all the tiles URLs and adding them to a list. Is it possible to get any help ? I'm using the latest stable version of the library (On Android off course).
Comment: @TheYann Memory usage is all tied to the number of tiles being downloaded.  The likely cause of this problem is too great a range in min and max zoom levels, as each zoom level has a larger number of tiles that the one above it.  Try narrowing the range if possible.
Comment: @BradLeege Well I tried a lot of things, narrowing the zoom range, as well as the bounds, but still my minimum requirements seems to be too much. I'll try to find a solution and maybe submit a pullrequest.
Answer: I asked this question to the support team, here's the answer:
"We don't currently have a release date for the Android SDK or for this feature, because both are in very early stages of development.
--
Tom MacWright
firstname.lastname@example.com"
It's a very good product, I hope we can use it soon in Android.
Comment: Good news: as of 2 days ago, this is being actively developed! https://github.com/mapbox/mapbox-android-sdk/issues/533
Comment: Yes, I just got the same answer. I'm with you, MapBox looks perfect on iOS and what is available on Droid looks just as promising. Unfortunately we can't pick it up without this portion.
Comment: Does anyone have any idea on the progress of the support of this feature?
Answer: In your layout file there must be:
<com.mapbox.mapboxsdk.views.MapView
        android:id="@+id/yourMapViewId"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

In code where you want to initialize MapView:
File file = new File("your full path to tiles db");
MBTilesLayer mbTilesLayer = new MBTilesLayer(file);
MapView mapView = (MapView) findViewById(R.id.yourMapViewId);
mapView.setTileSource(mbTilesLayer);


Black Screen Tab Bar Controller

Question: I am facing a problem. When I want to change the View for a Tab View Controller, my application gives a black screen.

And here is my code to change view:
let homeViewController = self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? HomeViewController

self.view.window?.rootViewController = homeViewController
self.view.window?.makeKeyAndVisible()

Constants.swift:
import Foundation

struct Constants {

    struct Storyboard {

        static let homeViewController = "homeVC"

    }
}

homeVC is the first View of TabBarController, with the Label.
Comment: try set TabbarViewController id = "homeVC", It will load all tab its have(include ViewController with Label text)
Answer: This is my way. I am not using storyboard by the way. I am using xib.
let dashboardVc = DashboardTabController()
self.window!.rootViewController = dashboardVc
self.window!.makeKeyAndVisible()
self.window?.overrideUserInterfaceStyle = .light

and then in dashboardTabController type this one.
import UIKit

class DashboardTabController: UITabBarController {

    @IBOutlet weak var dashboardTabBar: UITabBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        let firstViewController = HomeViewController()

        firstViewController.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "ic_home_24px"), selectedImage: UIImage(named: "ic_home_24px"))

        let secondViewController = AddContactViewController()

        secondViewController.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "ic_group_add_24px"), selectedImage: UIImage(named: "ic_group_add_24px"))

        let tabBarList = [firstViewController, secondViewController]

        viewControllers = tabBarList
    }
}

don't forget in DashBoardTabController xib, implement the UITabBar in bottom. Hopefully it's helpful. Just mention me if you need more help on executing this.
Comment: I have replace class of my first Item view in Storyboard, and then, the simulator not showing a black screen but it's showing right screen with label but without Tab Bar, so I have not yet used your code.
Comment: I think because you are not setting tab bar page in root view controller. But instead you are setting the home page on root. that's why the tab bar is missing

Black Screen Tab Bar Controller


The value of $ A \exp\left(\frac{-1}{2\pi} \int_{-\pi}^{\pi} \ln(1+A+2BC \cos x) dx \right)$

Question: I'm looking for the value of: $$ A \exp\left(\frac{-1}{2\pi} \int_{-\pi}^{\pi} \ln(1+A+2BC \cos x) dx \right)$$
I know we could take $y=1+A+2BC \cos x$ but changing variable in this way makes the integral from $1+ A - 2BC$ to $1+ A - 2BC$ which makes the integral zero!
How to solve it ?
thanks
Comment: $\cos$ is an even function, so the integral is $2\int_0^\pi \dotsb$.
Answer: Hint:$$y=A \exp\left(\frac{-1}{2\pi} \int_{-\pi}^{\pi} \ln(1+A+2BC \cos x) \  \mathrm dx \right)\to$$
$$\ln y=\ln A+\left(\frac{-1}{2\pi} \int_{-\pi}^{\pi} \ln(1+A+2BC \cos x  \mathrm dx\right)=\ln A+\left(\frac{-1}{\pi} \int_{0}^{\pi} \ln(1+A+2BC \cos x  \mathrm dx \right)$$
now take $1+A+2BC \cos x=z$ then $\  \mathrm dz=-2BC\ \sin x \ \mathrm dx\to \  \mathrm dx=\pm \dfrac{-\  \mathrm dz}{2BC\sqrt{1-z^2}}$ we have
$$\ln y=\ln A-\underbrace{\frac{1}{2\pi BC} \left(\int_{0}^{\frac{\pi}{2}} \frac{-\ln z}{\sqrt{1-z^2}} \  \mathrm dz+\int_{\frac{\pi}{2}}^{\pi} \frac{\ln z}{\sqrt{1-z^2}} \  \mathrm dz\right) }_H
$$
then integrate by part ...$$\large{y '=Ae^{H}\cdot H '}$$


$\pm A$ is sectorial implies it is bounded

Question: The question is as follows: suppose $(A,D(A))$ is a sectorial operator on a Banach space $X$ such that $-A$ is sectorial as well, prove that $A$ must be bounded.
Since I've found there are many more or less equivalent conventions on sectoriality I'll state the one I'm more familiar with:
$A$ is sectorial if the sector
$\Sigma(\omega,\theta):=\left\{ z\in\mathbb{C}| \;\;|\arg(\omega-z)|<\theta\right\}$
is contained in the resolvent set $\rho(A)$, where $\omega\in\mathbb{R}$ and $\theta\in\left(\frac {\pi}2,\pi\right)$ and
$\forall z\in\Sigma(\omega,\theta)\;\;\; ||R(z,A)||\leq M|z|^{-1},$
for some positive constant $M$.
It is straightforward to show that if $\pm A$ is sectorial then the spectrum $\sigma(A)$ is bounded. Now, I have two strategies in my mind that I cannot conclude:

Showing that the generated Analytic Semigroup is actually Uniformly Continuous, since I know that then such semigroup is of the form $e^{tA}$, for bounded $A$ and since the generator is unique we can conclude. It may help to use the fact that, if we call $T(t)$ the generated semigroup, we now that

$$\forall x\in X\;\;\; A\int_0^s T(s)xds=T(t)x-x,$$
since showing uniform continuity amounts to show that $||T(t)-I|| \rightarrow 0^+$ in the operator norm, however this puts me in a vicious cycle since what we need is precisely a bound on the norm of $A$.

Another property I've seen is that the image of $T(t)$ is contained in $D(A)$, thus if we show that $T(t)$ is surjective (in particular invertible) we can conclude immediately. Now, in the context of $C_0$-semigroups I would simply note that $A$ actually generates a group, i.e. $-A$ generates the semigroup $T(-t)=T(t)^{-1}$ but, after doing some research, I was surprised to not found a single piece of literature on "Analytic Groups of Operators". This makes me think that this approach won't work, at least not that straight-forwardly, to show that $T(t)$ is invertible (which it must be, since a uniform semigroup is actually a group of operators).

Do you have any idea on how to conclude one of this approaches? A new approach would of course be welcome too!
Comment: Your definition of sectorial operator is incomplete, I think. You're missing a condition on the norm of resolvent. Anyway, I don't quite understand where you are stuck with approach 2. Can you show that the semigroups $(S_t)$ and $(T_t)$ generated by $A$ and $-A$, respectively, satisfy $S_t T_t=T_t S_t=\mathrm{id}$?
Comment: @MaoWao Honestly no, the semigroups are given by some line integral and I'm not quite sure on how to compute their product. I'll add some computations later if necessary.
Answer: Let $(S_t)$ and $(T_t)$ be the semigroups generated by $A$ and $-A$, respectively. As both of them are analytic, they map $X$ into $D(A)$ for $t>0$ and commute with $A$. If $\xi\in X$, then
$$
\frac{d}{dt}S_tT_t\xi=AS_t T_t\xi-S_tAT_t\xi=0
$$
for $t>0$. Thus $S_tT_t=\mathrm{id}_X$. The proof of $T_t S_t=\mathrm{id}_X$ is analogous. Thus $S_t$ is invertible for every $t>0$. Since $S_t(X)\subset D(A)$, this implies $D(A)=X$. By the closed graph theorem, $A$ must hence be bounded.
Comment: No, what I use is that sectorial operator generate analytic semigroups, and these are immediately differentiable (i.e. $t\mapsto T_t\xi$ is differentiable on $(0,\infty)$). Alternatively you can also make the same computation for $\xi\in D(A)$ first and use boundedness of $S_t$ and $T_t$ to extend the identities $S_t T_t\xi=\xi$ and $T_t S_t\xi=\xi$ to all of $X$.
Comment: A doubt arose in my mind when rewriting this, when you take the derivative aren't you implicitly assuming that the semigroup is uniformly continuous?


500 internal server error while installing

Question: What is the reason for the error "500 internal server error" while trying to install drupal,

i have created database successfully
After that i have downloaded and extracted the drupal 7.22 in my desired        directory.

But when i trying to install the tables in my database its showing  the error and approximately more than 30 tables are storing and the installation process stops automatically with showing the above error . Can anybody tell me why the error is coming.
Comment: 500 is an HTTP status code, you'll need to find the underlying error by looking through the server log files. Until you have the specific error that's occurring it will be impossible for anyone here to help
Comment: increase execution time in php.ini
Answer: As Clive says above, it's nearly impossible to help without knowing more about your particular setup and debug info.
Common pitfalls are :

Various php.ini settings : max_execution_time as mentioned by monymirza above, but also memory_limit. This last can be raised during install and dev, then lowered for production.
Lacking .htaccess at Drupal's root. Standard unix commands often don't copy hidden files, and .htaccess is more or less mandatory for D7 to work.
Lousy DB connection, particularly on shared hosting.
Misconfigured vhost : perhaps a particular setting messes up things between domains, or subdomains. Also, you have to check the AllowOverride All directive on Drupal directory for it to function properly.

There are others, but these should get you started.
Answer: Thanks for those hints.
In my instance, the site was installed on a Virtual Host inside Virtualmin/Webmin, which contains symbolic links in the public folder pointing to "awstatsicons".
The Drupal .htaccess file contains a directive to follow symbolic links in the installation directory:
# Follow symbolic links in this directory.
  Options +FollowSymLinks

Commenting out the Options +FollowSymLinks allowed the installation script to run:
# Follow symbolic links in this directory.
# Options +FollowSymLinks

However, I subsequently learned that Drupal needs to be able to follow Symlinks to work, so changing that to:
# Follow symbolic links in this directory.
# Options +FollowSymLinks
Options +SymLinksIfOwnerMatch

This needs to be repeated in the .htaccess located at sites/default/files seems to work.
Answer: Try to delete/move all of the modules to another place. Then try to move back again one by one and try to see the output. In this way bring back all the modules and try to see the output. Then most probably you will be done or atleast you may know the module which making problem.


Erro: expected class-name before

Question: Estou desenvolvendo um projeto onde eu tenho uma classe online que herda de uma classe X, onde essa classe X precisa dar um new em um objeto da classe online. Quando eu faço isso acontece o erro, devido à herança eu acredito:

expected class-name before

class X
{
    public:
        X();
        virtual ~X();
        X* makeMethod(string Method);
    protected:

    private:
};

X* X::makeMethod(string Method){
    return new online();
}

class online: public X{
    public:
        online();
        virtual ~online();
        void makeMethod(string Method);
    protected:

    private: };

Como resolver esse erro?
Answer: Declare a classe antes de defini-la, pode até ser a primeira linha do arquivo:
class online {};

Assim você já pode usá-la no seu código e só depois defina como ela será implementada, como já o fez, o que pode ser depois dela já ter sido usada.
class online {};

class X {
    public:
        X();
        virtual ~X();
        X* makeMethod(string Method);
};

X* X::makeMethod(string Method) {
    return new online();
}

class online: public X {
    public:
        online();
        virtual ~online();
        void makeMethod(string Method);
};

Coloquei no GitHub para referência futura.

Erro: expected class-name before


Backbone not communicating with rails controller?

Question: I'm working my way through a simple Backbone JS app using Rails 4.1, and am having some trouble getting my data from the controller to the Collection.
I have setup a Model, View, Collection, and Router for the app, but when the index view renders, I get nothing returned. When I try to hit the js app's initialize in the console, I get the following error:
TypeError: Cannot read property 'tasks' of undefined
Which is referring to 'data', which is passed into the initialize function from the rails controller.
After some debugging, I'm seeing my controller is receiving the following error when trying to call initialize on the js app:
NoMethodError: private method `initialize' called for TodoList:Module

My setup is as follows:
Controller:
class TasksController < ApplicationController
  respond_to :json, :html

  def index
    @tasks = Task.all
    respond_with(@tasks)
  end
end

Backbone App:
var TodoList = {
  Models: {},
  Collections: {},
  Views: {},
  Routers: {},

  initialize: function(data) {
    this.tasks = new TodoList.Collections.Tasks(data.tasks);
    new TodoList.Routers.Tasks();
    Backbone.history.start();
  }
};

Backbone Router:
TodoList.Routers.Tasks = Backbone.Router.extend({
  routes: {
    '': 'index'
  },

  index: function() {
    alert('I cannot get this text to render');
  }
});

Backbone Model:
var Task = Backbone.Model.extend({});

Backbone Collection:
TodoList.Collections.Tasks = Backbone.Collection.extend({
  model: Task,
  url: '/tasks'
});

UPDATE
tasks/index.html/erb, where TodoList.initialize is called from:
<%= content_for :javascript do %>
    <%= javascript_tag do %>
        TodoList.initialize({ tasks: <%== @tasks.to_json %> });
    <% end %>
<% end %>

Comment: Where do you call `TodoList.initialize` in your JavaScript? Something is very confused here. That `TypeError` is a JavaScript error but the `NoMethodError` is a Ruby error. You're trying to call `TodoList.initialize` in Ruby but you want to say `TodoList.initialize(some_javascript_data)` in JavaScript.
Comment: I call TodoList.initialize from my index.html.erb file... I'll attach in an update above.  And I imagine its a ruby error because im using pry to debug on the ruby side...maybe that's a red herring?
Answer: After some digging, I realized I was missing the following line from my application.html.erb layout file that referenced my javascript
<%= yield :javascript %>


images changing the position of other elements on being zoomed

Question: I am making a page in which there will be array of images. I need the images to be zoomed when the mouse is hovered and i got it successfully through java script. But the problem is when the image gets enlarged the position of the other images is also getting changed.
  I want such that the zoomed image does not change the position of other images like Google Images...  that is i want the zoomed image to come over the beside images....any help please...
 Thanks in advance
Answer: You should use absolute positioning and z-index.
HTML

CSS
.container {
     position: relative;
}
.container img {
     position: absolute;
     z-index: 0;
}
.container img:hover {
     position: absolute;
     z-index: 1;
}

Answer: Avoid making use of percentage for giving height and width. I have experienced it too. Instead provide height and width in "pixels(px)". That would serve better and the solution for your query.


Integrating factor of $x^2ydx-(x^3+y^3)dy=0$

Question: $x^2ydx-(x^3+y^3)dy=0$
I have to find an integrating factor $\mu$.
Denote $P=x^2y,Q=-(x^3+y^3)$
The correct answer for getting an integrating factor is $\mu=e^{\int\frac{P_y-Q_x}{\color{red}{P}}dy}$ or $\mu=e^{\int\frac{P_y-Q_x}{\color{red}{-P}}dy}$ ?
In my post Solve $ye^ydx+(1+xe^y)dy=0$ , I got a comment that the correct answer is $\mu=e^{\int\frac{P_y-Q_x}{\color{red}{P}}dy}.$
Then , $\int\frac{x^2+3x^2}{x^2y}dy=4ln|y| \implies \mu=e^{ln|y|}=y^4$ , But the correct integrating factor is $y^{-4}$.
How is it possible ? maybe $\mu=e^{\int\frac{P_y-Q_x}{\color{red}{-P}}dy}$?
Thanks !
Answer: There is no general formula for an integrating factor.
However you can assume the integrating factor depends only on one variable or the other, and if that assumption is consistent with the equation then you can go from there.
If you assume it depends only on $x$ and the equation is of the form $P dx + Q dy = 0$ then you want $\frac{\partial}{\partial y}(P\mu)=\frac{\partial}{\partial x}(Q\mu)$, which is to say $P_y \mu = Q_x \mu + Q \mu'$, so $\mu'=\frac{P_y-Q_x}{Q} \mu$. This is consistent with the assumption about $\mu$ if and only if $\frac{P_y-Q_x}{Q}$ depends only on $x$.
If you assume it depends only on $y$ then you want $\frac{\partial}{\partial y}(P\mu)=\frac{\partial}{\partial x}(Q\mu)$ or $P_y \mu + P \mu' = Q_x \mu$, so $\mu'=\frac{Q_x-P_y}{P} \mu$. Note the sign change. This is consistent with the assumption about $\mu$ if and only if $\frac{Q_x-P_y}{P}$ depends only on $y$.
This is the same as what was told to you in the comments of the other question.
Answer: You forgot a minus in the formula for integrating factor. The formula says that if $(P_y-Q_x)/M$ is a function of $y$ only, then the equation $P(x,y)dx+Q(x,y)dy=0$ has an intergrating factor
$\mu(y)=\exp\left(-\int\dfrac{P_y-Q_x}{M}dy\right).$
In your case, $(P_y-Q_x)/M=(4x^2)/(x^2y)=4/y$, thus
$\mu(y)=\exp\left(-\int 4dy/y\right)=1/y^4.$


Playing against a very athletic player - singles tennis strategy

Question: What kind of strategy should you use when you play against someone who plays at a higher level than you, but is still beatable on a bad day? This particular player is very athletic, but she doesn't have topspin, doesn't have the best form, but just hits hard and flat, and gets to everything.
I have all the shots, but prefer the baseline. I am fast, but she has beaten me twice in the past, she's a little above my level, but still beatable.
Answer: Consistency. That is the most effective way to beat a player who is at a higher level than you, especially someone who doesn't have topspin or great form.
Practice what my coach used to call your "rally ball." This is a topspin ball that should land around three-quarters court and should pass high (4-5 feet) over the net. If you are able to hit a ball like this consistently, you will suddenly find yourself beating players that play at higher levels. This shot is penetrating enough that your opponent will not be able to take advantage and hit offensive shots consistently, but it can extend a rally long enough for her to make an unforced error, give you a short ball, or get frustrated and go for an offensive shot from the baseline (which is very low percentage).
Please not that I am NOT telling you to push the ball. The rally ball is not a weak lob; it is a driving shot with topspin that will force your opponent to stay behind the baseline where her hard, flat shots will often miss long.


How to check if contents of two lists is same in python?

Question: I have 3 lists :

list_1 = [1,2]
list_2 = [2,1]
list_3 = [1,2,3]

Note: numbers inside [] are the ids from Django Model

I want to test whether the contents (but not necessarily the order) of two lists are exactly the same. With reference to the 3 examples above:
Comparing list_1 and list_2
should return True,
but if I do validation between list_2 and list_3, or between list_1 and list_3,
then the result should be False.
How do I achieve this?
Thanks :D
Comment: I don't understand the question. If you want to test if numbers in `list_1` are in `list_2`, why would you do validation between `list_2` and `list_3`? And why would that cause it to return `False`?
Comment: Convert the lists to `set`, then use `set.issubset()` to tell if one list contains another.
Comment: Using sets is slower. See link at the bottom. Also, I think OP doesn't want to compare for trivial subsets but equality, rending your answer possibly incorrect. Oh and possible duplicate of http://stackoverflow.com/q/7828867/5775722
Comment: Thanks for the reply @Barmar, I want to check if numbers inside one list are equal with another, then the values inside them must be same
Comment: Now I understand. What you want is `validate(list_1, list_2)` is true, but `validate(list_2, list_3)` is false.
Answer: I interpret your question as return true if the contents (but not necessarily order) of the lists are identical, otherwise return false. This can be solved by sorting both lists, then using the == for comparison. sorted() returns a list of integers in ascending order. This means that if the lists' contents are the same, sorted() returns identical lists.
def validation(list_1,list_2):
    return sorted(list_1) == sorted(list_2)

This passes all of your test cases. I might have misunderstood your question, please clarify if that's the case.
Comment: Actually, using `Counter(list_1) == Counter(list_2)` would be better in terms of time complexity.
Comment: I got **TypeError: '<' not supported between instances of 'QuerySet' and 'QuerySet'**


Unmarshalling XML having name value pair in java

Question: <GetDeadlineOffset>
<deadlineCode>DeadlineCode</deadlineCode>
<parameters>
    <parameter name="Name1" value="Value1"/>
    <parameter name="Name2" value="Value2"/>
</parameters>
</GetDeadlineOffset>

How to unmarshall this format of xml where we don't have the specified XSD.
Comment: First of all, your xml is not properly structured as there is no closing tag for GetDeadlineOffset. Second, what have you tried? Are you using Xstream, JAXB, etc.?
Comment: sorry for the Structure, I have tried Jaxb but i don't have XSD for this, Can YOu please tell How can i use Xstream for such structure.
Answer: If you know what the XML looks like then you can generate an XSD but that isn't required to use XSteam.
XStream has pretty decent documentation on their site so you will want to start off by reading that. The quick overview can be found here: http://x-stream.github.io/tutorial.html
You are going to want to create beans for GetDeadlineOffset and Parameter and then you should be able to use fromXml().
I tend to like using annotations so once you have your annotated beans, you should be able to do something like this:
XStream xstream = new XStream();
xStream.processAnnotations(GetDeadlineOffset.class);
xStream.processAnnotations(Parameter.class);
GetDeadlineOffset getDeadlineOffset = (GetDeadlineOffset)xstream.fromXML(xml);


Problem in finding the Euclidean measure of a set in $\mathbb{R^3}$

Question:
Problem. For each $\alpha \in \mathbb{R}$, let $S_{\alpha}=\{(x,y,z)\in \mathbb{R}^3~|~ x^2+y^2+z^2=\alpha^2\}$.
Let $E=\bigcup_{\alpha\in \mathbb{R\setminus \mathbb{Q}}}S_\alpha$. Which of the followings are true?

The Lebesgue measure of $E$ is infinite?
E contains an nonempty open set.
E is path-connected .
Every open set containing $E^c$ has infinite Lebesgue measure.

My Solution.

True. Since $E^c=\bigcup_{\alpha\in  \mathbb{Q}}S_\alpha$ and $\mu(S_\alpha)=0$ So by countable additivity of $\mu$, $E^c$ has measure zero.

False. Since $E$ and $E^c$ both are Dense in $\mathbb{R^3}$.

False. Since any two sphere of irrational radius always there exists an intermediate sphere of rational radius between them.

True. I think there is only one open set containing $E^c$ namely $\mathbb{R^3}$. And $\mu(\mathbb{R^3})=\infty.$

But the answer key indicates the options: 1 is only True.
Then what is wrong with my conclusion about option 4. Please let me know where I made mistake. Thank You..
Comment: The open set only needs to contain a countable collection of the $S_\alpha$. Each 'shell' can be contained in an open set of arbitrarily small measure. Sum them up. Basically the same way you would show that the rationals have measure zero in the reals.
Comment: Oho ... u r right....!!!!
Answer: As you pointed out, we know $E^c = \bigcup_{\alpha \in \mathbb{Q}} S_{\alpha}$. Let $(a_n)_n$ be an enumeration of the rationals. Then for each $n \in \mathbb{N}$, define:
$$
r_n = \min \left\{ \frac{1}{2^n}, \frac{1}{{a_n}^4 2^n}  \right\}
$$
where $r_n = 1/2^n$ if $a_n = 0$, and
$$
R_n = \{(x,y,z) \in \mathbb{R}^3 \, | \, {a_n}^2 - r_n < x^2 + y^2 + z^2 < {a_n}^2 + r_n \}
$$
Remark that each $R_n$ is open, and that the size of $R_n$ is given by the difference of two spheres, i.e.:
\begin{align*}
\mu(R_n) &= \mu(B(0,{a_n}^2+r_n)) - \mu(B({a_n}^2-r_n))
\\ &= \frac{4}{3} \pi ({a_n}^2 + r_n)^3 - \frac{4}{3} \pi ({a_n}^2 - r_n)^3
\\ &= \frac{4}{3} \pi  \left( 6 {a_n}^4 r_n + 2 {r_n}^3   \right)
\\ &\leq \frac{4}{3} \pi \left( \frac{6}{2^n} + \frac{2}{2^{3n}}  \right)
\\ &\leq \frac{48 \pi}{3} \cdot \frac{1}{2^n}
\end{align*}
Since each $R_n$ is open, their union is open. It is also clear that the union of the $R_n$ contains $E^c$, and finally we have:
$$
\mu \left( \bigcup_{n \in \mathbb{N}} R_n \right)
\leq
\sum \limits_{n=1}^{\infty} \frac{48 \pi}{3} \cdot \frac{1}{2^n}
= \frac{48 \pi}{3}
$$
This gives an example of an open set that contains $E^c$ which has finite measure.


lighttpd AND apache on the same server?

Question: I've been thinking about running lighttpd for static content, but I'd rather not throw down the couple extra bucks to run the second box. Is it possible (and this is me going out on a limb) to run Apache on port 80 and lighttpd on another port (say, 81)? I know it would be better to just put it on another box, but I'm looking to do this on the cheap if possible.
Thanks
Answer: Changing the port that lighttpd listens on is pretty staightforward. Just change the "server.port" directive in "lighttpd.conf" (or wherever your OS decides to put the config for lighttpd).
Are you planning on adding a ":81" to all the URLs that refer to the lighttpd content?
If not, you should think about running lighttpd on port 80, moving Apache to another port, and proxying access to Apache through lighttpd. As has been discused on Server Fault already, running lighttpd as the proxy is preferred since it's "lighter weight" than Apache.
Of course, lighttpd isn't the only show in town. Some comparison between lighttpd, apache, and nginx has been the topic of conversation over at Stack Overflow. I don't use lighttpd and I don't know if the memory leak issues that I've seen mentioned in a couple of places have been addressed or not.
Comment: "Are you planning on adding a ":81" to all the URLs" ...yeah, that's what I was figuring for static content. I can't imagine that there's any reason I _couldn't_ do it, but I'd rather ask then experiment and waste a day.
Comment: I've been running Lighty for some time and have yet to encounter the memory leak problem. Supposedly, it still exists, but I can only assume it only occurs in certain instances/configurations which haven't been identified yet.
Answer: Why do you want to do this?  Having a separate server to handle static content, isn't necessarily a bad idea.  However, running lighttpd (or anything else) and apache on the same machine seem to be a bit misguided.
If you're having proformance issues, I'd find out where they are coming from. If it's anything like disk IO, memory issues, network issues, etc. running lighttpd isn't going to help. All those issues will still be there (assuming it's ran on the same machine).
If you're problem is long running scripts or similar, maybe it will help a tad bit, but I don't think it would be worth the effort.
In my opinion, if your site needs static content served different then dynamic, then you probably should move that content to another server.  It's probably time to start looking at a bigger hosting package.
That being said, I would suggest storing the static content on another disk (on another controller if possible) just to mitigate the lighttpd and apache processes from fighting for disk access.  Also, if you have the ram, it's possible to put that static content into a ramdisk for even faster access.  Though at somepoint simple network bandwidth limitations are going to come into play.
Comment: Obviously you've never actually done this, because it does make a significant difference to system load and throughput to serve static content with something like lighttpd or nginx.  Apache is relatively bad at serving static content, especially when it's also serving dynamic content out of the same server.

lighttpd AND apache on the same server?


Programmatically get the name of the Application Folder in OSX

Question: In the USA and Europe the application folder is named Applications, but under Chinese or Japanese localization how is it named?
Is there a way to programmatically get the name of the folder?
Answer: The directory names in the filesystem are always in English.  The directories can have localized names attached to them for displaying to the user, but those aren't the names you use to access the directories.  From Internationalization Programming Topics:

You need to be aware of localized path names in your application and display them appropriately. Localized path names are for display purposes only and should never be used when accessing the file system. You should continue to use the actual pathname when working with files and directories in your code, including when you need to write to caches or user preferences. The only time you should use a localized path name is when you want to display that path to the user through your application's user interface.

That said, you get get the path programmatically using NSSearchPathForDirectoriesInDomains:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSLocalDomainMask, YES);
// Returns an NSArray containing the string "/Applications"

You can also use -[NSFileManager URLsForDirectory:inDomains:]:
NSArray *urls = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationDirectory inDomains:NSLocalDomainMask];
// Returns an NSArray containing the NSURL "file://localhost/Applications"

If you need the localized names to display to the user, look at Internationalization Programming Topics.
Comment: the first example doesn't work with ARC, are you sure about the return type?
Comment: Check the [documentation](https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/miscellaneous/foundation_functions/Reference/reference.html#//apple_ref/doc/uid/20000055-SW5).  If you're getting an error, edit your question and paste in your code and the error.
Comment: I found the error sorry. Is "Path" not "Paths"
`NSSearchPathForDirectoriesInDomains`
Comment: +1. Nice job getting a ton of relevant information into a concise answer. It might be better a bit more emphasis on the fact that you _should_ get the path programmatically (Apple reserves the right to rename /Applications to "/HaHa/Your Code Doesn't Work On Housecat" in 10.9…), but since the OP was specifically asking for that, I don't think he'll have any problem finding it. Also, NSFileManager is "preferred" over NSSearchPathForDirectories (even the NSSearchPathForDirectories docs say so), but it's not deprecated or anything, so that's fine.
Comment: @MatterGoal I have fixed the typo.
Answer: [[[NSFileManager defaultManager] URLsForDirectory: NSApplicationDirectory inDomains:NSLocalDomainMask] lastObject];

I think should work (reference). If you're on a previous version of OS X and URLsForDirectory is unsupported, NSSearchPathForDirectoriesInDomains() is an alternative.
Answer: To get the localized name of a folder (or an application with localized names) appropriate for presentation to the user, use:
NSString *localizedName = [[NSFileManager defaultManager] displayNameAtPath:path];

For the Applications folder, you can use:
NSString *localizedApplicationDirectoryName = [[NSFileManager defaultManager] displayNameAtPath:NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSLocalDomainMask, YES).lastObject];

Answer: Swift:
let urls = FileManager().urls(for: .applicationDirectory, in: .localDomainMask)

▿ 1 element
    ▿ 0 : file:///Applications/

let urls = FileManager().urls(for: .allApplicationsDirectory, in: .localDomainMask)

▿ 4 elements
    ▿ 0 : file:///Applications/
    ▿ 1 : file:///Applications/Utilities/
    ▿ 2 : file:///Developer/Applications/
    ▿ 3 : file:///Applications/Demos/


Forecast confidence intervals from multiple realizations

Question: I have a forecast which involves sampling a probability distribution and therefore each time I run the forecast there is some random variation between results. If I run the forecast many times, how do I compute the expected forecast, 5% and 95% confidence intervals using the ensemble of results?
Two options I have tried
(1) At each time step compute the 0.5, 0.025 and 0.975th quantiles across all forecasts.
(2) Take the sum over all time steps and use the forecasts where this sum corresponds to 0.5, 0.025, 0.975th quantile of all sums?
I am pretty sure both methods are incorrect.
The first because it involves choosing from each forecast at each time step. Each forecast is an independent realization and so it feels like I should be considering each forecast independently. In any case, the confidence intervals I get when I use this method are very wide, much wider than the max variation in the individual forecasts.
The second option also seems incorrect. When I use this method the confidence intervals may cross. Furthermore, who is to say the forecast I choose to represent the ith confidence interval will still represent the ith confidence interval when I run the ith+1 time step.
Hoping someone can explain the floors in my logic and help me figure out the correct procedure.
Comment: @whuber I think you might be right, I am looking for a measure of uncertainty on my forecast. i.e. define the region about my forecast where the true value will fall 95% of the time.
Comment: Not an answer to your broader question, but if you are aiming for 95% CIs, you probably need to be grabbing the 0.025 and 0.975 quantiles, not the 0.05 and 0.95 quantiles -- which would only contain 90% of the time.
Comment: good point thanks!
Comment: Given you are forecasting, it sounds like you probably want to compute *prediction* intervals rather than confidence intervals.  Could you elaborate on what this interval is intended to do?
Comment: Do you expect the underlying probability to be constant so that all you have is sampling variance, or are you trying to identify changes in probability over time?
Comment: @EdM, the aim is to forecast a certain property of a subject. That property is drawn from a probability distribution which is a function of the age of the subject, so while probability distribution remains constant the probability does not.
Answer: If I have understand the question correctly, this is a case of Ensemble Forecasting, and I believe the goal is to find Prediction rather than Confidence Intervals. Given a set of $n$ predictions $\hat{y}_{1, t+h}, \hat{y}_{2, t+h}, .., \hat{y}_{n, t+h}$ for $h$ timesteps ahead:

Expected forecast: average of the set of predictions
50% Prediction Interval: median of the predictions
95% Prediction Interval: Find the 2.5% and 97.5% quantiles of the inverse empirical cumulative distribution of $\hat{y}_{i, t+h}$, there is 95% chance that the prediction falls in this interval.
Comment: This is great thank you and explains some of the confusion I have been having. After some analysis of my results, it seems sensible that the expected forecast should be the average since it is more reflective of the ensemble than the median. Can you put this on a more robust footing for me? Why mean gives Expected and median gives 50% PI. My floored intuition would be that for a unimodal symmetric distribution, one would want to report the "most likely" outcome, which I would naively say is the median. Looking at my results, however, this is clearly not the case.
Comment: clarification on my previous comment, I meant **asymmetric** distribution
Comment: By definition 'mean' corresponds to the 'expected' value (or average). Note than in this case, it's most probably the conditional mean given the available information until time $t$. Median is literally the midpoint of a frequency distribution; by default 50% of the population lies above/ below. If you have a Gaussian distribution these probably are the same; if your distribution is skewed, however, they'll differ.


Como tornar legível o código que usa propriedades da String?

Question: Tenho uma string que usa partes de outra String, como tornar mais "limpo" esse código? Visto que é bem dificil compreender.
String sessionHash = dirPath.substring(dirPath.substring(0, dirPath.length() - 1).lastIndexOf("/"));

sessionHash: /23980dc32e16792007de3343f1f99211/
dirPath:
  /home/daniela/oknok/data/uploads/23980dc32e16792007de3343f1f99211/
Answer: Pelo que entendi acho que o método getname() produz o resultado que você espera:
String sessionHash = new File(dirPath).getName();

Ou para ficar igualzinho:
String sessionHash = "/" + new File(dirPath).getName() + "/";

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: +1 e se ela quiser as barras em volta (tal como no exemplo) é só adicioná-las via concatenação de string.
Comment: Tirando o `substring` duplo, não melhora muita coisa mesmo... Você saberia dizer se esse método proposto, usando o `File`, vai dar um resultado igual num sistema Windows? (que usa "\" em vez de "/" como separador) Eu acho que vai, mas estou sem compilador aqui pra testar...
Comment: @mgibsonbr até onde eu sei vai dar certo, mas também não posso garantir.
Comment: @mgibsonbr mudei para resolver isto embora eu duvide que seja a intenção manter as barras. Eu estava fazendo igual a sua mas abortei porque achei que não melhorava quase nada.
Comment: a intenção era manter as barras, obrigada. Realmente bem mais legível e de fácil manutenção.
Comment: Se eu não me engano, existe uma constante na classe `File`, a `FileSeparator`, que é melhor pra isso. Usando o valor da resposta fica um pouco preso ao SO para execução do código.
Comment: @mutlei Concordo mas neste caso não vai gerar um nome de arquivo e sim uma *string* que a autora só onde vai usar. Pelo que entendi precisa ser assim mesmo independente do OS, portanto neste caso específico não deve ser usado o `separator`. A não ser que ela diga que tem que ser diferente, aí fica seu registro que precisa adaptar isto.
Answer: Você pode fazer isso através do método split: ele quebra uma string em pedaços usando uma expressão regular como delimitadora. Quebrando em torno da barra, e pegando o penúltimo pedaço (o último é vazio, pois está depois da última barra) você consegue o resultado que quer:
String[] partes = dirPath.split("/");
String sessionHash = "/" + partes[partes.length-2] + "/";

No caso específico da barra, entretanto, é mais simples usar a classe File, tal como sugerido por Maniero.


Permanent placeholder?

Question: Is there a simple way to have an input with a default starting text that can't be removed? For example, I want to input a custom url, it has "www.mysite.com/" (WITHIN the input) and I want the input to continue after that bit, but not be erasable.
Comment: Why not prepend your input with `www.mysite.com/`? (e.g. `www.mysiste.com`)
Comment: I know there's many workarounds (like below), it's just I'd have to custom style this one input (and container) so I wanted to know if it was possible another way.
Answer: Just use:

    Path: www.mysite.com/<input
        name="path"
        value=""
        placeholder="images/foo.jpg">

... then add the prefix on the server.
You can style the background and border of the input to be transparent, and then apply a suitable background and border to the
Comment: Well, I want it inside the input itself, *if* possible, but yes, that would work too. :)
Comment: @Brian — Styling it as suggested in the answer will make it *appear* within the input.
Answer: You could set up an onKeyPress handler for the input, and then on every keypress check whether or not the input still starts with your prefix (and if not, it could add it back in).
However, I suspect that in practice this would be a terrible idea, both from an implementation and a usability perspective.
A somewhat healthier approach would be to use an onBlur event that does the same thing.  It wouldn't instantly update the input, but as soon as the user clicks away it would fix it.

Permanent placeholder?


Convert Embedded JSON Dictionary to Pandas Dataframe

Question: I have an embedded set of data given to me which needs to be converted to a pandas Dataframe
"{'rows':{'data':[[{'column_name':'column','row_value':value}]]}"

It's just a snippet of what it looks like at the start. Everything inside data repeats over and over. i.e.
{'column_name':'name', 'row_value :value }

I want the values of column_name to be the column headings. And the values of row_value to be the values in each row.
Ive tried a few different ways. I thought it would be something along the lines of
df = pd.DataFrame(data=[data_rows['row_value'] for data_rows in raw_data['rows']['data']], columns=['column_name'])

But I might be way off. I probably not stepping into the data right with raw_data['rows']['data']
Any suggestions would be great.
Comment: How is your data enclosed?
Comment: @Ynjxsjmh I just updated it to be more accurate. Its actually enclosed in quotes which i've only now just noticed. So I know at least I have to remove those now first.
Comment: Why there are tow `rows` in the dictionary?
Comment: @Ynjxsjmh typo. My bad. Updated now.
Answer: You can try to add another loop in your list comprehension to get elements out:
df = pd.DataFrame(data=[data_row for data_rows in raw_data['rows']['data'] for data_row in data_rows])

print(df)

                  name value  type
0  dynamic_tag_tracker  null  null

Comment: Just made one last update to JSON to make it simpler looking. Tried something similar to what you have, but no luck. I am assuming I need to remove the quotes first before doing processing.
Comment: @JackGruber If you couldn't do `raw_data['rows']['data']`, you can try to convert your data to dictionary with `raw_data = ast.literal_eval(raw_data)` first.


PHPUnit throws error: \Drupal\Tests\DocumentElement class not found

Question: I have added some phpunit tests to my custom module. When trying to run them in I get this error: Class '\Drupal\Tests\DocumentElement' not found I have copied core/phpunit.xml.dist to core/phpunit.xml and edited the URL and DB values but nothing else.
The command I'm running is vendor/bin/phpunit -c web/core/phpunit.xml web/modules/contrib/my_module/.
It seems that the classloader is not working. What have I missed?
I'm using drupal 9 and phpunit 9. I've also tried with phpunit 7 and 8 but I get the same error.
Answer: Finally got to the bottom of this! The package drupal/core-dev is required.
composer require --dev drupal/core-dev

This installs the package as a development dependency.
Comment: Simple, but if you forgot about this as I did just now, can be frustrating!
Comment: composer require drupal/core-dev
Answer: Drupal forgot to add few dependency libraries.
See you have these 2 libraries.
composer show symfony/phpunit-bridge
composer show phpspec/prophecy-phpunit

If you don't please install.
I also noticed that following library also essential.
behat/mink

Comment: Those are dependencies for *drupal/core-dev*. If you need them, you need *drupal/core-dev*.


Implementing pinch effect on a image view in iphone

Question: Thanks in advance.
   I want to apply pinch, rotation and pan gesture effect on an image view.like this
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(scalePiece:)];
    [imgView addGestureRecognizer:pinchGesture];
    [pinchGesture release];

    UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotatePiece:)];
    [imgView addGestureRecognizer:rotationGesture];
    [rotationGesture release];

    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panPiece:)];
    [imgView addGestureRecognizer:panGesture];
    [panGesture release];

// Method implementation
- (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        UIView *piece = gestureRecognizer.view;
        CGPoint locationInView = [gestureRecognizer locationInView:piece];
        CGPoint locationInSuperview = [gestureRecognizer locationInView:piece.superview];

        piece.layer.anchorPoint = CGPointMake(locationInView.x / piece.bounds.size.width, locationInView.y / piece.bounds.size.height);
        piece.center = locationInSuperview;
    }
}
- (void)rotatePiece:(UIRotationGestureRecognizer *)gestureRecognizer
{
    [self adjustAnchorPointForGestureRecognizer:gestureRecognizer];

    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        [gestureRecognizer view].transform = CGAffineTransformRotate([[gestureRecognizer view] transform], [gestureRecognizer rotation]);
         NSLog(@"Rotate : %f",[gestureRecognizer rotation]);
        [gestureRecognizer setRotation:0];
    }
}
- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
    UIView *piece = [gestureRecognizer view];

    [self adjustAnchorPointForGestureRecognizer:gestureRecognizer];

    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        CGPoint translation = [gestureRecognizer translationInView:[piece superview]];

        [piece setCenter:CGPointMake([piece center].x + translation.x, [piece center].y + translation.y)];
        [gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
    }
}

- (void)scalePiece:(UIPinchGestureRecognizer *)gestureRecognizer
{
    [self adjustAnchorPointForGestureRecognizer:gestureRecognizer];

    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        [gestureRecognizer view].transform = CGAffineTransformScale([[gestureRecognizer view] transform], [gestureRecognizer velocity], [gestureRecognizer velocity]);
        [gestureRecognizer setScale:1];
    }
}

In this rotation and swipe(pan) working fine but pinch is not good. I have seen one app i.e.,http://itunes.apple.com/us/app/image-mask-costume-hd/id443821357?mt=8   in this the touch events are very nice . I want to implement like this is it possible by using gesture or we need to follow touch events. Do any one have idea please help me to do it.
Answer: Try this code: http://dl.dropbox.com/u/9397784/Image%20multitouch.txt
Replace currentlyEditing with your view. Just copy the code into the implementation of the view or view controller you want to use it in. The code handles zoom, rotate and pan. To reset the view back to the default position, call yourView.transform = CGAffineTransformIdentity;.
Comment: This method does not use a gesture recognizer, but handles the touch event directly. I find it easier to do it that way. All other objects (buttons, etc.) should still respond to touch after you put this in.
Comment: Thanks for ur response.Yes this is what i exactly want.In this every thing works fine ,But for pinch effect if i am pinching either in x or y direction i want to increase or decrease the view size in that direction only means width or height, not to scale in both directions. I think u got my point.If not clear once download img mask example from app store and check it once please.
Comment: I see what you mean. Let me check the code and see where that can be changed.
Comment: Use this line: `CGAffineTransform newTransform2 = CGAffineTransformScale(currentlyEditing.transform, (curPoint1.x - curPoint2.x) / (prevPoint1.x - prevPoint2.x), (curPoint1.y - curPoint2.y) / (prevPoint1.y - prevPoint2.y));` instead of the current one where `newTransform2` is set. This is untested but should work.
Comment: Try this: `CGAffineTransformScale(currentlyEditing.transform, abs(curPoint1.x - curPoint2.x) / abs(prevPoint1.x - prevPoint2.x), abs(curPoint1.y - curPoint2.y) / abs(prevPoint1.y - prevPoint2.y));`
Answer: The Apple Touches example suggests to use [gestureRecognizer scale] and not [gestureRecognizer velocity]:
- (IBAction)scalePiece:(UIPinchGestureRecognizer *)gestureRecognizer
{
    [self adjustAnchorPointForGestureRecognizer:gestureRecognizer];

    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        [gestureRecognizer view].transform = CGAffineTransformScale([[gestureRecognizer view] transform], [gestureRecognizer scale], [gestureRecognizer scale]);
        [gestureRecognizer setScale:1];
    }
}


Como limitar os caracteres de um label?

Question: Estou num projeto e-commerce, e preciso exibir o nome de um produto. Estou pensando em utilizar um label para isso. A ideia é deixar x caracteres visíveis, se o titulo ultrapassar esse numero x de caracteres, exibir "...". Eu não sei como fazer isso, nem se a melhor opção ou se é possível com um label.
Observações: Estou utilizando jsp para recuperar o titulo do produto do banco de dados. A linguagem de programação é JAVA e utilizo html e jsp. eu consigo recuperar o nome com <%anuncio.getTitulo()%>.
Alguma dica ou sugestão de como fazer isso?
Comment: Se eu entendi bem, quando o titulo do anúncio que você está pegando através do `<%anuncio.getTitulo%>` ultrapassar o número **X** de letras será exibido `...` no título, isso?
Comment: Se for isso mesmo que você quer fazer, jogue o retorno do seu get `<%anuncio.getTitulo%>` dentro de uma variável string e utilize o método `length()` que te retorna o numero de letras de uma variável **String**, faça uma condição, se esse número retornado ultrapassar o número de letras que você quer basta mandar exibir `...` senão exibe `<%anuncio.getTitulo%>` mesmo
Answer: Java Servlet 3.0 ou superior
Caso você esteja utilizando a Java Servlet versão 3.0 ou superior você pode usar esse trecho de código:
<lable><c:out value="${anuncio.getTitulo().length() <= maxSize ? anuncio.getTitulo() : anuncio.getTitulo().substring(0, maxSize).concat('...')}" /></lable>

maxSize é o tamanho máximo que você quer no label.
Se você vai utilizar isso em vários locais, criar um tagfile é uma boa opção.
Java Servlet inferior a versão 3.0
Outra opção, caso você esteja utilizando uma versão inferior a Java Servlet 3.0 é utilizar o seguinte scriptlet:

    <%
        int maxSize = 5;
        String titulo = anuncio.getTitulo();
        out.println(titulo.length() <= maxSize ? titulo : titulo.substring(0, maxSize).concat("..."));
    %>

Comment: Funcionou com a segunda opção. Obrigada!
Answer: Você pode tambem fazer essa tratativa utilizando somente HTML e CSS:

label{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    word-wrap: hyphenate;
    max-width: 100px;
    display: block;
}
label > span{
  overflow: hidden;
}

    Isso é um texte com um label muito grande

Abraço
Answer: Não sei como fazer isto em jsp, mas em javascript direto no html seria o seguinte:
em js:
Estou num projeto e-commerce, e preciso exibir o nome de um produto

(function(){
var element = document.getElementById("label");
element.innerHTML  =
                        //@inicio, //@comprimento
 element.innerHTML.substr(0, 10)+"...";
})()

O código substitui o texto do elemento pelo seu próprio texto "quebrado" em uma quantidade x de caracteres (incluindo espaços) e concatena com "..."
https://jsfiddle.net/a5r375eb/

Como limitar os caracteres de um label?


Replace inner HTML of a div with Ajax response

Question: i am trying to change inner HTML of a div after some interval.
i am getting right response which i want with Ajax.
but unable to replace inner HTML of selected after and with Ajax response.
what is wrong with my code..
Html

    51 seconds ago

    58 seconds ago

.
.
.
.
.

    10 minute ago

j query
setInterval(function() {
            $( ".time" ).each(function( index ) {
                var sendTime=  $(this).attr("data-time");
                dataString = "sendtime="+sendTime+"&q=convertTime";
                $.ajax({
                    type: "POST",
                    url: "data_handler.php",
                    data: dataString,
                    cache: true,
                    success: function(response) {
                        alert(response);
                        $(this).html(response);
                        //alert(response);
                    }
                });
            });
        }, 5000);

Comment: What happens when you run it?
Answer: this is the window in the callback. Use the value given to the callback of each :
        $( ".time" ).each(function(index , elem) {
            var sendTime=  $(this).attr("data-time");
            dataString = "sendtime="+sendTime+"&q=convertTime";
            $.ajax({
                type: "POST",
                url: "data_handler.php",
                data: dataString,
                cache: true,
                success: function(response) {
                    alert(response);
                    $(elem).html(response);
                }
            });
        });

You don't need to define a new variable to protect this as jQuery already does it for you.
Answer: As you are using an asynchronous function with a callback, this in your callback doesn't come from the same context. You need to save this in a variable used in the callback.
Try like this:
setInterval(function() {
            $( ".time" ).each(function( index ) {
                var sendTime=  $(this).attr("data-time");
                dataString = "sendtime="+sendTime+"&q=convertTime";
                var self = this;
                $.ajax({
                    type: "POST",
                    url: "data_handler.php",
                    data: dataString,
                    cache: true,
                    success: function(response) {
                        alert(response);
                        $(self).html(response);
                        //alert(response);
                    }
                });
            });
        }, 5000);

Comment: This adds useless code : jQuery declares a variable already... See my answer.
Answer: I think $(this) is out of context. Try:
setInterval(function() {
            $( ".time" ).each(function( index ) {
                var $this = $(this);
                var sendTime=  $(this).attr("data-time");
                dataString = "sendtime="+sendTime+"&q=convertTime";
                $.ajax({
                    type: "POST",
                    url: "data_handler.php",
                    data: dataString,
                    cache: true,
                    success: function(response) {
                        alert(response);
                        $this.html(response);
                        //alert(response);
                    }
                });
            });
}, 5000);

Answer: setInterval(function() {
        $( ".time" ).each(function( index ) {
            var sendTime=  $(this).attr("data-time");
            var _thisvariable = $(this);
            dataString = "sendtime="+sendTime+"&q=convertTime";
            $.ajax({
                type: "POST",
                url: "data_handler.php",
                data: dataString,
                cache: true,
                success: function(response) {
                    alert(response);
                    _thisvariable.html(response);
                    //alert(response);
                }
            });
        });
    }, 5000);


.cauchy integral formula.

Question: $\int \frac{e^{zt}}{\sinh z} \mathrm{d}z$ and $|z|=8$ this is the problem about Cauchy integral formula. I keep making a mistake and find the wrong solution. Can you help me?
So, we know the Cauchy integral formula $\frac{1}{2πi}\int \frac{f(p)}{z-p} \mathrm{d}p$ and since $|z|=8$ then we get $p=0,πi,2πi$ ($\sinh z=\frac{e^z-e^{-z}}{2}$).

for $p=0$,   $f(p)=\frac{2e^{zt} \cdot e^z}{e^z+1}$ and this is equal to $1$.
for $p=πi$,  $f(p)=\frac{2e^{zt} \cdot e^z}{e^z-1}$ and this is equal to $\cos πt+i \sin πt$.
for $p=2πi$, $f(p)=\frac{2e^{zt} \cdot e^z}{e^z+1}$ and this is equal to $\cos 2πt+i \sin2πt$.

Finally,
$\left((\cos 2πt+i \sin2πt)+(\cos πt+i \sin πt)+1 \right) \cdot 2πi$ but apparently this is not the correct solution.
Thanks for help.
Comment: What about $-\pi i$ and $-2\pi i$?
Comment: @daniel: I did not consider those. but for p=-πi f(p)=cosπt-isinπt and for p=-2πi f(p)=cos2πt-isin2πt. and finally for all (p=0,πi,2πi,-πi,-2πi) the solution is (1+2cosπt+2cos2πt)2πi but the answer says (1-2cosπt+2cos2πt)2πi can you point out what else I make a wrong?
Answer: The zeros of the denominator $\sinh z$ are all simple, so the residue of
$$\frac{f(z)}{\sinh z},$$
where $f$ is a holomorphic function, in $k\pi i$ is
$$\operatorname{Res}\left(\frac{f(z)}{\sinh z}; k\pi i\right) = \frac{f(k\pi i)}{\sinh' (k\pi i)} = \frac{f(k\pi i)}{\cosh (k\pi i)} = (-1)^k f(k\pi i).$$
Thus we have
$$\begin{align}
\int_{\lvert z\rvert = 8} \frac{e^{zt}}{\sinh z}\,dz &= 2\pi i \sum_{\lvert \zeta\rvert < 8} \operatorname{Res}\left(\frac{e^{zt}}{\sinh z}; \zeta\right)\\
&= 2\pi i \sum_{k=-2}^2 (-1)^k e^{k\pi i t}\\
&= 2\pi i\bigl(1 - 2\cos (\pi t) + 2 \cos (2\pi t)\bigr)
\end{align}$$
in agreement with the official solution.
I must admit that I don't understand your

for $p=0$,   $f(p)=\frac{2e^{zt} \cdot e^z}{e^z+1}$ and this is equal to $1$.

etc. The right hand side does not depend on $p$. If you use Cauchy's integral theorem to replace the circle $\lvert z\rvert = 8$ with small circles around each of the zeros of the denominator so that you can apply the integral formula for each of the small circles, you still would need to write the integrand in the form $\dfrac{g(z)}{z-k\pi i}$, which leads to
$$g(z) = \frac{(z-k\pi i)e^{zt}}{\sinh z} = \frac{2(z-k\pi i)}{e^{2z}-1}e^{z(t+1)} = \frac{2(z-k\pi i)}{e^{2(z-k\pi i)}-1}e^{z(t+1)},$$
and the first factor of that tends to $\dfrac{1}{\exp'(0)} = 1$ for $z\to k\pi i$, so we obtain $g(k\pi i) = e^{k\pi i(t+1)} = (-1)^ke^{k\pi it}$ in accordance with the residues computed above.

.cauchy integral formula.


Conversão de dados factor para numeric

Question: No seguinte exemplo:
> str(rhm)
'data.frame':   24 obs. of  4 variables:
 $ plant     : Factor w/ 1 level "LaR": 1 1 1 1 1 1 1 1 1 1 ...
 $ time      : int  0 0 0 0 3 3 3 3 7 7 ...
 $ Tratamento: Factor w/ 4 levels "T1pH1","T1pH2",..: 1 2 3 4 1 2 3 4 1 2 ...
 $ wt        : Factor w/ 20 levels "0,0013","0,0017",..: 20 20 20 20 10 16 18 17 12 19 ...
> str(unclass(rhm$wt))
 atomic [1:24] 20 20 20 20 10 16 18 17 12 19 ...
 - attr(*, "levels")= chr [1:20] "0,0013" "0,0017" "0,0036" "0,0045" ...

Ao tentar transformar a variável wt em número, ao invés de "0,0013", "0.0017"... aparecem:
as.numeric(rhm$wt)
[1:24] 20 20 20 20 10 16 18 17 12 19 ...

Como converter wt para números?
Tentei duas formas sugeridas em fórum:
as.numeric(as.character(rhm$wt))
as.numeric(levels(rhm$wt))[rhm$wt]

Contudo ocorre a substituição dos meus dados por NAs:
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
Warning message:
NAs introduced by coercion

Como posso transformar meus dados corretamente?
Answer: No R o separador de casas decimais é ..
Para o seu código funcionar você tem duas opções:
Usar o seguinte código para converter factor em numérico:
as.numeric(gsub(",", ".", as.character(rhm$wt)))

A função gsub com esses argumentos troca todas as vírgulas por ponto. Em seguida o R consegue converter de chr para numeric. Veja esse exemplo simples:
> as.numeric("0,1")
[1] NA
Warning message:
NAs introduced by coercion
> as.numeric(gsub(",", ".", "0,1"))
[1] 0.1

Outra forma é: na leitura dos dados, que você provavelmente está usando o read.table. Usar o argumento sep = "," indicando que o seu separador de casas decimais é ,.
Comment: Só lembrando que a opção 2, de corrigir na leitura dos dados, é bem mais interessante pois resolve o problema para todas colunas de uma vez (se for o caso) e usa menos caracteres.
Comment: Obrigada! Resolvido!

Conversão de dados factor para numeric


A modular equation of 23rd degree of Dedekind's $\eta$ function.

Question: Regarding the Post Additional values of Dedekind's $\eta$ function in radical form
 I wrote the equation that has as root the value $\frac{\eta(23i)}{\eta(i)}$  that is missing.
Can someone help me solve (in radical form) the following equation, whose solution is the value of Dedekind's modular $\frac{\eta(23i)}{\eta(i)}$ function?
$$x^{48}+\frac{684}{23^{5}}x^{36}-\frac{2496}{23^{7}}x^{32}+\frac{10944}{23^{9}}x^{28}+\frac{3826738}{23^{11}}x^{24}-\frac{31577472}{23^{13}}x^{20}+$$
$$\frac{785460096}{23^{15}}x^{16}-\frac{2112004548}{23^{17}}x^{12}+\frac{4240221504}{23^{19}}x^{8}+\frac{18998208}{23^{21}}x^{4}-\frac{1}{23^{23}}=0$$
where
$$x=\frac{\eta(23i)}{\eta(i)}.$$
This equation comes from the work of L. Kiepert and specializes for the value reported in the title of the application. My intent is to find the solution in closed form.
Comment: $x\approx \frac1{316}$
Comment: Your equation is correct and it splits into two sextics over $\mathbb{Q}[23]$ but solution in radicals is not possible. That is, if $s=\sqrt{23}$,and $y=(sx)^4$, then
$0 = y^6 + 4sy^5 +(184-108s)y^4 +(-2070+548s)y^3 +(142232+8820s)y^2 +(-132480+27796s)y +(264845-55224s)$.
Comment: @Peter Foreman-Excellent approximation!
Comment: @Somos-That's a good question! But I don't have the answer.--By the way, what news about Berndt?
Comment: @Somos-You should try to solve the equation and you will see that the solution is very accurate!
Answer: After substitution $x^4\to x,$ we get a 12-degree equation that factors into cubics over the rationals extended with $\sqrt{23}$ and $\sqrt2\cdot\sqrt[4]{23\,}$. Solving the cubic equation, we get
$$\small\begin{align}
\!\!\frac{\eta(23i)}{\eta(i)}&=\\
&\!\!\!\!\!\!\sqrt[4]{\frac{2\cdot 2^{2/3} \sqrt[3]{\alpha }+\sqrt[3]{\frac{2}{\alpha }} \left(360 \sqrt{23}+9 \sqrt{2} \cdot23^{3/4}-1426-525 \sqrt{2}\, \sqrt[4]{23}\right)-8 \sqrt{23}+6 \sqrt{2}\,\sqrt[4]{23}
   \left(3+\sqrt{23}\right)}{6348}},
\end{align}$$
where
$$\small\alpha =32 \sqrt{23} \left(38-9 \sqrt{3}\right)+2484 \left(9 \sqrt{3}-4\right)-9 \sqrt{2}\, \sqrt[4]{23} \,\left(717-454 \sqrt{3}+139 \sqrt{23}+62 \sqrt{69}\right).$$

A modular equation of 23rd degree of Dedekind’s $\eta$ function.