Is this a good generating function for Sum-of-divisors function?

Question: I have an expression for the sum-of-divisors function defined as $$\sigma(n)=\sum_{d\mid n}d.$$
However I do not know how nontrivial or practical it actually is.
Let us define $$A=\frac{b}{2}-\frac{b}{\pi}\sum_{n=1}^\infty{\frac{\sin{\frac{2\pi nx}{b}}}{n}}=x\pmod b$$ where, when $\frac{x}{b}$ is a whole number, $A=\frac{b}{2}$
Now define $$B=\lim \limits_{n\to\infty}\frac{b}{2}-\frac{b}{\pi}\tan^{-1}\left(\cot\left(\frac{\pi x}{b}+\frac{1}{n}\right)\right)=x\pmod b$$ where, when $\frac{x}{b}$ is a whole number, $B=0$.  The limit helps avoid division by zero in certain cases, but can be excluded in theory.
Now $$\sum_{b=1}^x A-\sum_{b=1}^x B=\frac{\sigma(x)}{2}.$$
So then $$\sigma(x)=2\left(\sum_{b=1}^x A-\sum_{b=1}^x B\right).$$
Can't this be considered a generating function for the $\sigma(x)$?  If so, why hasn't it been seen before?  Is this function somehow trivial?
Comment: I'm not sure that that's what "generating function" means. A(n ordinary) generating function of $\sigma(n)$ would be the function $\sum_{n=0}^\infty\sigma(n)x^n$. (There are other types of generating function, such as exponential or Dirichlet (di-ri-CLAY, sometimes di-ri-SHLAY).)
Comment: This classical [Dirichlet series](https://en.wikipedia.org/wiki/Divisor_function#Series_relations)  is a [generating function](https://en.wikipedia.org/wiki/Generating_function) for $\sigma_a$ (with $a=1$ in your case) :$$\zeta(s)\,\zeta(s-a)=\sum_{n=0}^\infty\frac {\sigma_a(n)}{n^s}$$
Answer: A Generating function can be defined as a generating function is a formal power series in one indeterminate, whose coefficients contain information about a sequence of numbers $a_n$ which is indexed by the natural numbers.
What you gave is not a formal power series and hence not a generating function. $\sigma(n)$ is an arithmetic function , its formal power series is the  Dirichlet series which for an arithmetic function $f(n)$ is of the form
$$ \ F(s)=\sum_{n=1}^{\infty}\frac{f(n)}{n^s}$$
And hence as Raymond Manzoni mentioned in his comment the generating function for $\sigma(n)$ is $$\zeta(s)\,\zeta(s-1)=\sum_{n=0}^\infty\frac {\sigma_1(n)}{n^s}$$


Using SQL Profiler on a database that's in production

Question: As a developer, I use SQL Profiler quite often. It's a good debugging tool, both to track what my code is doing and to analyse performance problems.
But I've always used it on my development environment, and in a very controlled way.

Start my application, and get it into a specific state
Start the profiler
Perform a specific sequence of actions on my application
Stop the profiler and examine the results.

Can the SQL Profiler be practically used in an in-production environment?
My first concern is that it would degrade the performance.
My second concern is that, because it's in production, you aren't triggering the interesting actions itself. You would have to leave the profiler running for a long period then analyse the results. Would the result set become too unwieldy? (Taking up too much disk space and being too hard to query).
Does anyone use the SQL Profiler in production?
Full disclosure: I've posted the same question on the Database Administrators Beta Site.
Serverfault members who want to support the DBA stackexchange site have the opportunity to answer the question there rather than here.
Comment: possible duplicate of http://serverfault.com/questions/176501/how-do-i-properly-set-up-sql-server-profiler-in-a-production-environment
Answer:
Yes, the act of monitoring will require some resources. Running it on an overloaded server could kill it.
You'll actually monitor real life load: your actions could get lost in the noise of this load.

We run it on production sometimes. Mainly with a text filter for specific code, or with CPU/duration filters to trap longer running. And we don't try to capture XML execution plans or some such nonsence
The key is to know what you are looking for: we don't tend to leave it running and trap everything.
In this case, if you want to see the results of some actions can you do it out of hours?
Comment: I agree with gbn, it definitely requires resources, so you'll need to be careful when running it.  We typically use it with a filter on the login to debug the action(s) of a particular user for a specific problem.  We also periodically run a trace for the whole day to gather information.  Something like this definitely needs to be scheduled on days with lighter loads, and needs to be very closely watched.  It also helps the load to log to local files on another computer and then process the data afterwards.


how to compute the cohomology ring of grassmannian G(4,2)

Question: I need to compute the ring of cohomologies over the integers of the complex grassmannian G(4,2).
As I understand, one can use the Schubert cells and cellular homology to show that the homology groups of G(4,2) are free abelian with bases corresponding to the appropriate Schubert cells.
And the cohomology groups have the same structure, am I right?
Now - I want to understand how the cup product looks like in this case without using some general formulas (like Pieri's or Giambelli's) which seem to be hard to prove. How can I do that? I don't understand how one can compute cup products using cellular cohomology.
Thank you.
Comment: Only the Euler characteristic is discussed [here](http://math.stackexchange.com/q/45292/11619), but the answers (other than mine) may have useful references?
Answer: I don't know, how can one compute product for cellular cohomology, maybe using some tricks.
In case complex grassmannian $G(4,2)$ Schubert cells give you that $H^0=H^2=H^6=H^8=\mathbb Z$ and $H^4=\mathbb Z^2$ (other are zero). Define their generators by $a_2,a_4,a_4',a_6$ and $a_8$. Some theorem about cohomology of a manifold (I don't remember the name) gives us $a_2\cdot a_6=a_8$. And considering cell subspace $\mathbb CP^2=G(3,2)\subset G(4,2)$ shows that $a_2^2=a'_4$.
[Instead this you may write down a spectral sequence for $U(2)$-fibration $V(4,2)\to G(4,2)$]
To show that $a'_4\cdot a_4=0$ consider two Schubert $4$-cells of $G(4,2)$: for basis $v_1,v_2,v_3,v_4\in\mathbb C^4$ they defined as sets of hyperplanes $\langle sv_1+v_2,\,tv_1+v_3\rangle$ and $\langle sv_2+tv_3+v_4,\,v_1\rangle$ for complex parameters $s,t$. Therefore cocycles $a_4$ and $a'_4$ are Poincare-dual for submanifolds $M':=\{W\in G(4,2):W\subset\langle v_2,v_3,v_4\rangle\}$ and $M:=\{W\in G(4,2):W\ni v_1\}$ (because intersection cell with corresponding submanifold is transversal). $M\cap M'=\emptyset$, thus $a'_4\cdot a_4=0$, $a_2\cdot a_4=0$. Also observe that self-intersection indices of $M$ and $M'$ are $1$, therefore $a_4^2=a_4'^2=a_8$.
So, $H^*(G(4,2))=\mathbb Z[a_2,a_4]/(a_2^5,\,\,a_2\cdot a_4,\,\,a_4^2-a_2^4)$.
Comment: Very nice explanation.
Comment: The first relation $a_2^5$ is generated by the other two, thus you do not need it.


$\mathbb{Z}$ (in $\mathbb{R}$) has no limit points (sequential)

Question: Our definition of limit point is that $p$ is a limit point if there exists a non-constant sequence in $\mathbb{Z}$ that converges to $p$.
How can I prove that there don't exist any sequences in $\mathbb{Z}$ that converge?
Comment: Use $\varepsilon=1/4$.
Answer: Use the definition of convergence: choose a small neighborhood around $p$ that doesn't contain any other integers, and show that any sequence of integers satisfying the convergence criteria is necessarily constant.
(Actually, precisely, it is eventually constant; for instance, the sequence $\{1,2,2,2,\dots,2,\dots\}$ is non-constant, and converges to $2$, but is not what you want to allow here)
Answer: Your definition of limit point is wrong. The sequence
$$
a_n=\begin{cases}
0 & \text{if $n=0$}\\
1 & \text{if $n>0$}
\end{cases}
$$
is not constant and clearly converges to $1$. But $1$ is not a limit point of $\{0,1\}$ in $\mathbb{R}$, because $\{0,1\}$ consists of two isolated points.
The correct definition is

$p$ is a limit point of $S\subseteq \mathbb{R}$ if there exists a non eventually constant sequence in $S$ converging to $p$.

A sequence $(a_n)$ is eventually constant if there is $N$ such that, for $n\ge N$, $a_n=a_N$.
Now, if $(a_n)$ is a sequence in $\mathbb{Z}$ that converges to $p$, it is eventually constant. Indeed, there is $N$ such that, for $n\ge N$, $|a_n-p|<\frac{1}{4}$. In particular, for $n\ge N$,
$$
|a_N-a_n|=|(a_N-p)+(p-a_n)|\le|a_N-p|+|p-a_n|<\frac{1}{4}+\frac{1}{4}=\frac{1}{2}
$$
and therefore $a_n=a_N$. So the sequence is eventually constant.
Answer: Hint
If a sequence in $\Bbb R$ converges, it is a Cauchy sequence, but if the terms of a sequence $\{a_n\}$ are different integers, then $|a_p-a_q|\ge 1$.


Like query in mongodb to match any wording out of the name in PHP

Question: I am working on a app where i am implementing the web api in flight framework. I am using mongodb database & want to do "Like" query in the database to retrieve records where the restaurant name matching the given words anywhere in its name.
I am doing this with following way :
<code>    $mongoDb = MongoDbConnector::getCollection('restaurants');
        $regex = new MongoRegex('/\b' . $restaurantName . '\b/i');
            $restaurantListDataCount = $mongoDb->find(array('city' => $city, 'name' => $regex))->count();
</code>
thing is i am getting count as 0 here even though more than 100 records having the particular string i am searching for exists in its name.
How the regex be in a way modified to make it work?
Answer:
Just Change like that

<code>  $regex = new MongoRegex('/.*' . $restaurantName . '.*/i');
</code>
Comment: Exactly what i want. Thanks


Hospedagem de web service é igual a um site com páginas?

Question: Estou desenvolvendo uma aplicação mobile com Xamarin. Essa aplicação é uma tela para autorizar ou não desconto acima do autorizado pelos vendedores. Então, tenho um web service que vai no banco e pega todas as informações pertinentes ao cliente e alimenta o aplicativo que estará na mão de quem tem poder para autorizar.
O web service deverá ser hospedado da mesma forma que um site? Nesse caso, provavelmente em uma intranet, provavelmente, eu ainda não tenho certeza.
Answer: A hospedagem essencialmente sim. Ou não, depende da tecnologia usada, mas não da funcionalidade.
Pelas tags está usando a Web API, o que me parece correto. O que diferencia esta tecnologia do MVC é que ela não gera uma view tradicional e sim um dado a ser processado pelo cliente. A forma que isto vai servidor não muda nada.
Se tiver algum motivo para hospedar de forma diferente é requisito da aplicação não porque é um web service.
Comment: Big, vamos usar webapi como back end e serviços Rest para isso e o mobile(front) vai consumir isso. Essa pergunta o cliente me fez, em relação a hospedagem.
Comment: Ou seja, pela resposta do Bigown, eu vou fazer uma hospedagem normal, como eu faço em um site e correr para o abraço


Dimensions of log likelihood for Gaussian process

Question: The log-likelihood for a Gaussian process is given by
$$\log p(y|X) = -\frac{1}{2}y^T(K+\sigma^2_n I)^{-1}y - \frac{1}{2}\log|K+\sigma^2_n I|-\frac{n}{2}\log2\pi$$
[See here: https://stats.stackexchange.com/questions/280105/log-marginal-likelihood-for-gaussian-process]
I don't understand how one would compute this, as to my eyes the dimensions don't match up. The first term $-\frac{1}{2}y^T(K+\sigma^2_n I)^{-1}y$ yields just a number, but the second term $\frac{1}{2}\log|K+\sigma^2_n I|$ is a matrix. Am I going wrong in my thinking here?
Comment: The expression you wrote is not log-likelihood, it is log-marginal-likelihood. They both are very very different. The likelihood of a Gaussian process is $p(y|f) = \mathcal{N}(f, \sigma_n^2)$. [reference](http://mlg.eng.cam.ac.uk/teaching/4f13/1920/gp%20and%20data.pdf) slide 4.
Answer: The second term is the determinant of the covariance matrix
$$
|K + \sigma^2_nI| = \det(K + \sigma^2_nI),
$$
which is a polynomial function that outputs a scalar value.


Tilting a line and a cloud of 3D points around the line

Question: I have a line defined by two points, $q_1$ and $q_2$, and a cloud of three-dimensional points around the line, $Q$.
I rotate, but do not dilate/stretch the line by moving $q_1$ to some $t_1$ and $q_2$ to some $t_2$.  In other words, the Euclidean distance between $q_1$ and $q_2$, and between $t_1$ and $t_2$, is the same.  How do I correspondingly map the points to this new orientation s.t. their positions relative to the line remain unchanged?
Note that the full set of equations for rotations about an arbitrary axis are provided here:
http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/
For convenience, below I provide the Mathematica input for a rotation matrix about an arbitrary axis defined by points $P_1 = (a,b,c)$ & $P_2 = (d,e,f)$, with direction vector $<u,v,w> = (d-a,e-b,f-c)$, where "theta" = $\theta$ is the rotation angle (in radians), and where $L = (u^2+v^2+w^2)$.  The three-dimensional point to be rotated is given by $(x,y,z)$.
RotationMatrixArbitraryLine =
{((a*(v^2 + w^2) - u*(b*v + c*w - u*x - v*y - w*z))*(1 -
          Cos[theta]) + L*x*Cos[theta] +
      L^(1/2)*(-c*v + b*w - w*y + v*z)Sin[theta])/
    L, ((b(u^2 + w^2) - v*(a*u + c*w - u*x - v*y - w*z))*(1 -
         Cos[theta]) + L*y*Cos[theta] +
      L^(1/2)*(c*u - a*w + w*x - u*z)Sin[theta])/
    L, ((c(u^2 + v^2) - w*(a*u + b*v - u*x - v*y - w*z))*(1 -
         Cos[theta]) + L*z*Cos[theta] +
      L^(1/2)*(-b*u + a*v - v*x + u*y)*Sin[theta])/L}
The above expression works on the tests I have provided.  For example, a $\theta = \frac{\pi}{4}$ degree rotation of the point {0,0,1} about direction vector {1,0,0} maps the point to {0,-1,0}.  Changing the direction vector to {0,1,0} maps the same point to {1,0,0}.
Comment: Actually, I think there is a good way of stating which particular rotation you want. You could demand that the axis of rotation is orthogonal to both $(q_2-q_1)$ and $(t_2-t_1)$.
Comment: Note that mapping $q_i$ to $t_i$ only fixes the transformation up to rotations about the line (and mirroring, but I suspect you're looking for orientation-preserving transformations). In other words, it is not uniquely determined where a point should go since you can rotate all of them together about the line. For the sake of clarity: does it matter in your problem which rotation angle about the line is chosen?
Comment: @DaanMichiels No it doesn't matter, since $Q$ is actually a set of random points over symmetric space around the line.  However, if we're going to aim for something, I suppose it would be to minimize the amount of rotation of the point set?
Comment: I don't see a good way to determine what is "minimal" rotation, as a I don't see a good way to determine the absolute amount of rotation about the line. Indeed, if I did, I would try to come up with a solution having no rotation. I think you can only say that one configuration is rotated so-and-so-much relative to another one, but you cannot measure it absolutely, much like in physics you cannot measure how fast an object moves *absolutely*, only relative to other objects. I think we should just aim for "the rotation doesn't matter".
Comment: @DaanMichiels That sounds like a perfectly good metric to me.
Answer: You are looking for a linear (or affine) isometry which maps $q_1$ to $t_1$ and $q_2$ to $t_2$.
First map $q_1$ to $t_1$. This gives a translation $x\mapsto x + t_1 - q_1$. call this map $T$.
Then the vector $q_2-q_1$ is mapped to $t_2-t_1$. This will be a rotation, which we compute in the following steps -

The vector $u=(q_2-q_1)\times(t_2-t_1)$ (cross product) is perpendicular to the plane spanned by these vectors. Consider $a$ to be the corresponding unit vector. Also let $b$ and $c'$ be the unit vectors in the directions $q_2-q_1$ and $t_2-t_1$. Clearly $a$, $b$ and $c=a\times b$ are a set of orthonormal vectors. We use this basis in place of usual $k$, $i$ and $j$ (note the order).
let us say the angle between $q_2-q_1$ and $t_2-t_1$ is $\theta$. We want to rotate the plane spanned by $b$ and $c$ such that $b$ is rotated towards $c$   by an angle $\theta$. [draw a diagram and the various orientations will be clear]
for any vector $x$, its components along $a$, $b$ & $c$ are $(x.a)a$, $(x.b)b$  & $(x.c)c$. So we can write $$x=\left(\begin{array}{c}x.a\\x.b\\x.c\\\end{array}\right)$$ To write the rotation map we observe that in our chosen basis $$\left(\begin{array}{c}1\\0\\0\\\end{array}\right)\mapsto \left(\begin{array}{c}1\\0\\0\\\end{array}\right)$$ $$\left(\begin{array}{c}0\\1\\0\\\end{array}\right)\mapsto \left(\begin{array}{c}0\\\cos\theta\\\sin\theta\\\end{array}\right)$$ $$\left(\begin{array}{c}1\\0\\0\\\end{array}\right)\mapsto \left(\begin{array}{c}0\\-\sin\theta\\\cos\theta\\\end{array}\right)$$ Write the matrix of that map, call it $M$. I leave that as an exercise.
Now I will write the final rotation map $R$ - $$x\mapsto M(x-t_1)+t_1$$ Where every vector is expressed in our chosen basis. [Work out this final expression as one more exercise]

The final affine map is given by the composition of the two maps translation $T$ followed by rotation $R$. This is not unique. There could be many more maps which will do your job.
Comment: How do you find the angle $\theta$?
Comment: @magguu Could you provide an example to make sure I understand?
Comment: @DaanMichiels $\cos\theta = (q_2-q_1).(t_2-t_1)/\big(\|q_2-q_1\|.\|t_2-t_1\|\big)$ ... actually you do not need $\theta$. you just need $\cos\theta$ and $\sin\theta$. use the sin-cos identity to find it.
Comment: @AffiDavid Take $q_1=0$, $t_1=0$. then there is no translation map. actually figuring out the translation is trivial so i am leaving it out.

now take $q_1=(1,0,0)$ and $t_1=(0,1,0)$. clearly you have to rotate the $q$ line towards the $t$ line by $90^{\circ}$. This is all that you need to do in this example. try to draw the points and lines on a black board and it will all be clear.
Comment: @magguu - My point is mainly: how do you find the sign of the sine? (That sounds funnier than anticipated.)
Comment: My analysis assumes that the angle is between $0$ and $\pi$. in this domain sine is always positive. if you think about it, the angle between two vectors can never exceed $\pi$ and so we are safe.
Comment: @Daan: The sign of the angle is always positive. If you move the $q_i$ around trying to make it negative, the cross product flips and starts pointing the other way instead, and relative to that vector the angle is positive again.
Comment: @RahulNarain - Yes, you are right of course.
Comment: since no one commented about it. let me add something more - after the transaltion part is done ... there are many ways to align the lines .... in the above solution i have used a rotation ... but one cud use a mirror image flip about the angular bisector line.

and if the dimension of the ambient space is more than 3, there are many more options.


How to improve JPA Query performance and response time on multiple Join tables and conditions

Question: I am very fresh java beginner and I am trying to implement possibility to review documents. User, who belongs to a certain group can review documents of particular types that are assigned to that group's review document types. User can not review own documents. When user belongs to many groups that can review many document types, sometimes I get about 1500~ documents that meet query condition. I tried paging, but still there are some visible latency in front page. When I fetch all documents (~1500) it takes about 3000+ ms. I am not sure if it is a lot or not. My JPA query is below.
    @Query("SELECT d FROM Document d WHERE d.id IN (SELECT DISTINCT d.id FROM Document d" +
        " JOIN d.documentType dt" +
        " JOIN dt.reviewUserGroups rug" +
        " JOIN rug.users u WHERE u.username = :username" +
        " AND d.documentState = it.akademija.wizards.enums.DocumentState.SUBMITTED" +
        " AND u <> d.author" +
        " AND (lower(CONCAT(d.author.firstname, ' ', d.author.lastname)) like %:searchFor% " +
        " OR lower(d.title) like %:searchFor%" +
        " OR lower(d.description) like %:searchFor%" +
        " OR lower(d.id) like %:searchFor%" +
        " OR lower(dt.title) like %:searchFor%))")
    Page<Document> getDocumentsForReview(@Param(value = "username") String username,
                                     @Param(value = "searchFor") String searchFor,
                                     Pageable pageable);

Please let me know what is the best way to improve performance, because I have some feeling that this type of search using "like" multiple times in query and joining through many Entities is not the right one.
Comment: You have to use indexes, btree for equals, and fulltext for likes.
Comment: Can you share the database definition in order to analyze if you're using proper indexes?
Comment: Can you please clarify what do you mean by database definition. At the moment I have not indexed anything. Hibernate creates table automatically on start up. I did not put any indexing information in entities and it would be great if you can share some documentation or tutorial how to properly index fields in entities with multiple joins (as per query provided). I am not using entity manger, just JPARepository implementation.
Answer: Use fulltext search instead of like. Create Fulltext index  for that, see http://www.h2database.com/html/tutorial.html?highlight=fulltext&search=fulltext#fulltext


How to proceed from the level 2 and up in a Discrete Wavelet Transform Daubechies kind 4

Question: The wavelet elements of a Daubechies kind 4 are
$$(0.4830, 0.8365, 0.2241, -0.1294) $$
Let's say I have the following signal array
$$ [1, 2, 0, 4, 5, 6, 8, 10 ]$$
Doing a Daubechies 4 DWT of this array is basically multiplying a $8\times 8$ array with a $8\times 1$ array (signal).
The $8\times1$ array will have the following elements,
\begin{array}{cccc} 0.483 & 0.8365 &0.2241 &-0.1294 &0 &0 &0 &0 \\
 0 &0 &0.483 &0.8365 &0.2241 &-0.1294 &0 &0 \\
 0 &0 &0 &0 &0.483 &0.8365 &0.2241 &-0.1294 \\
0.2241 &-0.1294 &0 &0 &0 &0 &0.483 &0.8365 \\
-0.1294 &-0.2241 &0.8365 &-0.483 &0 &0 &0 &0 \\
0 &0 &-0.1294 &-0.2241 &0.8365 &-0.483 &0 &0 \\
0 &0 &0 &0 &-0.1294 &-0.2241 &0.8365 &-0.483 \\
0.8365 &-0.483 &0 &0 &0 &0 &-0.1294 &-0.2241 \\
\end{array}
The result will be
for the scaling function...
- 0 : 1.638357430415108
- 1 : 3.6903274198537357
- 2 : 7.9329681069730205
- 3 : 12.194191165473843

for the wavelet
- 0 : -2.5095489112134235
- 1 : 0.3882285676537802
- 2 : -0.1294095225512608
- 3 : -3.4061243833814774

Sorry but my math is rusty. I don't know the exact terms for these two elements that come from the DWT decomposition. Some call, scaling function and wavelet, others call trend subsignal and fluctuation, others call c and d... etc.
Anyway, now I need to perform another level of DWT DB4, what values do I send to the algorithm that will perform the decomposition? The scaling function c or the wavelet d?
and what about the inverse transformations?
Answer: The inverse of this step of the transform will be the inverse matrix to the matrix you wrote above. Mechanically just build a matrix of the values you wrote, and then invert this matrix. The Db4 should be designed so that this inverse matrix will be the same (up to maybe a scaling / normalization factor / transpose), which is what makes orthogonal wavelets so simple to use. We only need one filter pair two short arrays of numbers.
Makes programming simpler and/or memory overheads slimmer than if we needed separate filters for forward and backward transform.
Usually in discrete wavelet transforms you iterate on the low-pass channel, which is the output from the scaling function or father wavelet. This is called dyadic decomposition, You can read more here. At every level you don't stop you will only have "result" of the mother wavelet. These are the "detail" coefficients at this level of resolution. At the lowest level of resolution (where you stop the transform) you will also have "approximation" coefficients, which come from the father wavelet function belonging this coarsest scale.
There also exist wavelet packet analysis, where you can iterate also on the high-pass band (where mother wavelets live) and not only on the low-pass band (where father wavelets live). But these packet analyses are probably a bit over-course.
What happens at next level is that for the coefficients of the high pass filter you put an identity matrix $I$ and for the coefficients of the low pass filter coefficients you put a subsampled version of original matrix.
We can see by ocular inspection that high pass filter comes last in the 8x8 matrix, so those are the elements which will be affected by the $I_4$ block.
$$\begin{bmatrix}D&0\\0&I_4\end{bmatrix}$$
The "$D$" here will be the 4x4 size transform matrix for Db4. If we write it out it will look like this:
$$\left[\begin{array}{cccc|cccc}0.483&0.8365&0.2241&-0.1294&0&0&0&0\\0.2241&-0.1294&0.483&0.8365&0&0&0&0\\ -0.1294&-0.2241&0.8365&-0.483&0&0&0&0\\0.8365&-0.483&-0.1294&-0.2241&0&0&0&0\\\hline0&0&0&0&1&0&0&0\\0&0&0&0&0&1&0&0\\0&0&0&0&0&0&1&0\\0&0&0&0&0&0&0&1\end{array}\right]$$
With lines to clarify the block-structure. Now when you have both transform matrices, what remains is to find their inverses, and for ON transform, Inverse is equal to transpose, so this is easily done.
Comment: brilliant!!!!!!!!!!! thanks. Fantastic explanation.
Comment: Thanks for the answer but this is my problem. Suppose I take an array with 8 elements and decompose it with DWT DB4. I get two arrays with 4 elements. Let's call it `a` and `b`. Then I take one of these arrays and decompose again. I get two arrays with 2 elements, let's call it `c` and `d`. I cannot continue anymore because I have reached 2 elements. Now it is time to reverse it. I take `c` and `d` and inverse transform it, getting an array with 4 elements. How can I inverse transform again now? I only have one array with 4 elements... I need a second array of 4 elements.
Comment: You don't "throw away" the 4 detail coefficients you get from the first level, you keep them in the vector for later, when you get back to inverse transforming at first level. Do you know about block-diagonal matrices?
Comment: @SpaceDog second level will be a matrix with the block matrix structure I describe in edited answer.
Comment: Sorry, my math is rusty. After the first decomposition I have two 4x4 arrays, shown in my question. The first is scaling factor. Should I inject that into the same algorithm and obtain two a 2x2 matrices? and what happens on the way back? Please explain using the numbers I have provided...
Comment: if I am asking too much, no problem. I still appreciate the help.
Comment: Don't turn it into two 4x1 arrays but keep it as one 8x1 vector and then figure out which matrix of the form I showed you the next step will be.
Comment: I was able to restore the original signal by doing this: I did the first decomposition and got `a` and `b`. I did a second decomposition on `a` and got `c` and `d`. For the inverse process I did a reconstruction using `c` and `d` and got `e`. Then a second reconstruction using `e` and `b` and got the original signal. `a` and `c` are the low-pass and `b` and `d` high pass. Is that it?
Comment: @SpaceDog it sounds right, I am more used to expressing it with matrices. I will try to write it out as the second matrix.


Selenium: Dynamic clicking of radio button beside search result

Question: I'm a month-old with Selenium and so far all I use is the IDE. Haven't had the luxury of reading on RC (although I will be after this critical project). Anyway I would like to know how I could click the radio button beside a search result w/c does not always appear on the same position. W/ my limited knowledge in Selenium and programming, best solution I can think of is veryfyTextPresent on the text of the result then click blindly a couple of positions beside the text using xPath (? is this even doable ?). How could I do this in a less primitive manner?
So in this scenario I would verify Bingo! then would like to click on the radio button beside it
O  xxxxxxxx
O  xxxxxxxx
O  xxxxxxxx
O  Bingo!
O  xxxxxxxx
O  xxxxxxxx
However on different searches this could look like this
O  Bingo!
O  xxxxxxxx
O  xxxxxxxx
O  xxxxxxxx
O  xxxxxxxx
O  xxxxxxxx
Anyway I hope I've explained my problem clearly. Thanks in advance for all your comments, suggestions and guides. :)
Answer: Try using firebug to investigate any additional distinguishing properties for the radio button. If they do exist, use them to construct a CSS identifier. If not, (and if possible), ask the developer to add properties.
Alternately, try posting the HTML tags from firebug for the radio button here..
Comment: Hi Rajat. Here's the HTML tag for the radio button. As you can see the ID is incremental depending on the number of records selected. And since records are pretty much random posting I can't quit pinpoint the exact radio button for a specific record that I'm searching for. Thanks for the tip! :)
Comment:
Select


When summarizing data from a lognormal distribution, when does it make sense to report the arithmetic mean vs. geometric mean

Question: When data are sampled from a lognormal distribution with a reasonably large geometric standard deviation, the distribution is asymmetrical and the arithmetic mean will be distinct from (and larger than) the geometric mean.

The arithmetic mean can be thought of as the center of gravity of the
distribution. Parkin and Robinson suggest it makes sense to use the arithmetic mean "for situations where an estimate of the total mass
of a variable (either a chemical constituent or a process) is required" (1).

The geometric mean is equivalent to the median (for the entire distribution; not for any particular sample). It is the center point, in the sense that half the values are higher, and half are lower.

I've always thought that the geometric mean is a more sensible (and standard) way to describe the distribution.
Of course, there is no need to choose, and reporting both means makes sense in some situations. But if you want to report only one mean, what is the best way to choose (and explain your choice)?

Addendum. Here is the key section from page 222 of Parkin and Robinson (using N not for population size, but for the element nitrogen):

<code>1.Parkin, T. B. & Robinson, J. A. Analysis of lognormal data. Adv Soil Sci 20, 193–235 (1992).
</code>
Comment: If you're interested in learning about the population mean of the original variable, it would make sense to report an estimate of that specific quantity (though you won't *necessarily* use the sample mean to estimate it) rather than of the mean of its log. But in any case I don't really understand the common default to only consider a single measure of location (or, rather, *scale* in the case of a lognormal), when two or three measures may be considerably more informative while taking up only a few more characters. That's not intended as criticism of your post; it's the publishing environment
Comment: Working in industry, I generally would just report the median and note something like "the mean is less useful here, because of the lopsided distribution". I don't fancy explaining geometric means or log-normal distributions to stakeholders.
Comment: The answers are interesting, but the question more or less answers itself, if vacuously: it all depends on exactly what you are trying to do. I'd add a trivial but homely example. The distribution of my expenditure is markedly skew with occasional enormous items (house, car, whatever) and numerous minor items (coffee, lunch, whatever). But the total -- as implied by the arithmetic mean -- is undoubtedly the key quantity -- yet it is not contradictory to say that **otherwise** the geometric mean is more interesting to me than the arithmetic mean.
Comment: I agree strongly on the interest and importance of the geometric mean. An intriguing educational question is that the geometric mean seems often to be considered too advanced for introductory texts but perhaps also too elementary or obvious for more advanced texts. The neglect in introductory texts may often arise because, or be encouraged by, reluctance to use logarithms in front of students (or even scientists etc.).
Comment: @NickCox, did anyone take a geometric mean of more than two numbers before 1800? I think no, which suggests that the concept is advanced after all. As benchmarks, logs were common with Napier's book of 1614, and the geometric mean was familiar for Cauchy in 1821, but this paper (cited in Cajori's History of Mathematical Notations as an early example of nth-root notation) suggests that even in 1788 people only thought of the geometric mean as between two quantities: https://babel.hathitrust.org/cgi/pt?id=hvd.hxin1i&seq=403
Comment: Good question. I don't know any examples. But the argument from date of invention is puzzling. Calculus was a joint discovery in the 17th century while scatter plots were not routine until the 19th century. Which is the deeper idea?
Comment: I think the history is a good guide to which ideas are intuitive, and which may go over the heads of an introductory class. (https://en.wikipedia.org/wiki/Genetic_method). At the elementary-school level, I'd rather see proto-calculus (estimate the size of the lake / field / park on the map by drawing trapezoids on the grid) than proto-scatter plots.
Comment: I would like to see both!
Comment: ... arise from ...
Comment: *Update:* The original post asked for a statistic to report as a summary of the distribution. Meanwhile the highlighted sections of the quote are about a statistic for computing a total, which is a different goal.

I might even say that the total is not a statistic of the distribution at all. Eg: when the total nitrogen loss $T$ from $a$ areas is estimated as $a/b$ times the arithmetic average of nitrogen loss from $b$ sample areas, I'd say that the arithmetic and geometric averages are both distributional properties, but the size $a$ and the total $T$ are population properties instead.
Comment: @NickCox If you want to know the total, compute the total. The arithmetic mean is a pretty indirect way to estimate the total. I still don't understand a justification for choosing the arithmetic mean (center of gravity) of data from a lognormal distribution rather than the geometric mean as a way to summarize the data.
Comment: Clearly (or so I hope)  I understand and agree that you can get the total directly. Given your question, one answer is that the arithmetic mean is informative because it implies the total, as you will understand. So, the underlying question seems to be getting more elusive not less. Is it something a little artificial such as _If you were allowed to report for a lognormal distribution only one of arithmetic mean and geometric mean, which would you choose and why?_
Comment: @NickCox. The context is that I am writing a review of lognormal distributons (and geomean...) for nonmathematical scientists. I want to include a paragraph explaining when to focus on GeoMean and when to focus on the arithmetic mean. "arithmetic mean implies the total" is pretty vague to me. I still am unable to write some clear advice about which mean to choose.
Comment: I don't have your _Intuitive_ book to hand but I guess you know of  papers cited in https://stat.ethz.ch/~stahel/lognormal/  If not, those are vital references.
Comment: @NickCox Thanks for that link. I had read most of the papers and pages linked from that page, but not all of them.
Comment: To echo some of the comments:  the objective needs to be considered which may lead to the mean, the median, the 99th percentile or multiple summary statistics.  In this day and age especially when you either don't know what the result will be used for, there's no reason why you can't keep everything:  the data, how it was collected, why it was collected, an assessment of the quality of the data, and the estimated parameters of a distribution (if it is reasonable to assume a particular distribution) as collected data rarely has a single use (and unfortunately multiple mis-uses).
Answer: If data comes from a lognormal distribution, then yes, the geometric mean is the single best summary statistic.
The key is the hypothesis. If the post had asked about choosing between normal and lognormal models, then the arithmetic mean might be more useful. Instead, the post asked about "data sampled from a lognormal distribution" -- i.e. a distribution already assumed or chosen to be lognormal. So whatever reasoning went into that assumption or choice probably would also suggest using the geometric mean.
Here are two examples:

A lognormal distribution might model weather or disasters such as water flows, rainfall, and hurricanes, or earthquakes, fire damages, and insurance claims. Then the sampled events can differ by orders of magnitude. So the arithmetic mean will be roughly $1/n$ times the largest case, which is not an especially useful number. By contrast, the geometric mean will estimate the median of the population, and be a reasonable guide to a common size for the events.

A lognormal distribution might model repeated financial processes, such as changes in stock prices, currency rates, or crypto values. Then the arithmetic mean does not scale nicely, so it is not an especially useful number. By contrast, reporting that the geometric mean is an increase of (e.g.) $1\%$ in a month or year or day is useful, because the powers $1.01^t$ will estimate the geometric means of samples over other time scales.
Comment: What you say makes lots of sense to me, and how I would have answered until reading the paper/review by Parkin doi: 10.1007/978-1-4612-2930-8_4  They prefer to use the arithmetic mean from clear lognormal distributions, when the values are concentrations or masses, saying that the center of gravity is what matters most. I don't really understand that argument, which is why I posted the question here.
Comment: Parkin URL: https://link.springer.com/chapter/10.1007/978-1-4612-2930-8_4.   (paywalled)
Comment: Sorry. That is a long paper. I should have been more specific. I added a screenshot the the relevant page to the original question.
Comment: I responded to the quote from the paper in a comment on the post
Comment: I would argue that for some of the variables that you mention in your first example, that percentiles rather than the mean or median are more likely to be used when the objective is to build something strong enough to withstand more extreme events.  Again, which and how many summary statistics are needed depend on the objective.
Answer: As the definition of the lognormal distribution suggests, if $Z\sim\mathcal{N}(\mu,\sigma^2)$ then $X=\exp(Z)$ follows the $\mathcal{logN}(\mu,\sigma^2)$ distribution. I think that the answer to "which mean to report?" first needs to go through "which part of the data are you interested in?". That is, are you interested in the measurements themselves ($X$) or in the underlying normal variable ($Z$)?
If you have some measurements and you are interested in the underlying variable (for example, your measure some power ratio and would like to learn something regarding this data in dB), then I'd report the geometric mean. Not only you inform the reader about $X$, but it also follows that $\sqrt[n]{\prod_{i=1}^{n}X_i}=\exp(\frac{1}{n}\sum_{i=1}^{n}Z_i)$. That is, one quantity tells two tales.
However, If you are interested in the measurements themselves - that is, you have some size which traditionally follows the lognormal distribution, such as the concentration of elements and their radioactivity in the Earth's crust (example taken from here), then I'd report the arithmetic mean as it is the most common central metric.
PS. As far as I know,  for a unimodal distribution the center of gravity lies in the mode, not the mean. While for $Z\sim\mathcal{N}(\mu,\sigma^2)$ we know that $\mu$ is not only the mean but also the median and the mode, this isn't the case for $X=\exp(Z)$. Its mean is defined as $\exp(\mu+0.5\sigma^2)$, its median is $\exp(\mu)$ and its mode is $\exp(\mu-\sigma^2)$.
Comment: @spatzie thanks. I don't understand the end of the second paragraph. "Two tales"? I also would prefer stronger statements about pros/cons of geo and arithmetic means. "interested in the underlying value" vs "interest in the measurements themselves" isn't very clear to me.
Comment: Two tales: It tells you something about both $X$ and $Z$
Comment: @spatzie. I don't think your equation in paragraph 2 is right. Please check. Beyond that, I don't understand the point. What two concepts does the geometric mean covey/
Comment: The arithmetic/geometric means are different tools, serving different purposes. When we  need to pick which tool do use use, we first need to consider what is the purpose of our investigation. One does not simply take some data and spills all the central/dispersion metric available, right? What are these measurements? What do we want to know about the data collected? If we report some quantities, what does the addressee want to know? These are the questions you should ask yourself before discussing general pros/cons of different tools.
Comment: Thanks for pointing out the mistake in par.2, I've corrected it
Comment: Let me try one more explanation: Imagine we're dealing with a right triangle.  The length  of its hypotenuse is (x+y). The arithmetic mean $\frac{x+y}{2}$ would give use the length of half the hypotenuse (obviously), while the geometric mean $\sqrt{xy}$ would give use the length of the perpendicular to the hypotenuse. Which of them should we report? It depends on what is our subject of investigation.
Comment: @spatzie. Your first equation is wrong. I sort of see what you are getting at, but it really doesn't help in a general case. When should a scientist focus on (report) the arithmetic mean vs. the geomean for lognormal data? I don't think a (corrected) example of triangles will help her decide.
Comment: Once again - the general case of which mean to report when your data is lognormal depends on the scientist's interest of investigation. If what she seeks to know about is the underlying normal distribution (which yielded the data itself), then she should report the geometric mean, as it helps us understand what is the median of the underlying normal. If her interest lies in the data "as is" with no special interest in the underlying normal, then she should report the arithmetic mean.
Comment: The first sentence of the PS is wrong. The center of gravity of a unimodal distribution is its mean, not its mode.
Answer: I think that the standard deviation (or standard error) will help you decide. The variation within a log-normal distribution is asymmetric and so the conventionally calculated standard deviation will overstate the variation on the low end and understate it on the high end. That leads to confidence intervals that do not behave well.
In an example that will be familiar to you the confidence interval for a drug EC50 might go down to near or, sometimes, below zero. As that would imply the statistical possibility of super-duper potency, or more than infinite, that is misleading. (Unless you are a homeopathy practitioner!) The confidence interval for the logEC50 behaves correctly.
Given that, I prefer by far the geometric mean, and would call it the mean log EC50.
Comment: Hi @Michael Lew. I think you miss the point of the question. Yes, lognormal distributions (with a sufficiently high GeoSD) are asymmetrical. But Parker and Robinson prefer using the arithmetic mean when the distribution is of mass or concentration because it is the center-of-gravity of the distribution. BUT.. there is a better way to compute the arithmetic mean than add them up and divide by n. And there are better equations to compute the CI of the arithmetic mean (that are based on sampling from lognormal, not normal).

I agree with you, of course, on reporting log(EC50) not EC50.
Answer: [I'm going to post an answer to my own question, in hopes of getting comments and a better answer. ]
Imagine your goal is to compare a variable like pollutant concentration or rainfall in various locations. At each general location, you collect measurements  and find that over several time intervals. The distribution among those values is lognormal.  You don't care about the typical value (median) in each location. What you really want to compare is the total amount of rain or pollutant in the locations. You can't know that, but the arithmetic mean is proportional to the total. Therefore comparing the arithmetic means is more sensible than comparing the geometric means.
Answer: If you only report one mean, you should choose the one with the most practical relevance. In situations where an estimate of the total mass matters, it is the arithmetic mean.
The mean is dominated by extreme values which is a desirable quality.
Situations where an estimate of the total mass matters (and not most common values) are situations where the total mass has most relevance, e.g. influence on the actions.
You are interested to know how extreme magnitudes of an earthquake or changes in a stock price, or rainfall can be because you have to prepare for that and before you prepare for most common magnitudes.
EDIT:
So this answer can be seen as an extension to Spätzle's answer who says that it depends on the question you are trying to answer.
Matt F. Is right that the geometric mean is a good summary for the lognormal distribution because it fits the multplicative nature of the data generating process.
However practical implications might sometimes be more relevant which is why you want to show the arithmetic mean.
Comment: Will you clarify in which of your examples you want to know the total mass vs the extreme magnitudes vs the most common magnitudes? I think you have different examples in mind for each of those, and that would be helpful, but I can't quite make out which examples you intend for which statistics.
Comment: Examples where the total mass matters are - rainfall, e.g. when you build infrastructure that should last,  changes in stock prices when you are interested to estimate a risk. It really depends on what question you are trying to answer. My answer can be seen as an extension of your answer and Spätzle's answer.


Multiple Morphs on Scroll

Question: Struggling to get multiple SVGs to animate on scroll.  I followed the CodePen and the first animation works fine, but the second doesn't.  I need to be able to run like 4-5 of these on the homepage.
<code>    var scrollMorph1  = new TimelineLite({paused:true})
    .to("#headerBottomMask",1, {morphSVG:"#headerBottomMask2"},0)
    .to("#headerBottom01a",1, {morphSVG:"#headerBottom01b"},0)
    .to("#headerBottom02a",1, {morphSVG:"#headerBottom02b"},0)
    .to("#headerBottom03a",1, {morphSVG:"#headerBottom03b"},0)
    .to("#headerBottom04a",1, {morphSVG:"#headerBottom04b"},0)

    $(window).scroll(function() {
        var scrolled = $(window).scrollTop();
        var diff = 50;

        var object1 = $('#header h1');
        var topOfRange1 = object1.offset().top + diff;

        if (scrolled > topOfRange1 ) {
            scrollMorph1.play().timeScale(1);
            } else {scrollMorph1.reverse().timeScale(1);}
    });

    var scrollMorph2  = new TimelineLite({paused:true})
    .to("#clientsMask",1, {morphSVG:"#clientsMask2"},0)

    $(window).scroll(function() {
        var scrolled = $(window).scrollTop();
        var diff = 50;

        var object2 = $('#weare a');
        var topOfRange2 = object2.offset().top + diff;

        if (scrolled > topOfRange2 ) {
            scrollMorph2.play().timeScale(1);
            } else {scrollMorph2.reverse().timeScale(1);}
    });
</code>
Answer: Code works fine.  Wasn't targeting the Path, but rather the SVG's ID on the second one.  Have to target the path.
Comment: You should delete your question then.

Multiple Morphs on Scroll


How to clear Azure Storage Emulator Data from command line?

Question: My solution is using Azure Emulator. I would like to clear the Azure Storage Emulator Blobs, Queues and Tables without having to perform manual actions. I need to be able to do it from command line, preferably PowerShell.
Server Explorer in Visual Studio 2015, Azure-node:

AzureStorageEmulator.exe help returns the following commands:

AzureStorageEmulator.exe init: Initialize the emulator database and configuration.
AzureStorageEmulator.exe start: Start the emulator.
AzureStorageEmulator.exe stop: Stop the emulator.
AzureStorageEmulator.exe status: Get current emulator status.
AzureStorageEmulator.exe clear: Delete all data in the emulator.
AzureStorageEmulator.exe help [command]: Show general or command-specific help.

However when trying out "clear" the following is returned:

The following services have been succesfully cleared of user data:
  None
Answer: cd C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator
.\AzureStorageEmulator.exe clear all

Comment: this hangs for me! anyone have any ideas how to do this manually?
Comment: The docs for the Storage Emulator command line tool are at: https://learn.microsoft.com/en-us/azure/storage/common/storage-use-emulator#storage-emulator-command-line-tool-reference
Comment: @JohnNicholas - Stop the emulator. Then delete the AzureStorageEmulatorDbXXX.mdf / ldf files in your windows home directory.
Comment: For people suspecting a hang: it took a long time to run for me, several minutes.
Answer: Visual Studio 2022 and Azurite

it will not use SQL Server like Legacy Storage Simulator and all the related data is stored as large JSON files in the following folder.

%userprofile%\AppData\Local\Temp\Azurite
or maybe
%userprofile%\AppData\Local\.vstools\Azurite

you will see  Azurite  services starting up in Visual Studio Service Dependencies Window when you open VS with any project that needs this

Azure Storage Explorer Will automatically connect to this new emulator VIA REST-API and if you using Legacy Emulator and new emulator at the same time you are working with different data sets
it seems that Azurite currently has no explicit stop and clear command (3.14.3) and if you cannot delete these folders, just close both Visual Studio and Storage Explorer and try again.
see also related note on official note in azurite github (link)

Note. Delete above files and folders and restart Azurite to clean up
Azurite. It will remove all data stored in Azurite!!

check always the Output -> Service Dependencies to find the correct location. Recently the location is changed to the following folder
%USERPROFILE%\AppData\Local\.vstools\azurite

Visual Studio 2019 and deprecated Azure Storage Emulator
Running "AzureStorageEmulator.exe clear all" & "init" command usually hangs (or may take too much time)
solution: you can go to user folder (%userprofile%) usually in the following address and delete existing AzureStorageEmulatorDb510.mdf and ldf files.(last suffix 510 stands for version 5.10 of emulator)
C:\Users\[YOUR_USER] or %userprofile%

if you can not delete them you because they are locked, stop Azure Storage Emulator by running AzureStorageEmulator.exe stop and try again or simply by shutting it down from its icon  in system tray
Answer: An alternative approach if you are using Azurite & VS2022+ is to use VSCode Durable Functions Monitor extension to delete the hub in the emulator.
I found Purge and Clean operations (from VSCode ext.) failed against Azurite both when I ran from VS2022 or using docker. They work for me when I am using real Azure storage. This eliminates the annoyance of having to quit VS before you can delete the files.
Deleting the hub in VSCode Durable Functions Monitor is by far the quickest way I have found so far to reset everything before another debug run.
Comment: Those purge methods are useless.


How to enable Google analytics while site is in maintenance mode?

Question: I want to know how many users visit my site that is currently in maintenance mode. I have installed the google analytics module, but it doesn't add google tracking codes to the maintenance page, so google analytics says "Tracking not installed".
How do I enable it while site is in maintenance mode?
Answer: You'll have to do it manually unfortunately, the normal page building handler isn't called for the maintenance page so the analytics module never actually builds up the necessary javascript.
You can follow the instructions here to set up a custom maintenance page template, from there you'll just need to add the tracking code manually to the bottom of the site. It should start working instantly.


Error copying Postgres database in Heroku

Question: I've been using the same command to copy my Heroku Postgres database from my production environment to my development without a hitch, until today:
heroku pg:copy <production-app>::DATABASE DATABASE --app <development-app>
Starting copy of DATABASE to DATABASE... done
Copying... !
 ▸    An error occurred and the backup did not finish.
 ▸
 ▸
 ▸    pg_restore: warning: errors ignored on restore: 36
 ▸    pg_restore finished with errors
 ▸    waiting for pg_dump to complete
 ▸    pg_dump finished successfully
 ▸
 ▸    Run heroku pg:backups:info <redacted> for more details.

Then if I run the command for more details, I get:
▸    Not found.

Comment: which plan you are - free? maybe you can find the problem in documentation - if there are some limitations listed
Comment: If you're using any postgres extensions it's almost certainly related to a change Heroku made to how they handle postgres extensions. There's lots more discussions and possible workarounds in this post: https://stackoverflow.com/questions/73206939/heroku-postgres-postgis-django-releases-fail-with-relation-spatial-ref-sys
Comment: @DougHarris Ah that might be it since I'm using `citext`
Comment: I'm also using `citext` :-(
Answer: Probably not a solution because it didn't fully work for me, but possibly a place to start.
Rather than use pg:copy, I tried to break it into a few steps.
First, I did a dump from the source database:
pg_dump -O -f dumpfile.sql $(heroku config:get DATABASE_URL -a <my-app>
Next, I manually edited the file. I changed:
CREATE EXTENSION IF NOT EXISTS citext WITH SCHEMA public; to
CREATE EXTENSION IF NOT EXISTS citext WITH SCHEMA heroku_ext;
and I replaced any references to public.citext with heroku_ext.citext.
Last, I loaded the edited dump file:
psql $(heroku config:get HEROKU_POSTGRESQL_COLOR_URL -a <my-app>) < dumpfile.sql
It didn't fail in the same way as pg:copy but there were other errors that prevented my app from running properly. I haven't yet had the chance to dig deeper.
Update: Heroku support suggested this workaround to me that is somewhat similar but I've not had a chance to try it yet:

The best path forward is going to be moving those extensions into the heroku_ext schema.
To fix the pg:copy upgrade method, you will need to correct the source system to be in the heroku_ext. To do this you will want to capture a backup, modify the backup file and restore using the modified backup file.
Because of the uniqueness around each customers' database, we are not able to automate these steps behind the scenes.
Steps for doing so

Download Your Backup https://devcenter.heroku.com/articles/heroku-postgres-backups#downloading-your-backups
Convert dump file to .sql file pg_restore -f <output-file-name> <input-file-name>
Modify the CREATE EXTENSION commands to use WITH SCHEMA heroku_ext. You may need to modify the dependencies suggested above.
Restore the backup using pg_restore
Take a new backup pg:backup:capture on the corrected database so the next restore comes from a corrected


Is 'change' event in Backbone.js only "reference based" change instead of "value based" change

Question: I write one piece of test code:
var ModelHasObjectAttribute = Backbone.Model.extend({
    defaults:{
        property_value:99   ,
        object_attr:{"year":"1990"}
    },
    setYear:function(year) {  // function like this cannot trigger change
        var temp_object_attr = jQuery.extend({},  this.get('object_attr')  ); // This shallow copy is to change the reference of object_attr,
        temp_object_attr["year"] = year;            // otherwise I cannot trigger 'change' event, if the value of one attribute changed but reference not changed
        this.set( 'object_attr', temp_object_attr );
    },
    changeYear:function( year ) {
        console.log("before changing, " + this.get('object_attr')['year']);
        this.get('object_attr')["year"] = year;
        console.log( this.get('object_attr'));
    },
    initialize: function () {
        var classRef = this;
        this.on('change:property_value', function() {
            alert("heard property_value changing");
        });
        this.on('change:maxvalue', function() {
            alert("heard maxvalue changing");
        });
        this.on('change:object_attr', function() {
            alert('heard object_attr changing' + classRef.get('object_attr')['year']);
        });
    }
});
var on_instance = new ModelHasObjectAttribute ();
on_instance.set('property_value',10);
on_instance.changeYear(2015); // this line of code does not trigger default 'change' event
on_instance.setYear(2016);    // this one triggered
console.log( on_instance.get('object_attr') );

For example, if I want change to be triggered when object_attr is changed,
I have to change the reference of the object stored under object_attr.
just modify the value of object of object_attr, will not trigger change.
How can I avoid the expensive shallow copy, and also trigger change events?
Answer: That approach doesn't work because Backbone has no way to detect that you have changed the object_attr object. This isn't so much a Backbone issue as a general JavaScript point - you can't observe object property changes (yet).
The best way to set deep attributes with change events is to use a plugin like Backbone.DeepModel, which overrides set to work with nested attributes:
var ModelHasObjectAttribute = Backbone.Model.extend({
  // ...
  setYear:function(year) {
    // triggers 'change' events
    this.set('object_attr.year', year);
  },
  // ...
}

N.B. The link is to a recent fork of DeepModel. Depending on your app setup, you may need to use the (unmaintained) original version.
Comment: Thank you for your answer! I think it is a good one, I also used one workaround, that is  make object_attr one Backbone model


Handling cumulative exposure variables in mixed-effects logistic regression (MELR) models

Question: I am working on analyzing the results of an observational study, a brief description of which is as follows:
X number of diabetic subjects have been recruited to collect naturalistic driving data, and subsequently model their driving behavior as a function of a bunch of predictors such as blood-glucose level, roadway and environmental characteristics, etc.
One aspect of this study that I am currently dealing with involves modeling the driver behavior at stop-controlled intersections using the following response and predictor variables:

Response variable: unsafe behavior (rolling stop or no stop) & safe behavior (full stop; reference level)
Predictor variable: Cumulative exposure to glucose episodes prior to the trip start. An episode is simply an event where the blood-glucose level stays below or above a certain threshold for a certain period of time. A trip is
the movement of a car between two points from engine start to stop.

So, each row in my analysis data has a value of the response (unsafe or safe), and cumulative total duration of exposure to glucose episode at the trip start. During a trip a subject can come across multiple stop intersections, so there will be multiple rows for the response but the cumulative exposure information for those responses will be the same. I am using the lme4 R package and setting up the model formula as follows:
lme4::glmer(
  stop_beh ~ cumexp_episode_totalmins + (1|subj), # by-subj random effects
  data = my_data,
  family = "binomial"
)

I am wondering if this is the correct way to handle cumulative exposure variables in MELR models?
Update
Based on Erik's response, I thought adding how my data is organized will add clarity to my question.
  "subj", "trip_id", "stop_encounter_id", "cumexp_episode_toatlmins",
  # start of the study period;
  # multiple stop sign encounters within a trip
  "A", 1, 1, 0,
  "A", 1, 2, 0,
  "A", 1, 3, 0,
  # driver had 15 minutes of episode before the start of trip 2;
  # notice the episode info is repeated for the trip
  "A", 2, 1, 15,
  "A", 2, 2, 15,
  "A", 2, 3, 15,
  # no additional episode b/w trips 2 & 3
  "A", 3, 1, 15,
  "A", 3, 2, 15,
  # 15 more minutes of episode between trip 3 & 4
  "A", 4, 1, 30,
  "A", 4, 2, 30

Answer: Welcome to the site, Ashirwad. You can code your predictor variables however you want in a MELR. The bigger question is about whether the way you have coded it makes sense given your research question and whether it would be acceptable to substantive researchers well-versed in the topic.
Your current model treats the cumulative exposure as person-level variable having the same repeated value within subj.* This is completely acceptable, and if you keep it this way, assumes that the association is linear. You may want to consider whether there is a non-linear association between this variable and safe stopping behavior by including polynomial terms for cumulative exposure in the model.
One question I have is about whether your data is coded such that you know how much time elapsed between trip start and each instance of behavior at a stop-controlled occasion. If you do, then you could model the process as a time-varying effect. In such a model, each instance of stopping behavior is a function of how much time elapsed since injection and that occasion. The advantage of this formulation is that you can allow the effect of time elapsed to vary across persons, which seems relevant given that the rate at which the drug is metabolized likely varies across persons. This is practically accomplished in the mixed model by specifying the slope of the time elapsed variable as a random effect. This varying slope can also be investigated for non-linearity.
Edit based on updated information about trips
As noted, you have observed subjects for multiple trips. Hence, you can reformulate your current model into a 3-level model with trips nested within subjects. You can estimate this model as follows:
m1 <- glmer(
  stop_beh ~ cumexp_episode_totalmins + (1|subj/trip_id), data = my_data,
  family = "binomial")

You can use a likelihood ratio test to see whether the addition of the third level provides a better fit to the data than your two level model (call it m0) by running anova(m0, m1). A p-value less than .05 is generally taken to mean that the more complicated three-level model provides a better fit to the data.
*Based on your comments, we now know that cumulative exposure is a trip-level variable that is consistent within trips, but different within subjects. That is fine. The model will estimate it's association with the outcome accordingly.
Comment: @Ashirwad, I updated my response.
Comment: Thanks for your response & welcome, Erik! Also, apologies for responding late. I somehow missed the notification.
Comment: Now back to the question, the statement "Your current model treats the cumulative exposure as person-level variable having the same repeated value within subj" is slightly incorrect. The same values are repeated for multiple stop encounters within a trip, but it increases or stays the same with each additional trip depending on whether the person had an episode between those trips or not.
Comment: @Ashirwad: Does this mean that each individual took multiple trips? If so, how many? You may want to consider this as another nested random intercept (trips nested within subject).
Comment: Yes! I don't recall the number, but the number of trips varies by the subject. Yeah, that's a good idea. I will try that.
Comment: Also, I updated the question to add a brief description of how my analysis data is setup. You may want to look at it.
Comment: Thanks, @Erik! I will use your suggestions to improve my models.


Find the minimum of $J = \int_{x_a}^{x_b} [1 + (\frac{dy}{dx})^2]^\frac{1}{2}dx$ with respect to $y(x)$.

Question: Find $y(x)$ such that the Euclidean distance between $(x_a, y(x_a))$ and $(x_b,y(x_b))$ is a minimum, i.e., find the minimum of
$$J = \int_{x_a}^{x_b} \left[1 + \left(\frac{dy}{dx}\right)^2\right]^\frac{1}{2}dx$$
with respect to $y(x)$.
So far I have attempted to integrate this. Is the first integral all I need?
Comment: Are $y(x_a)$ and $y(x_b)$ fixed, or can they be anything?
Answer: Assume wlog that $x_b>x_a$ and let $$d=\sqrt{(y(x_b)-y(x_a))^2+(x_b-x_a)^2}$$
denote the Euclidean distance between the two points $(x_b,y(x_b))$ and $(x_a,y(x_a))$. It is easy to see that
$$d\geq|x_b-x_a|=x_b-x_a=\int^{x_b}_{x_a}dx$$
On the other hand
$$d\leq\int^{x_b}_{x_a}\Big(1+\Big(\frac{dy}{dx}\Big)^2\Big)^{1/2}\,dx$$
The last inequality follows from the fact that the length of the  straight line joining two points in space is no longer than any other curve joining these two points. Therefore from the last two inequlaties we get that the minimum is reached when $y(x)=c$ for some constant $c$.


Toggling fullscreen and removing styles

Question: I am trying to toggle to fullscreen when I press a button. I have created some extra styles when the window pops up but, when I try to exit using the escape key, the styles are still there. If I press the escape key after the fullscreen has exited the styles are removed. Is there a workaround. Here is the code of what I have currently
var mainContainer = document.getElementById("mainContainer");

function toggleFullScreen() {
    if (mainContainer.webkitRequestFullscreen) {
        mainContainer.webkitRequestFullscreen();
        mainContainer.style.backgroundColor = "#3D5A80";
        mainContainer.style.paddingTop = "40px";
    }
    $(document).keydown(function (e) {
        if (e.keyCode == 27) {
            mainContainer.style.backgroundColor = null;
        }
    });
}

Answer: here is js fiddle for toy

var mainContainer = document.getElementById("mainContainer");

function toggleFullScreen() {
    if (mainContainer.webkitRequestFullscreen) {
        mainContainer.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
        mainContainer.style.backgroundColor = "#3D5A80";
        mainContainer.style.paddingTop = "40px";
    }
document.addEventListener('webkitfullscreenchange', exitHandler);
}
    function exitHandler() {
        if (!document.webkitIsFullScreen && !document.mozFullScreen && !document.msFullscreenElement) {
             mainContainer.style.backgroundColor = null;
        }
    }
$(document).keydown(function (e) {
        if (e.keyCode == 27) {
     // this is nessecary so far i dont know how to attach event on esc while fullscreen on

        }
    });
$('.button').click(function(){
 toggleFullScreen();
});
#mainContainer{
  height:50vw;
  width:100%;
  background:green;
}

<button class='button'>
FS
</button>

Oh i guess snipped does not support fullscreen play it on jsfiddle
so far i just attached event when you go off from fullscreen thats all enjoy
Answer:

Toggling fullscreen and removing styles


SQL While and if loop

Question: I'm trying to write a while loop in sql but it couldnt. I'm trying to look all rows and if students final score >60 ı want to update his score as passed.
while(select  Result from Student) IS NOT NULL
  begin
  IF ( select Final_Score from Student )> 60
  begin
  update Student set Result='Passed'
  end
  else
  begin
  update Student set  Result='Failed'
  end
  end

I want to use While loop . How can I do it?
Thank you
Answer: SQL is a query language and does not have any procedural elements (loops, conditionals).
A condition like the one you want is simply expressed with a WHERE clause:
update student
    set result = 'Passed'
where final_score > 60;

update student
    set result = 'Failed'
where final_score <= 60;

Alternatively you can use a CASE expression and run only one UPDATE statement
update student
    set result = case
                   when final_score > 60 then 'Passed'
                   else 'Failed'
                 end;

Answer: You could write it as:
update Student set Result=CASE WHEN Final_Score > 60 THEN 'Passed' ELSE 'Failed' END

Single set-based query will be much more performant than loop.
Comment: @fd2812 There is no suqbquery in my example. This is single statement operation
Comment: I got this error
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

for while clause

SQL While and if loop


What is a closed form of $\int_0^1\ln(-\ln x)\ \text{li}\ x\ dx$

Question: Let $\operatorname{li} x$ denote the logarithmic integral:
$$\operatorname{li} x=\int_0^x\frac{dt}{\ln t}.$$
Is it possible to find a closed form of the following integral?
$$\int_0^1\ln(-\ln x) \operatorname{li} x\ dx$$
I tried integration by parts, but only ended up with more complicated expressions.
Comment: Mathematica is unable to find a closed form.  Plugging the numerical value of the integral into the Inverse Symbolic Calculator turns up nothing.  Do you have a reason to suspect that a closed form exists?
Answer: This integral can be expressed in a closed form:
$$\int_0^1\ln(-\ln x)\operatorname{li}x\ dx=\frac{\pi^2}{12}+\frac{(\ln2)^2}2+\gamma\,\ln2,\tag1$$
where $\gamma$ is the Euler-Mascheroni constant.

Proof:
Let
$$\mathcal{I}(a)=\int_0^1(-\ln x)^a\operatorname{li}x\ dx,\tag2$$
then, taking a derivative with respect to $a$, we get
$$\mathcal{I}'(0)=\int_0^1\ln(-\ln x)\operatorname{li}x\ dx.\tag3$$
Mathematica can express the integral $(2)$ in a closed form for explicitly given non-negative integer values of $a$, but not in a general form with a parameter. We could use those values to get a conjectured general formula, and indeed one could get the result $(1)$ this way. Numerical integration shows that
$$\Bigg|\frac{\pi^2}{12}+\frac{(\ln2)^2}2+\gamma\,\ln2-\int_0^1\ln(-\ln x)\operatorname{li}x\ dx\Bigg|<10^{-1000}\tag4,$$
so the result looks plausible.
But here we will follow a different approach to get a rigorous proof (modulo possible bugs in Mathematica tuned exactly to hide that tiny difference). Take the formula $(12)$ from the MathWorld article:
$$\operatorname{li}x=\operatorname{Ei}(\ln x),\tag5$$
where $\operatorname{Ei}z$ is the exponential integral, and plug it into $(2)$. In this form the integral can be evaluated in Mathematica, that gives us
$$\mathcal{I}(a)=-\frac{_2F_1(a+1,a+1;a+2;-1)\ \Gamma(a+1)}{a+1},\tag6$$
and, taking a derivative with respect to $a$,
$$\mathcal{I}'(0)=(1+\gamma)\ln2-\left[\frac{d}{da}{_2F_1}(a+1,a+1;a+2;-1)\right]_{a=0}.\tag7$$
To find the derivative of the hypergeometric function we need to replace it with its definition (formula $(8)$ in this MathWorld article):
$$_2F_1(a+1,a+1;a+2;-1)=\sum_{n=0}^\infty\frac{(a+1)\ \Gamma(a+n+1)}{(a+n+1)\ \Gamma(a+1)\ n!}(-1)^n.\tag8$$
So,
$$\left[\frac{d}{da}{_2F_1}(a+1,a+1;a+2;-1)\right]_{a=0}=\sum_{n=0}^\infty\frac{(n+1)(\gamma+\psi(n+1))+n}{(n+1)^2}(-1)^n,\tag9$$
where $\psi(n+1)=\frac{\Gamma'(n+1)}{\Gamma(n+1)}=-\gamma+\sum_{m=1}^n\frac1m\,$ is the digamma function. Evaluating this sum with Mathematica we get
$$\left[\frac{d}{da}{_2F_1}(a+1,a+1;a+2;-1)\right]_{a=0}=\ln2-\frac{(\ln2)^2}2-\frac{\pi^2}{12}\tag{10}.$$
Plugging this back in $(7)$ and $(3)$ we get the final result $(1)$.
Comment: I used $\frac{d}{da}z^a=z^a\cdot\ln z$. In this case $z=-\ln x$, and after taking a derivative, I substituted $a=0$.
Comment: Excuse my dumbness, how do you get from (2) to (3)?
Answer: Solution by Khalef Ruhemi
From the definition
$$\operatorname{li}(x)=\int_0^x\frac{\ dt}{\ln t}=-\int_0^x\int_0^\infty t^y\ dt\ dy=-\int_0^\infty\frac{x^{y+1}}{1+y}\ dy=-\int_0^\infty\frac{e^{-(1+y)\ln(1/x)}}{1+y}\ dy$$
where we used $$\frac{1}{\ln t}=-\int_0^\infty t^y\ dy, \quad t\in(0,1)$$
It follows that
\begin{align}
I&=-\int_0^1\left(\ln\left(\ln(1/x)\right)\int_0^\infty\frac{e^{-(1+y)\ln(1/x)}}{1+y}\ dy\right)\ dx,\quad \ln(1/x)=t\\
&=-\int_0^\infty\left(\frac1{1+y}\int_0^\infty e^{-(2+y)t}\ln t \ dt\right)\ dy\\
&=\int_0^\infty\frac1{1+y}\left(\frac{\gamma}{2+y}+\frac{\ln(2+y)}{2+y}\right)\ dy,\quad \frac1{1+y}=x\tag{*}\\
&=\gamma\int_0^1\frac{\ dx}{1+x}+\int_0^1\frac{\ln(1+x)-\ln x}{1+x}\ dx\\
&=\gamma\ln2+\frac12\ln^22+\frac12\zeta(2)
\end{align}

Regarding step $(*)$, we know that $$\int_0^\infty t^p e^{-(y+2)t}\ dt=\Gamma(p+1)(2+y)^{-p-1}$$
Differentiate both sides with respect to $p$ to get
$$\int_0^\infty t^p e^{-(y+2)t}\ln t\ dt=\Gamma'(p+1)(2+y)^{-p-1}-\Gamma(p+1)(2+y)^{-p-1}\ln(2+y)$$
Set $p=0$ we get
$$\int_0^\infty e^{-(2+y)t}\ln t\ dt=-\frac{\gamma}{2+y}-\frac{\ln(2+y)}{2+y}$$


Abrir arquivo em C

Question: Gostaria de saber como eu faço para abrir um arquivo em C (Abrir mesmo, como se tivesse dado duplo-click), pq da forma que eu fiz, o programa diz que o arquivo foi aberto, mas ele não é aberto de fato.
Caso a linguagem C não possa fazer isso, qual linguagem eu posso usar?
Código:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{

  FILE *arquivo = fopen("c:\\eu.txt", "r");// testa se o arquivo foi aberto com sucesso

  if(arquivo != NULL)
    printf("Arquivo foi aberto com sucesso.");
  else
    printf("Nao foi possivel abrir o arquivo.");

  printf("\n\n");
  system("PAUSE");
  return 0;
}

Comment: Como assim duplo-clique? Você quer carregar o conteúdo do arquivo ou você quer exibir o conteúdo do arquivo com o gerenciador daquele determinado tipo de arquivo?
Comment: Se aparecer a mensagem "Arquivo foi aberto com sucesso." então ele está aberto. Se além disso você quiser exibir o conteúdo deste arquivo então terá que incluir em seu programa os comandos adequados para isso e, ao final, não esquecer de fechar o arquivo aberto.
Answer: Na verdade, utilizando o fopen, você terá um ponteiro para o arquivo, então você poderá trabalhar com o conteúdo desse arquivo (ler e escrever no arquivo, por exemplo).
Caso você queira abrir o arquivo com a aplicação padrão, vamos supor um Bloco de Notas, você pode usar as funções execl ou system.
Atualmente eu não consego testá-los no windows, mas creio que deva funcionar também.

Abrir arquivo em C


How to determine which button pressed on android

Question: i need to know, how to recognize, which button is pressed.
Like if i have two buttons ,say button 1 and button2,and both of them performing the same method, say method(),how to determine which button pressed ?
Regards
Answer: Most ellegant pattern to follow:
public void onClick(View v) {
switch(v.getId())
{
case R.id.button_a_id:
// handle button A click;
break;
case R.id.button_b_id:
// handle button B click;
break;
default:
throw new RuntimeException("Unknow button ID");
}

This way it's much simplier to debug it and makes sure you don't miss to handle any click.
Answer: OR... you can just put a android:onClick="foo" in the xml code of the
button, and define a method on java with the signature. Inside the
 method foo, get the id and compare it with the one you need
public void foo(View v){

if (v.getId() == R.id.yourButton){

}

else if (v.getId() == R.id.nextButton){

}

}

Answer: I have 10 buttons performing the same method updateText(), I used this code to get the clicked button's text:
public void updateText(View v){
    Button btn = (Button) findViewById(v.getId());
    String text = btn.getText().toString();
}

Answer: If by "performing the same method" you mean theirs OnClickListener then you have to reference the parameter being passed to it.
public void onClick(View v) {
    if(v==btnA) {
       doA();
    } else if(v==btnB) {
       doB();
    }
}

Answer: Ok got the solution
if (yesButton.getId() == ((Button) v).getId()){

  // remainingNumber
 }

else if (noButton.getId() == ((Button) v).getId())
{
    // it was the second button
}


Transforing improper integral into normal integral

Question: I had some basic integral:
$$
I=\int _0^2 \frac{dx}{\sqrt{2x-x^2}}
$$
I have subsituted $u=\sqrt{\frac{x}{2}}$ and got that
$$
I=2[\arcsin(u)]_0^1=\pi
$$
At the beginning $I$ was improper integral and the function was undefined for both $0$ and $2$, but $\arcsin$ is defined in both $0$ and $1$, so I don't need to calculate any limits? The final value is correct, but I don't know whether I can transform an improper integral into normal integral in such way.
Comment: There's nothing wrong with what you've done.  I'm sure there are examples where you can convert an improper integral into a proper one, but I don't have one in mind.  Someone will probably supply one soon.
Comment: Isn't $\int_0^1\frac{\mathrm{d}x}{\sqrt{1-x^2}}$ improper?  The integrand is unbounded near $x=1$.
Comment: @saulspatz ah yes, I didn't see that. But still, now I need a limit only in $x=1$ and not in $x=0$?
Answer: There always exists a substitution to turn an improper integral into a nonimproper integral for absolutely integrable singularities, which means that they weren't true singularities to begin with.
Take for example
$$\int_0^1 \frac{1}{\sqrt{x}}\:dx$$
and let $x = u^2 \implies dx = 2u du$
$$\int_0^1 \frac{2u}{u}\:du = \int_0^1 2\:du = 2$$
Comment: Is there a proof of the first statement you said Sir ?
Comment: @Orion Pax that is the definition of an absolutely integrable singularity, Optimus Prime


JQuery won't add first row

Question: I'm new in JQuery and I wanted to add row table with JQuery but my code won't add first row when the table has no row (If I already had a row it was work). So, what's wrong with my code?
jQuery(function () {
  var i = -1;
  $('input[name=barcode]').keydown(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if(code==13) {
        var idx = i+1;
        var $this = $(this);
        var kode = $(".barcode").val();
        $.get('engine.php?kode='+kode+'&button=getDataBarang' , function(data) {
            var arrayObj = JSON.parse(data);
            var k=0;
            var arr = [];
            $.each(arrayObj , function(key, value) {
                arr[k] = value;
                k++;
            });
            var newRow = $("
" + $this.val() + "	" +
            " "+arr[0]+" 	  "+arr[1]+" 	 "+
            " <input class='harga' required type='text' name='harga["+(idx)+"]' size='10' maxlength='9' pattern='.{1,9}' value='"+arr[2]+"'> 	  "+arr[3]+" 	"+
            "  <input class='jumlah' required type='text' name='jumlah["+(idx)+"]' size='3' maxlength='4' pattern='.{1,4}' value='1'> 	 "+
            "<input type='text' name='sub["+(idx)+"]' size='10' value='"+arr[2]+"' disabled>	"+
            "Batal	"+
            "<input type='hidden' name='kode[]' value='"+kode+"'>
");
            $('#tab > tbody > tr').eq(idx).after(newRow);
            alert(idx);
            //add total
            var total = 0;
            $('.harga').each(function () {
                var $this = $(this);
                var harga = parseInt($this.val());
                var index = $(this).prop('name').match(/\[(.*?)\]/)[1];
                var jumlah = $('input[name^=jumlah]').eq(index).val();
                $('input[name^=sub]').eq(index).val(jumlah*$(this).val());
                total += jumlah * harga;
            })
            $('.total').text(total);
            $('.barcode').val('');
        });
        return false;
    }
  });
});

Comment: can you create fiddle for this ??
Answer: It isn't clear where exactly you want the new row added, but if all you're trying to do is solve the problem of adding the new row when there are not yet any rows, you can change this:
$('#tab > tbody > tr').eq(idx).after(newRow);

to this:
var row = $('#tab > tbody > tr').eq(idx);
if (row.length) {
    row.after(newRow);
} else {
    $('#tab > tbody').append(newRow);
}

If you always want to just add a row to the end of the table, then you can just always use:
$('#tab > tbody').append(newRow);

JQuery won't add first row


Pushforward under map of curves

Question: If $C$ and $D$ are smooth projective curves and $f:C\to D$ is a map, how do we compute $c_1(f_{*}\mathscr{O}_C)$?
I think applying Grothendieck Riemann-Roch from wikipedia yields the answer, but I'm hoping that is overkill, since I don't really understand GRR.
Comment: I am assuming that the map is non-constant (so that it is finite). Do you know the genus of $C,D$? If yes, then $c_1$ can be computed by if you know $\deg f$ and RR for vector bundles on a curve.
Comment: That sounds like exactly what I want, how does that work?
Answer: If $f$ is non-constant, it is finite and let $d=\deg f$. Then, $f_*\mathcal{O}_C=V$ is a rank $d$ vector bundle on $D$ and thus $\chi(V)=c_1(V)+d(1-g(D))$ by RR. On the other hand, $\chi(V)=\chi(\mathcal{O}_C)=1-g(C)$. So, $c_1(V)=(1-g(C))-d(1-g(D))$.
Comment: Note that the equality $\chi(V)=\chi(\mathcal{O}_C)$ in this very nice answer  results from the equality of the individual summands $H^i(D,V)=H^i(D,f_*\mathcal O_C)\cong H^i(C,O_C)$, which in turn results from $f$ being an affine morphism. See Hartshorne Exercise III,8.2, page 252.
Comment: Dear Mohan, I have taken the liberty to correct a typo in the  equation of the second line: I have replaced the incorrect $g(C)$ by the term $g(D)$, which you obviously meant.
Comment: @GeorgesElencwajg Thank you for the kind correction.

Pushforward under map of curves


Qemu cannot run Windows 11

Question: When trying to execute the setup the setup stops after selecting the os type with the following result:
"this PC doesn't meet the minimum system requirements to install this version of windows. For more information visit ..."
What is wrong, My pc is up to date and Windows has enough memory?
Answer: So first of all win11 has 3 major system requirements

4GB RAM
Secure boot
TPM-device

The requirement of your hypersisor is qemu version 4. It is installed with Ubuntu 20.04.
Secure Boot
We do need a secure "bios", which is an UEFI system. Using Virtual machine Manager you do only have one chance to set this setting up. In the last step 5 you are asked, if you want to do some additional modifications to your machine. Set that hook. Once the machine is created, you won't have an easy chance to change that!

got to the tab Overview
Firmware change the default bios to : UEFI ... .secboot.fd

TPM device
The tpm thingy is a key management unit required by windows for security stuff.
skip the ppa for >=22.04, just run install -> thx@Olaf
If you not have installed swtpm yet, you have to install that on your machine.
https://launchpad.net/~smoser/+archive/ubuntu/swtpm
sudo add-apt-repository ppa:smoser/swtpm
sudo apt-get update
sudo apt-get install swtpm-tools swtpm

Change the permission of that folder if necessary
sudo chown -R tss:root /var/lib/swtpm-localca

The tss user is used by qemu. In this folder will be the certificates.
Once installed, add the TPM-device to your machine. In the configuration window of the machine choose:
- [Add Hardware]
- TPM
  - `Model`:`CRB`
  - `Backend`:`Emulated device`
  - `Version`:`2.0`

With a bit of luck, you should now be able to pass the magical win11 install barrier.
Comment: Current Ubuntu (jammy, 22.04) already has swtpm (https://packages.ubuntu.com/jammy/swtpm), so ppa isn't required anymore.
Answer: Just disable the Windows 11 requirements with regedit;
https://blogs.oracle.com/virtualization/post/install-microsoft-windows-11-on-virtualbox

Shift+F10 (run cmd)
run regedit
in HKEY_LOCAL_MACHINE\SYSTEM\Setup
right-click New, Key, LabConfig
New, DWORD (32-bit), BypassTPMCheck, 1
same for BypassRAMCheck and BypassSecureBootCheck
Comment: This particular windows was used precisely for testing that feature.^^
Hacking was no option.
Does this also concern the bios check for secure boot?
Comment: @CuttonEye What are you asking about the "Bypass Secure Boot Check" option?

Qemu cannot run Windows 11


XPath expression to locate web element which is a dropdown

Question: I am a little bit frustrated, because I searched for a web element in a
 HTML, by.XPATH with following-sibling. But the system is unable to locate my element.
I want to change the dropdown value for email address labelled "firstname.lastname@example.com" from "Standard" to "Admin".
But the attribute ID's value "role" is not unique. There are no unique attributes to locate the element.
The Table looks like this (there is no unique id or name I can search for:

                    firstname.lastname@example.com

                    <form action="/echo/UserManagement/UpdateRole?userId=0dca86a5-13d3-4ab5-a2e6-e75ab381dca9&accountReference=4711&username=max%40max.com" method="post" novalidate="novalidate">

                        <select class="roles medium" id="role" name="role"><option value="Admin">Admin</option>
                            <option value="Standard">Standard</option>
                            <option selected="selected" value="Basic">Basic</option>
                            <option value="Template">Template</option>
                        </select>

                            <button class="button button-primary save" type="submit">Save</button>

                                <button class="button button-primary" type="submit">Save</button>

                    </form>

                        <form action="/echo/UserManagement/RemoveUserFromAccount" method="post" novalidate="novalidate"><input id="userId" name="userId" type="hidden" value="0a23788b-0ed6-401b-a11e-8004d34acf1a"><input id="usernameToRemove" name="usernameToRemove" type="hidden" value="email@example.com">
                            <input id="accountReference" name="accountReference" type="hidden" value="4711">
                            <button type="submit" class="button button-danger remove_user" data-confirm="true">Remove</button>
                        </form>

                    email@example.com

                    <form action="/echo/UserManagement/UpdateRole?userId=e5b128b5-75f9-4002-bcd9-11c8bc891d49&accountReference=4711&username=john%40john.com" method="post" novalidate="novalidate">

                        <select class="roles medium" id="role" name="role"><option selected="selected" value="Admin">Admin</option>
                            <option value="Standard">Standard</option>
                            <option value="Basic">Basic</option>
                            <option value="Template">Template</option>
                        </select>

                            <button class="button button-primary save" type="submit">Save</button>

                                <button class="button button-primary" type="submit">Save</button>

                    </form>

                    <form action="/echo/UserManagement/RemoveUserFromAccount" method="post" novalidate="novalidate"><input id="userId" name="userId" type="hidden" value="f45a18fc-4903-4189-8cab-c158630373a3"><input id="usernameToRemove" name="usernameToRemove" type="hidden" value="email@example.com">
                        <input id="accountReference" name="accountReference" type="hidden" value="4711">
                        <button type="submit" class="button button-danger remove_user" data-confirm="true">Remove</button>
                    </form>

                    email@example.com

                    <form action="/echo/UserManagement/UpdateRole?userId=5e356ca7-fa23-45a9-b7f3-c9e71ce5cb5f&accountReference=4711&username=katja%40katja.com" method="post" novalidate="novalidate">

                        <select class="roles medium" id="role" name="role"><option value="Admin">Admin</option>
                            <option selected="selected" value="Standard">Standard</option>
                            <option value="Basic">Basic</option>
                            <option value="Template">Template</option>
                        </select>

                            <button class="button button-primary save" type="submit">Save</button>

                                <button class="button button-primary" type="submit">Save</button>

                    </form>

                        <form action="/echo/UserManagement/RemoveUserFromAccount" method="post" novalidate="novalidate"><input id="userId" name="userId" type="hidden" value="1c094ceb-13a7-41cf-b754-921ac15dd9dc"><input id="usernameToRemove" name="usernameToRemove" type="hidden" value="email@example.com">
                            <input id="accountReference" name="accountReference" type="hidden" value="4711">
                            <button type="submit" class="button button-danger remove_user" data-confirm="true">Remove</button>
                        </form>

My code trials:
driver.find_element(By.XPATH, "//td[text()='email@example.com']/following-sibling::/form/select")

and
driver.find_element(By.XPATH, "//td[text()='email@example.com']/following-sibling::*[1]/form/select")

Answer: Try the below XPath expression:
(//form[contains(@action,'katja.com')]//following::select)[1]

Explanation: The XPath expression selects the first <select> element that follows any <form> element with an action attribute containing the string "katja.com".
Code should look like:
driver.find_element(By.XPATH, "(//form[contains(@action,'katja.com')]//following::select)[1]"))

UPDATE: If you are getting No Such Element Exception, that could be due to more than one reason. Follow the trouble shooting steps in the below answer

https://stackoverflow.com/a/75865161/7598774
Comment: When I try with this I get:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:
Comment: If you manually inspect the page and try to locate the element using the XPath in my answer, will it locate the element successfully?
Comment: Thank you very much for your Comment, I do not knowed that it is possible to search in the Developer Tools. Now I know. I found the Solution for me, it is:
find_element(By.XPATH, "//td[text()='@katja.com']//following::select")


RHCS 5 NFS cluster node not releasing TCP 2049 on relocate

Question: Imagine if you will you have a 2 node Red Hat NFS Cluster; each node is RHEL5.4 64bit and they share a SAN LUN for the data. The primary interface on each server is HA failover bonded (bond0, eth0+eth1) and there is a standard floating cluster resource IP for NFS. The cluster configuration is set up with standard Red Hat tools and NFS has static ports defined in /etc/sysconfig/nfs in order to work through a firewall. So far so good, right? Very by the book, best practices – nothing funky or strange used in the server or cluster setup.
The core of the problem is when the clients are using TCP to mount the exported NFSv4 share; on a cluster service relocate to the other node the newly-passive node retains a 2049/tcp (nfs daemon) ESTABLISHED connection using the now-missing cluster IP to the clients even though that's technically impossible (as far as I'm aware). The "solution" was to move to using UDP when mounting from the clients as we were unable to figure out what was happening (and more importantly how to fix it). Any clues as to why are welcome, details below.
Cluster IP: 22.214.171.124
Client IP: 184.108.40.206

Starting out, NFS service is running on node-A, node-A has the cluster IP aliased as bond0:0 and the SAN mounted. The NFS client is connected via NFSv4 TCP to the cluster IP and things are working just fine. In our netstat on node-A we see:
184.108.40.206:2049 126.96.36.199.100:915 ESTABLISHED

Everything is as it should be. On node-A run a standard 'clusvcadm -r nfs-svc -m node-B' command to move NFS over to node-B; in both syslogs of node-A and node-B you see the proper messages – NFS being stopped, IP being released/moved, SAN unmounted/mounted and so forth. On the NFS client you see a few syslog messages about the NFS server not responding, then it comes back OK and everything is fine. Basically, NFS relocate to node-B works fine.
However, back on node-A which no longer owns the cluster IP 18.104.22.168 you still see in the netstat a connection on 2049! A quick 'rcpinfo -p' confirms it's still nfsd on that port.
184.108.40.206:2049 18.104.22.168.100:915 ESTABLISHED

Of course on node-B you see the same thing as that's correct. The 10 million dollar question is why is it still showing up on node-A? As soon as the IP went away that should have gotten flushed… if you simply restart nfsd the connection state on node-A turns to FIN_WAIT1 and it eventually times out. The cluster IP does not show up as an interface on node-A any longer to be clear, just in netstat.
And here is where it becomes important – if this TCP phantom 2049 connection is still on node-A and you now relocate the NFS service back to node-A (so it gets that cluster IP again), all clients stall and die with the NFS mount whether or not that phantom connection is in ESTABLISHED or FIN_WAIT1 state. Only when that phantom connection finally disappears from node-A can the NFS clients regain their NFS mount – this is on the order of 5 to 15 minutes.
We tested this back and forth a number of times, ensuring it wasn't firewall related and it was repeatable as a problem and not just some fluke. At the end of many hours the only workable solution was to move the clients to UDP and avoid the problem completely. I really want to know what's broken and how to fix it.
Comment: Also posted here: http://tacticalvim.wordpress.com/2010/08/28/rhcs-5-nfs-cluster-node-not-releasing-tcp/
Comment: You have such cool problems.. ;-)
Answer: Use netstat -p to figure out the PID of the process that's listening (or, well, you said it was nfsd, so find it's PID out of ps) and then do an strace on it and you can maybe figure out what's going on with it.  Or maybe you can do the strace on it before you do the clusvcadm command and see if it gets any signals or something (it could maybe be hanging in a signal handler or waiting for some system call to return...).
If worst comes to worst you could build a debug version of nfsd and run it under gdb and do the clusvcadm and see exactly what it's doing...
Answer: I was under the impression that with NFS over TCP you cannot go from A->B->A in a short amount of time. See, e.g., http://www.spinics.net/lists/cluster/msg08758.html
Comment: Great article, thanks - that last comment from Wendy speaks volumes about this problem. (edit) it eventually refers back to this bug report in the system from a few years back: https://bugzilla.redhat.com/show_bug.cgi?id=132823


Calculating the coordinates of a vertex within a triangle so that the triangle becomes a right-angle

Question: I have three points defining the vertices of a triangle
A(1,4)
B(6,7)
C(5,1)
I have found that vector AC has a slope(m) of 0.6 and vector BC has a slope of 6. From these slopes have the angles of ≈34.39° and ≈73.94° respectively. Based on this, I know that these vectors intersect to form angle B at ≈39.55°. I would like to relocate vertex B so that angle B becomes 90° and therefore, ∠ABC becomes a right-angle.
The solution is constrained by the fact that:

I don't wish to relocate vertex A or C.
I would like to adjust the
location of B while attempting to keep the degree of adjustment
relative to vertex A and C proportionate.

Being a geographer, I attempting to implement this solution using Geographic Information Systems (GIS) so I am not extremely proficient with math. Below is my logic for solving this problem but I haven't had any success so far, so please post your proposed solution. Thanks!
Essentially, I am attempting to adjust the slopes of vector AC and BC so that angle B is affected and becomes 90°.
-At first I attempted to sum the component angles and find the difference from 90° and identify those points that do not intersect at a right-angle.
I then tried to find what the new angles of the vectors should be by dividing each angle by the sum and multiplying by 90. I thought that by doing this I could find a 'proposed' new angle of the subject line.
Ex. (angleAC/(angleAC+angleBC))*90 = angleACnew
Using the new 'proposed' angle I would convert this back to a slope value and apply this to each of the vector equations and setting the equations equal to each other and algebraically solve for x.
I then planned on subbing back into one of the equations and solving for y. Thereby, giving be the new x,y coordinate for point B where B was a 90° angle.
However, I realized that this methodology does not work since the sum of angleAC and angleBC do not accurately reflect the internal angles of the triangle and therefore do not yield a logical "adjustment value".
Does anyone have some suggestions and/or guidance?
Comment: what is the degree of adjustment?
Answer: take your triangle and look at the side. then the points where the angle at point B' is the circle with side AC as diameter. As to the degree of adjustment I dont know what that is, I suggest you take the point where the angle bisector at B intersects with the circumference, but I will need a better definition of angle of adjustment to give you a better answer.
Hope this helps :)
Comment: Hi, thanks for replying. I attempted to define what I perceived as the "degree of adjustment". It was simply a term that I dreamt up to define the change in slope that I wanted to apply to the vectors based on my initial logic which proved to be flawed (see above comment). Thanks.
Answer: If vertices $A$ and $C$ are fixed, then the possible candidates for the new $B$ lie on the circle with diameter $AC$ (see Thales' Theorem). I'm not sure what the "degree of adjustment" in #2 is, but hopefully this helps.
Comment: Hi, the "degree of adjustment" was my term for the proposed change I was attempting to calculate for both vector A and vector C. I was attempting to increase or decrease the slopes of the incoming vectors (to B) in order to correct for angle B being either too obtuse or too acute (respectively). In terms of keeping this "adjustment proportional, I simply meant that I did not want to for instance, **only** adjust vector A to create a right angle at B.
Comment: @WD_geo I understand your statement a little better now: you want to adjust both vectors $AB$ and $CB$, rather than just adjust one of them. But this is still rather qualitative. How are you measuring adjustment (angle of rotation, or difference in slope)? How are you quantifying proportionality (minimize the difference in the angles of rotation, etc.)? Regardless, note that your goal is to move your old vertex $B$ to a[ny] point on the boundary of the circle with diameter $AC$.
Comment: yes I would like to be able to adjust both AB and AC. I realize it's rather qualitative, my best attempt to minimize the changes to the slope was the process I described in the very first italicized paragraph from my initial question. Although, the angles used were not appropriate, my attempt was to allocate the change of slope proportionately to both vectors (I hope this makes sense). Again as you mention, it doesn't really matter since your suggestion of Thales' theorem accomplishes what I need. Incorporating the angle bisector at B (from the other response) would also be useful.