Compute $\lim\limits_{n \to \infty} n\sum\limits_{k=1}^n(f(k/n) - f((k-1)/n))\int_{(k-1)/n}^{k/n}f(t)dt$

Question:
Let $f : [0,1] \to \mathbb{R}$ be a continuous function and let $(a_n)_{n>0}$ and $(b_n)_{n>0}$ be two sequences such that $$\displaystyle{ a_n = \sum_{k=1}^n{f \left(\frac{k-1}{n}\right) \cdot \int_\frac{k-1}{n}^\frac{k}{n}}{f(t)dt}},$$
$$\displaystyle  b_n = \sum_{k=1}^n{f \left(\frac{k}{n}\right) \cdot \int_\frac{k-1}{n}^\frac{k}{n}}{f(t)dt}, $$ $\forall n \in \mathbb{N}^*$.
a) Prove that $\displaystyle{\lim_{n \to \infty}{(b_n - a_n)} = 0}$.
b) Compute $\displaystyle{\lim_{n \to \infty}{n(b_n - a_n)}}$.

I have managed to solve a).
Proof for a) :
From the mean value theorem, we know that $\displaystyle{\exists c_k \in \left(\frac{k-1}{n}, \frac{k}{n}\right)}$ such that $\displaystyle{\int_{\frac{k-1}{n}}^{\frac{k}{n}}{f(t)dt} = \frac{1}{n}f(c_k)}$
So, $b_n = \displaystyle{\frac{1}{n}\sum_{k=1}^n {f(c_k) \cdot f\left(\frac{k}{n}\right)} = \frac{1}{2} \cdot \frac{1}{n}\sum_{k=1}^n{\left(\frac{f(c_k) + f\left(\frac{k}{n}\right)}{2}\right)^2 \cdot 4 - (f(c_k))^2 - \left(f\left(\frac{k}{n}\right)\right)^2}}$.
Since $f$ has the intermediate value property, then $\exists x_k \in \displaystyle{\left(c_k, \frac{k}{n}\right) \subset \left(\frac{k-1}{n}, \frac{k}{n} \right)}$ such that $\displaystyle{\frac{f(c_k) + f\left(\frac{k}{n}\right)}{2} = f(x_k)}$.
Therefore, $\displaystyle{\lim_{n \to \infty}b_n = \int_0^1{(f(t))^2dt}}$.
Using the same method, $\displaystyle{\lim_{n \to \infty}a_n = \int_0^1{(f(t))^2dt}}$, so $\displaystyle{\lim_{n \to \infty}{(b_n - a_n)} = 0}$.
I have trouble solving b). I tried using the same method but it doesn't work, not unless $f$ is differentiable (so I can use Lagrange's theorem).
$\displaystyle{n(b_n - a_n) = \sum_{k=1}^n{f(c_k) \left( f\left(\frac{k}{n}\right) - f\left(\frac{k-1}{n} \right) \right)}}$ and if $f$ is differentiable, then $\displaystyle{f\left(\frac{k}{n}\right) - f\left(\frac{k-1}{n} \right) = \frac{1}{n}f'(c_k)}$.
Comment: Riemann sum plus mean value theorem do the job here
Comment: If you can solve this for differentiable functions, you can do it for every continuous function, by density. Thus... please explain what you do to solve this for differentiable functions.
Comment: Try setting $g(x)=f(x)^2/2$ and compare the terms to changes in the value of $g$.
Comment: Sorry..... my bad!
Comment: This seems to be harder than one might think. Can you tell where the problem comes from?
Comment: @MartinR It's from a Romanian mathematics magazine called "Gazeta Matematica". Every month there are 13 new problems for each grade of eduation (I'm in the 12th and last grade), some of them are easy, but others may be difficult. This very problem is from the December/2017 number.
Answer: Here we construct a continuous function $f : [0, 1] \to [0, 1]$ such that the associated sequences $(a_n)$ and $(b_n)$ satisfy
$$ \lim_{n\to\infty} 3^n(b_{3^n} - a_{3^n}) = \infty \tag{*}$$
1. Construction
Pick $0 < y_2 < y_1 < 1$ and define $\psi : \mathbb{R} \to [0, 1]$ by
$$ \forall x \in [0, 3) \ : \quad  \psi(x) = \begin{cases}
3y_1, & x \in [0, 1) \\
3(y_2 - y_1), & x \in [1, 2) \\
3(1 - y_2), & x \in [2, 3)
\end{cases} $$
and extend by $3$-periodicity, i.e. $\psi(x) = \psi(x \text{ mod } 3)$. Then define $f_n : [0, 1] \to \mathbb{R}$ by
$$ f_n(x) = \int_{0}^{x} \prod_{i=1}^{n} \psi(3^i t) \, dt. $$
We will prove the following claim.

Theorem. $f_n$ converges uniformly to a continuous function $f : [0, 1] \to \mathbb{R}$. Moreover, for all $n \geq 1$ and $k \in \{1,\cdots,3^n\}$, we have $f(\frac{k}{3^n}) = f_n(\frac{k}{3^n})$ and
$$ \int_{\frac{k-1}{3^n}}^{\frac{k}{3^n}} f(x) \, dx
= \frac{1}{2\cdot 3^n}\left( f_n(\tfrac{k}{3^n}) + f_n(\tfrac{k-1}{3^n}) \right) + \frac{\alpha}{3^n}\left( f_n(\tfrac{k}{3^n}) - f_n(\tfrac{k-1}{3^n}) \right) $$
where $\alpha = 2\int_{0}^{1} (\psi(3t) - t) \, dt$.

Remark. $f$ is a variant of the Cantor-Lebesgue function, with the construction step modified so that the variation diverges fast.
Assuming this theorem, we find that
\begin{align*}
3^n(b_{3^n} - a_{3^n})
&= 3^n \sum_{k=1}^{3^n} \left( f(\tfrac{k}{3^n}) - f(\tfrac{k-1}{3^n}) \right) \int_{\frac{k-1}{3^n}}^{\frac{k}{3^n}} f(x) \, dx \\
&= \frac{1}{2} \sum_{k=1}^{3^n} \left( f_n(\tfrac{k}{3^n})^2 - f_n(\tfrac{k-1}{3^n})^2 \right) + \alpha \sum_{k=1}^{3^n} \left( f_n(\tfrac{k}{3^n}) - f_n(\tfrac{k-1}{3^n}) \right)^2 \\
&= \frac{1}{2} + \frac{\alpha}{9^n} \sum_{k=1}^{3^n} \prod_{i=1}^{n} \psi(3^i \cdot \tfrac{k-1}{3^n} )^2.
\end{align*}
But it is not hard to check that
$$ \sum_{k=1}^{3^n} \prod_{i=1}^{n} \psi(3^i \cdot \tfrac{k-1}{3^n} )^2
= \left( \psi(0)^2 + \psi(1)^2 + \psi(2)^2 \right)^n. $$
So we have
$$ 3^n(b_{3^n} - a_{3^n})
= \frac{1}{2} + \alpha \left( \frac{\psi(0)^2 + \psi(1)^2 + \psi(2)^2}{9} \right)^n. $$
Finally, we can choose $y_1$ and $y_2$ so that $\frac{\psi(0)^2 + \psi(1)^2 + \psi(2)^2}{9} > 1$ and $\alpha > 0$. Therefore the desired claim $\text{(*)}$ follows. ////
2. Proof of Theorem
The following lemma will be useful throughout our proof.

Lemma. For each $m \in \{1, \cdots, 3^n\}$ and $x \in [\frac{m-1}{3^n}, \frac{m}{3^n}]$ we have
\begin{align*}
f_{n+1}(x)
&= f_n(\tfrac{m-1}{3^n})
+ \left( f_{n}(\tfrac{m}{3^n}) - f_{n}(\tfrac{m-1}{3^n}) \right) \cdot f_1(3^n x - (m-1)) \\
&= f_n(x)
+ \left( f_{n}(\tfrac{m}{3^n}) - f_{n}(\tfrac{m-1}{3^n}) \right) \cdot \left( f_1(3^n x - (m-1)) - (3^n x - (m-1)) \right)
\end{align*}

Indeed, we have
\begin{align*}
f_{n+1}(x) - f_{n+1}(\tfrac{m-1}{3^n})
&= \int_{\frac{m-1}{3^n}}^{x} \prod_{i=1}^{n+1} \psi(3^i t) \, dt \\
&= \left( \prod_{i=1}^{n} \psi \left( 3^i \cdot \tfrac{m-1}{3^n} \right) \right) \cdot \left( \int_{\frac{m-1}{3^n}}^{x} \psi(3^{n+1} t) \, dt \right) \\
&= \left( 3^n \left( f_{n}(\tfrac{m}{3^n}) - f_{n}(\tfrac{m-1}{3^n}) \right) \right) \cdot \left( \frac{f_1(3^n x - (m-1))}{3^n} \right) \\
&= \left( f_{n}(\tfrac{m}{3^n}) - f_{n}(\tfrac{m-1}{3^n}) \right) \cdot f_1(3^n x - (m-1)).
\end{align*}
Plugging $x = \frac{m}{3^n}$ and $f_1(1) = 1$ shows that $f_{n+1}(\tfrac{m}{3^n}) - f_{n+1}(\tfrac{m-1}{3^n}) = f_{n}(\tfrac{m}{3^n}) - f_{n}(\tfrac{m-1}{3^n}) $. From this we easily deduce that $f_{n+1}(\tfrac{m}{3^n}) = f_{n}(\tfrac{m}{3^n})$ and the first half of Lemma follows. Now by using the fact that the graph of $f_n$ is linear on the interval $[\frac{m}{3^n}, \frac{m+1}{3^n}]$, we have
\begin{align*}
f_{n}(x) - f_{n}(\tfrac{m-1}{3^n})
&= \left( f_{n}(\tfrac{m}{3^n}) - f_{n}(\tfrac{m-1}{3^n}) \right) \cdot (3^n x - (m-1))
\end{align*}
and hence the second half of Lemma follows. ////
Proof of Theorem. We fist establish the uniform convergence. Let $r = \frac{1}{3}\sup |\psi|$. By our choice of $y_1$ and $y_2$ we know that $r \in [0, 1)$. Also,
$$ \forall m \in \{1,\cdots,3^n\} \ : \quad
\left| f_n(\tfrac{m}{3^n}) - f_n(\tfrac{m-1}{3^n}) \right|
= \frac{1}{3^n} \prod_{i=1}^{n} \left| \psi(3^i \cdot \tfrac{m}{3^n}) \right|
\leq r^n. $$
Now let $C = \sup_{x \in [0, 1]} |f_1(x) - x|$. Then by Lemma, uniformly in $x \in [0, 1]$ we have
$$ \left| f_{n+1}(x) - f_{n}(x) \right| \leq C r^n. $$
So $(f_n)$ converges uniformly over $[0, 1]$. Let $f : [0, 1] \to \mathbb{R}$ denote the limiting function. Then $f$ is continuous. Also, by the intermediate step of the proof of Lemma, we know that
\begin{align*}
f_n(\tfrac{k}{3^n})
&= f_{n+1}(\tfrac{k}{3^n})
 = f_{n+1}(\tfrac{3k}{3^{n+1}})
 = f_{n+2}(\tfrac{3k}{3^{n+1}}) \\
&= f_{n+2}(\tfrac{k}{3^n})
 = f_{n+2}(\tfrac{3^2 k}{3^{n+2}})
 = f_{n+3}(\tfrac{3^2 k}{3^{n+2}}) \\
&= f_{n+3}(\tfrac{k}{3^n})
 = \cdots \\
&\quad \vdots
\end{align*}
and hence $f(\tfrac{k}{3^n}) = f_{n}(\tfrac{k}{3^n})$. Now by Lemma again, for $n \geq N$ and $k \in \{1,\cdots,3^N\}$ we have
\begin{align*}
\int_{\frac{k-1}{3^N}}^{\frac{k}{3^N}} f_{n+1}(x) \, dx
&= \int_{\frac{k-1}{3^N}}^{\frac{k}{3^N}} f_{n}(x) \, dx \\
&\hspace{2em} + \sum_{j=3^{n-N}(k-1)}^{3^{n-N}k - 1}
\left( f(\tfrac{j+1}{3^n}) - f(\tfrac{j}{3^n}) \right) \\
&\hspace{8em}\times \int_{\frac{j}{3^n}}^{\frac{j+1}{3^n}} \left( f_1(3^n x - j) - (3^n x - j) \right) dx.
\end{align*}
Using the fact that $\int_{\frac{j}{3^n}}^{\frac{j+1}{3^n}} \left( f_1(3^n x - j) - (3^n x - j) \right) dx = \frac{\alpha}{2 \cdot 3^n}$ and that  we have
\begin{align*}
\int_{\frac{k-1}{3^N}}^{\frac{k}{3^N}} f_{n+1}(x) \, dx
&= \int_{\frac{k-1}{3^N}}^{\frac{k}{3^N}} f_{n}(x) \, dx
 + \sum_{j=3^{n-N}(k-1)}^{3^{n-N}k - 1}
\left( f(\tfrac{j+1}{3^n}) - f(\tfrac{j}{3^n}) \right) \cdot \frac{\alpha}{2\cdot 3^n} \\
&= \int_{\frac{k-1}{3^N}}^{\frac{k}{3^N}} f_{n}(x) \, dx
+ \frac{\alpha}{2\cdot 3^n} \left( f(\tfrac{k}{3^N}) - f(\tfrac{k-1}{3^N}) \right).
\end{align*}
Iterating this relation for $n \geq N$ and using that $f_n \to f$ uniformly and utilizing the equality $f(\tfrac{k}{3^N}) = f_N(\tfrac{k}{3^N})$,
\begin{align*}
\int_{\frac{k-1}{3^N}}^{\frac{k}{3^N}} f(x) \, dx
&= \int_{\frac{k-1}{3^N}}^{\frac{k}{3^N}} f_{N}(x) \, dx
+ \sum_{n\geq N} \frac{\alpha}{2\cdot 3^n} \left( f_N(\tfrac{k}{3^N}) - f_N(\tfrac{k-1}{3^N}) \right) \\
&= \int_{\frac{k-1}{3^N}}^{\frac{k}{3^N}} f_{N}(x) \, dx
+ \frac{\alpha}{3^N} \left( f_N(\tfrac{k}{3^N}) - f_N(\tfrac{k-1}{3^N}) \right).
\end{align*}
Finally, notice that $f_N$ is linear on the interval $[\frac{k-1}{3^N}, \frac{k}{3^N}]$. So the integral is computed as
$$ \int_{\frac{k-1}{3^N}}^{\frac{k}{3^N}} f_{N}(x) \, dx
= \frac{1}{2\cdot 3^N} \left( f_N(\tfrac{k}{3^N}) + f_N(\tfrac{k-1}{3^N}) \right) $$
which proves the desired identity in the theorem. ////
Answer: I think this is less easy than it sounds. So far, I only have a solution when $f$ is ${\mathcal C}^2$. The density argument suggested in the comments unfortunately seems to break down along the way (see Martin R's comment below).
We will show that the limit of $d_n=n(b_n-a_n)$ is $\frac{f(1)^2-f(0)^2}{2}$. With my additional hypothesis on $f$, $|f|+|f''|$ is bounded by some constant $M$ on $[0,1]$. For any subinterval $(a,b) \subseteq [0,1]$, we have
the following error estimate for the trapezoidal rule (see for example,
here for a proof)
$$
\Bigg| \int_a^b f(t)dt - (b-a)\bigg(\frac{f(a)+f(b)}{2}\bigg) \Bigg| \leq \frac{M(b-a)^3}{12} \tag{1}
$$
Using (1) with $a=\frac{k-1}{n}$ and $b=\frac{k}{n}$, we deduce :
$$
\Bigg| \int_{\frac{k-1}{n}}^{\frac{k}{n}} f(t)dt - \frac{1}{n}\bigg(\frac{f(\frac{k-1}{n})+f(\frac{k}{n})}{2}\bigg) \Bigg| \leq \frac{M}{12n^3} \tag{2}
$$
Multiplying by $f(\frac{k}{n})-f(\frac{k-1}{n})$ :
$$
\Bigg| \bigg(f(\frac{k}{n})-f(\frac{k-1}{n}\bigg)\int_{\frac{k-1}{n}}^{\frac{k}{n}} f(t)dt - \frac{1}{n}\bigg(\frac{f(\frac{k}{n})^2-f(\frac{k-1}{n})^2}{2}\bigg) \Bigg| \leq
\frac{M}{12n^3}(|f(\frac{k}{n})|+|f(\frac{k-1}{n})|) \leq
\frac{M^2}{6n^3} \tag{3}
$$
and summing and multiplying by $n$, we deduce
$$
\Big|d_n -\frac{f(1)^2-f(0)^2}{2}\Big| \leq \frac{M^2}{6n^2}
$$
which finishes the proof.
Comment: One point is unclear to me: $f$ can be uniformly approximated by polynomials, and I can see that $|f-p| < \epsilon$ implies $|a_n - a_n'| < C \epsilon$ and  $|b_n - b_n'| < C \epsilon$ where $(a_n') , (b_n')$ are the corresponding sequences for $p$. But I don't yet see why $n(b_n -a_n)$ and $n(b_n' - a_n')$ are arbitrarily close.
Comment: @MartinR I missed that, and now I think this part of the argument is not salvageable. I updated my answer accordingly. Thank you for your helpful comment
Comment: I see what @MartinR says. Still, it is a very nice idea to use the polynomial approximation.
Answer: It seems, if I didn't made any mistake, in general $n(b_n-a_n)$ may not converge!  I'll construct an explict counterexample to it. Consider periodic function $g:\mathbb{R}\to \mathbb{R}$ defined as:
$$g(x) = \begin{cases}0, \{x\} \le \frac{1}{4}\\ 4x - 1, \frac{1}{4} \le \{x\} \le \frac{1}{2}\\ 1, \frac{1}{2} \le \{x\} \le \frac{3}{4}\\ 4 - 4x, \frac{3}{4} \le \{x\} \le 1\end{cases}$$
and put $g_n(x) = g(2^{9n}x)$. We will construct our function $f$ as series $f(x) = \sum\limits_{n = 1}^\infty h_ng_n(x)$ with $\sum\limits_{n = 1}^\infty |h_n| < \infty$. We will prove that $2*2^{9n}(b_{2*2^{9n}} - a_{2*2^{9n}})$ is unbounded for suitable choise of $h_n$ thus sequence from the post can not converge. We are interested in the following sum:
\begin{equation}
\sum\limits_{k = 1}^{2*2^{9n}} \left(f\left(\frac{k}{2*2^{9n}}\right) - f\left(\frac{k-1}{2*2^{9n}}\right)\right)\int_{\frac{k-1}{2*2^{9n}}}^{\frac{k}{2*2^{9n}}}f(x)dx.
\end{equation}
Since for fixed $n$ everything is absolutely convergent we are basically interested in computing
\begin{equation}
\sum\limits_{k = 1}^{2*2^{9n}} \left(g_r\left(\frac{k}{2*2^{9n}}\right) - g_r\left(\frac{k-1}{2*2^{9n}}\right)\right)\int_{\frac{k-1}{2*2^{9n}}}^{\frac{k}{2*2^{9n}}}g_m(x)dx\qquad (1)
\end{equation}
for any $n, r, m > 0$. If $r > n$ then $ \left(g_r\left(\frac{k}{2*2^{9n}}\right) - g_r\left(\frac{k-1}{2*2^{9n}}\right)\right) = 0$ and so we are not interested in this cases. If $r < n$ then $ \left(g_r\left(\frac{k}{2*2^{9n}}\right) - g_r\left(\frac{k-1}{2*2^{9n}}\right)\right)$ has intervals of $k$ on which it is constant(those intervals of the length $2^{-9r}$ up to some factor of $2$ or $4$) and up to constant on them it equals to $0, 1, 0, -1, 0, 1, 0, -1, \ldots$ Now we have three cases:
1) $m > r$. In this case every copy of $g$ contained in $f_m$ contains in some interval of $k$ and moreover every interval is divided into some number(fixed for fixed $m, r$) of copyes of $g$ so we have sum of the kind $0 + I + 0 - I + ... = 0$ since in every tuple of $4$ intervals we get $0$(from now on lets call those tuples "quads").
2) $m < r$. In this case every quad is contained in some copy of $g$ in $f_m$ and moreover this copy(or, more preciesly, interval, to which it correspondes)  is divided into some number of this quads. Even more since $9$ is a huge number we can say that every quater of copy of $g$ is divided into some number of our quads. On the first and third quaters of $g$ we clearly has zero sum. With some computations one can show that second and fourth quaters also adds up to $0$.
3) $m = r$. In this case we up to some constant interested in $0*\int_0^{\frac{1}{4}}g(x)dx + 1*\int_\frac{1}{4}^\frac{1}{2}g(x)dx + 0*\int_\frac{1}{2}^\frac{3}{4}g(x)dx + (-1)*\int_\frac{3}{4}^1g(x)dx = 0$.
So the remainig case is $r = n$. In this case we would have $ \left(g_r\left(\frac{k}{2*2^{9n}}\right) - g_r\left(\frac{k-1}{2*2^{9n}}\right)\right) = (-1)^{k-1}$. First and second cases could be treated the same as before while in the third case we would have:
$$1*\int_0^\frac{1}{2}g(x)dx + (-1)*\int_\frac{1}{2}^1g(x)dx = \frac{-1}{4}.$$
So (1) is nonzero iff $n = r = m$ and equals to some fixed constant $c < 0$. Thus we have:
$$2*2^{9n}(b_{2*2^{9n}} - a_{2*2^{9n}}) = 2ch_n^2*2^{9n}.$$
Choosing $h_n = 2^{-n}$ we get what we want. Moreover since over some subsequence $h_n$ can decay arbitary slow we can not say anything better than $b_n - a_n \to 0$
In fact, when I was thiking about this problem I treated (1) as some kind of bilinear form on the space of continious functions so I wanted to find sequence of functions $(g_m)$ such that $<g_r, g_m>_n = c\delta_{n, m}\delta_{n, r}$ so I was searching for some kind of continious Rademacher functions.
Comment: It is interesting that we came up with a quite similar idea independently, but of course your construction seems much straightforward than mine. Nice answer :) (+1)
Answer: It seems we can compute limit in the case when $f$ is of bounded variation which means that even if counterexample exists it must look very ugly. $f$ is continious so it is uniformly continious so we can assume that  $|\int_{\frac{k-1}{n}}^{\frac{k}{n}} f(t)dt - \frac{1}{2n}(f(\frac{k}{n}) + f(\frac{k-1}{n}))| < \frac{\epsilon}{n}$ with $\epsilon \to 0$ as $n\to \infty$. So we have:
$|n(b_n - a_n) - \frac{1}{2}\sum\limits_{k=1}^n (f(\frac{k}{n}) - f(\frac{k-1}{n}))(f(\frac{k}{n}) + f(\frac{k-1}{n}))|\le \epsilon\sum\limits_{k=1}^n |f(\frac{k}{n}) - f(\frac{k-1}{n})| \le \epsilon Var(f)$
On the other hand $\frac{1}{2}\sum\limits_{k=1}^n (f(\frac{k}{n}) - f(\frac{k-1}{n}))(f(\frac{k}{n}) + f(\frac{k-1}{n})) = \frac{1}{2}(f(1)^2 - f(0)^2)$ so the limit is equal to $\frac{1}{2}(f(1)^2 - f(0)^2)$.


ERROR: Schema "x" does not exist

Question: I'm attempting to select the users from a 'users' table that have the most occurrences of their 'order_id' property in the 'shipments' table. This is what I've tried:
SELECT users.first_name, users.email, shipments.count(order_id)
    FROM users, shipments
    WHERE shipments.order_id = users.current_order_id
    GROUP by shipments.order_id
    ORDER by shipments.count(order_id) DESC
    LIMIT 25

But I'm getting an error of:
ERROR:  schema "shipments" does not exist

Any ideas?
Answer: You are doing the COUNT the wrong way. The tableName and column name go inside the COUNT(). or you could do COUNT(*) in this case:
SELECT users.first_name, users.email, count(shipments.order_id)
FROM users, shipments
WHERE shipments.order_id = users.current_order_id
GROUP by users.first_name, users.email
ORDER by count(shipments.order_id) DESC
LIMIT 25

Also, you should be doing GROUP BY the columns that you select that are not the aggregate function.
Comment: Different error now: "ERROR:  column "users.first_name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: EXPLAIN SELECT users.first_name, users.email, count(shipment..."
Comment: edited my answer. with additional information and updated query
Comment: Hmm this seems to have completely broken it! I'm getting data back, but the users returned have random numbers of matching orders. Row 1 is a user with <20 orders, but I know the top user has had 76.
Comment: The problem might be in the way your schemma was created. You have current_order_id in users table. That doesn't look like a good way to JOIN a users and shipments tables. You should probably have user_id in shipments instead. Otherwise you can only have a 1 to 1 relationship.

ERROR: Schema "x" does not exist


AES Encryption in flutter

Question: I want to AES encrypt data for the http requests in flutter. I have password and plaintext string which I want to encrypt.
I am using flutter_string_encryption. I have achieved in iOS app but both the output differs.
final salt = await cryptor.generateSalt();
final generatedKey = await cryptor.generateKeyFromPassword(password, salt);
final String encrypted = await cryptor.encrypt(string, generatedKey);

Comment: If encypting network call is the aim. I would recommend TLS(HTTPS) that would solve the problem. You'll also have to pin the Cert/PubKey in app to make it full-proof.
Comment: Actually requirement is to encrypt the data in request. But comparing encrypted text differs. I think it is because of

final salt = await cryptor.generateSalt();

salt is randomly generated.
Comment: Yes, salt should be known to encrypt/decrypt on both ends.
Comment: No luck getting encrypted data, can you suggest some sources for the same?
Answer: Do you have any particular attachment to flutter_string_encryption? I wrote a custom package based off PointyCastle and written entirely in Dart which can solve AES for you.
https://pub.dev/packages/steel_crypt
It looks something like this implemented:
var fortunaKey = CryptKey().genFortuna(); //generate 32 byte key with Fortuna; you can also enter your own
var nonce = CryptKey().genDart(len: 12); //generate IV for AES with Dart Random.secure(); you can also enter your own
var aesEncrypter = AesCrypt(key: fortunaKey, padding: PaddingAES.pkcs7); //generate AES encrypter with key and PKCS7 padding
String encrypted = aesEncrypter.gcm.encrypt(inp: 'somedatahere', iv: nonce); //encrypt using GCM
String decrypted = aesEncrypter.gcm.decrypt(inp: encrypted, iv: nonce); //decrypt

Answer: AKushWarrior's answer is right but if you don't want to use salt key it's ok, you can directly go with your encryption key
         encryptionKey ="qwertyuiop";//your encryption key
         var Encrypter = AesCrypt(encryptionKey, 'cbc', 'pkcs7');
         //using AES : CBC/ECB , encryptionKey and PKCS7 padding
         EncryptedData = Encrypter.encrypt("hello world");//your data instead of Hello world
         DecryptedData = Encrypter.decrypt(EncryptedData);

Comment: This is seriously insecure. You need an IV if you encrypt using the same key more than once. https://security.stackexchange.com/questions/35210/encrypting-using-aes-256-do-i-need-iv

AES Encryption in flutter


Cannot ssh to the server

Question: I have a problem ssh to the server.
Here is the content of my ssh file.
Host colfax
User xxxx
IdentifyFile -------
ProxyCommand ssh -T -v -i -----@---.com
Getting the below error:
Ssh_exchange_identification: connection closed by remote host.
Comment: Have you added the public key part on the remote machine?
Comment: @minhazur: Yes I have.
Comment: You can try this steps http://edoceo.com/notabene/ssh-exchange-identification
Answer: Could you please try downloading the key from Chrome or Mozilla Firefox.
The same problem got resolved for me after downloading the key using chrome for both Windows and Linux.
Hope this will solve the issue.
Comment: I changed to Chrome and downloaded the key. It is working now. Thanks for your suggestion.

Cannot ssh to the server


Example of cumulative distribution function and the empirical distribution function

Question: A random of 100 rolls of the die. The outcomes 1, 2, 3, 4, 5, 6, occurred 13, 19, 10, 17, 14, 27 times, respectively. Calculate the cumulative distribution function and the empirical distribution function? Plot both function in R?
Thank you in advance!
Answer: The empirical cumulative distribution function (ECDF) is based on data.
It is a 'stairstep' function. For your data, starting from height $0$ below $x = 1,$
it jumps up by $13/100$ at $x = 1,$ by an additional $19/100$ at $x = 2,$
and so on, until reaching a height of $1$ at $x = 6.$
In R, your rolls of the die (sorted by increasing numbers on die faces), can
be represented as follows:
x = rep(1:6, c(13, 19, 10, 17, 14, 27))
table(x)
x
 1  2  3  4  5  6
13 19 10 17 14 27

Then we can plot the ECDF as follows:
plot(ecdf(x), main="ECDF of 100 Rolls of a Die")

We can represent the CDF of a fair die as shown below. And then plot this
CDF (dotted red line) on the same axes as the ECDF. Centers
of open dots are exact values of the CDF. For as few as 100 tosses, agreement between the observed ECDF and the theoretical
CDF seems very good.
k = 1:6;  cdf = (1:6)/6
plot(ecdf(x), main="ECDF of 100 Rolls with Theoretical CDF")
 lines(k, cdf, type="s", col="red", lty = "dotted")
 points(k, cdf, col="red")

To do your own plotting on graph paper, you might start by
making tables of the ECDF and CDF at points $x = 1, 2, 3, 4, 5, 6.$
Comment: Thank you so much!


MSP430 g2553 ADC Voltage conversion, not getting a value

Question: I'm trying to program a TI MSP430 g2553 ADC10 to read input voltages. When I connect it to a power source, however, I get no value from the ADC10MEM register. I've tried many different tutorials, but nothing has been able to fix the issue. I believe it's an issue in how I'm setting up the ADC, but I don't know what a lot of the variables are, so I'm not sure what needs to be set and what doesn't. Does anyone have any insight on how I can figure this out, or know what to do to properly set up the ADC? The code I'm using was taken from
http://blog.elevendroids.com/2013/06/code-recipe-reading-msp430-power-supply-voltage-level/
and modified to fit my needs, but it isn't giving me any working value, even when the power supply is off, it doesn't give me 0.
Comment: Can you post your code? The code behind the link looks fine, I would probably have gone with the 2.5V reference right away to make it simpler, but it should work.
Answer: Could you try this? It returns the voltage in millivolts:
<code>unsigned read_voltage(void)
{
    unsigned adc, voltage;

    ADC10CTL1 = INCH_11 | ADC10DIV_3 | ADC10SSEL_3;
    ADC10CTL0 = ADC10SHT_3 | ADC10ON | ENC | REF2_5V | ADC10SC | REFON | SREF_1;
    while (ADC10CTL1 & ADC10BUSY) ;
    adc = ADC10MEM;
    ADC10CTL0 &= ~ENC;
    voltage = adc * 5;

    return voltage;
}
</code>


How to stop radio button from getting checked if there is a validation

Question: I have a layout with three radio button like this:

          <input type="radio" name="optradio" value="ABC" (change)= "showSection($event, 'abc')" checked>   ABC

            <input type="radio"  name="optradio"  value = "EFG" (change) = "showSection($event, 'EFG')">  EFG

            <input type="radio"   name="optradio" value = "HIJ"  (change) = "showSection($event, 'HIJ')">  HIJ

Now i have two arrays
let array_one = [];
let array_two = [];

I have a validation that if array_two.length <=1  I should not be able to switch between radio button's
I have used angular my problem is i am able to implement validation but the thing is radio button is getting checked and reaching to the selected one.
for example :
i am on 2nd radio button and now array_two.length <=1 is satisfied but now when clicking on 1st radio button 1st one is getting checked. i have to stop 1st one from getting checked
please can someone help
Comment: please post a stackblitz example, i don't fully understand your question.
Comment: @Robert : i have to stop my radio button to get selected if conditions / validation get satisfied
Comment: Have you tried to bind the disable propriety of radiobutton to a boolean variable that check the condition statement?
Comment: @Robert : I cant make it disable these all three buttons need to be in enabled mode only.
Comment: https://angular-ubw5kn.stackblitz.io
Comment: in the above example just like if you click on any radio button it will simply give you alert and it will not change to the selected radio button. similarly i have to show a pop up if array_two length is more den 1 and i have to stop radio button button from getting selected
Comment: I guess you could do something like this: https://stackblitz.com/edit/angular-1qxajq?file=src/app/app.component.ts But seems like bad UX, I as a user would get annoyed and wondering why I cannot change the radio button value ;) But if you have some popup like you say, then that would be ok :)
Comment: I tried this event.preventDefault() still it is moving to different radio button and pop up is something i am able to see.. not working
Comment: well it works in the stackblitz! did you change `change` to `click`?
Answer: I'm not sure that is what you want:
https://stackblitz.com/edit/angular-aphp8r
I created a formgroup that check the value of his children:
this.form = new FormGroup({
  gender: new FormControl(),
  age: new FormControl(),
  city: new FormControl()
});

when you click on a radiobutton, his value get pushed to the array and the condition
array_two.length <=1 become true:
this.Gender.valueChanges.subscribe(
      (x) => {
        this.array_one.push(x);
      }
    );

    this.Age.valueChanges.subscribe(
      (x) => {
        this.array_one.push(x);
      }
    );

    this.City.valueChanges.subscribe(
      (x) => {
        this.array_one.push(x);
      }
    );

when an action is triggered on a formgroup, the formgroup check the formcontrol children and look at their value, if the value is null, it's mean that it's not been checked so it disable the formcontrol. To get that i'm simply iterating over an object to get the key, the key is the formcontrol name and i use that to disable it, if it is null.
this.form.valueChanges.subscribe(
      (x) => {
        if(this.array_one.length >= 1) {
         for(var k in x) {
           console.log(k, x[k]);

           if(x[k] == null) {
             this.form.get(k).disable();
           }

          }
        }
      }
    );

If you have any question regards the code or other things, please tell me. I highly raccomend you to go with reactive form[0] in order to have the full control on the logic.
[0]https://angular.io/guide/reactive-forms
Comment: I dont need such a great example robert i only need one way to stop my radio to going to new state selected if my array length is more then 1
Answer: If I have understood correctly, you need to disable all the radio buttons upon a condition. For that, you need to use the disabled property binding with the radio buttons as
[disabled]="array_two.length <=1"

Stackblitz at https://stackblitz.com/edit/angular-disable-radio-group-on-condition


Unity iOS app's screen goes black on startup, but still appears to be running

Question: I'm using Unity Pro 4.5.3f3 + iOS Pro 4.x, Xcode 5.1.1, and tested with an iPhone 4S and 5 running iOS 7.1.2.
I recently took over development of an iOS app from a departing coworker at my game studio, and I'm attempting to compile the app in Xcode on my own machine for the first time. I have followed his instructions for which extra Obj-C code to add manually. The app works perfectly in Unity. Everything builds in Xcode without errors.
When the app runs, I see the custom splash screen loading as intended, but then the screen goes completely black. The app appears to be running fine...I can hear its sounds playing and it even responds when I tap the screen in areas where I know the buttons are supposed to be. There are no errors thrown to the log. But it doesn't display any graphics at all!
I suspect the Prime[31] plugin has something to do with it, as I get a strange log output saying Prime[31] didn't recognize several other plugins. And I can't delete it to test my theory, because way too many scripts depend on it.
Does anyone know how to fix this? I have lots of tasks to do for this app and I can't let something like this slow me down.
Comment: Ok, I just managed to delete Prime[31] from the app without breaking it, and the bug is still there, so I think that plugin is innocent. Anyone else have any ideas on what might cause something like this?
Answer: I encountered this issue last night when trying to configure my app to be compatible with Facebook Canvas.
Below is the line of code that was breaking:
<code>FB.Canvas.SetAspectRatio(9,16, FBScreen.CenterHorizontal(), FBScreen.CenterVertical());
</code>
To fix my issue I surrounded the line with the UNITY_WEBPLAYER preprocessor directive like so:
<code>#if UNITY_WEBPLAYER
    FB.Canvas.SetAspectRatio(9,16, FBScreen.CenterHorizontal(), FBScreen.CenterVertical());
#endif
</code>
Doing this causes that line of code to only be compiled and run in the web player, and not on the mobile device. Hope that helps!
Comment: I don't have support for Canvas in my code. Not sure what was breaking, but for the time being I've reverted to Unity 4.5.2, which doesn't have this problem.


What is the coefficient of $x^6$ in the development of $A$?

Question:
What is the coefficient of $x^6$ in the development of $A$, where $A=(x^2-3x-1)^4$.
Comment: Have you tried just multiplying it out?  What did you get?
Comment: Actually , we need to solve it using binomial theorem
Comment: I've made a mistake while editing. $A = (x^2-3x-1)^4$, not $2$.
Comment: Yep, I din't noticed that thanks. I've fixed it.
Comment: If you are required to use the binomial theorem, you should put that in your question.  Have you looked up the theorem?  What have you tried?
Answer: With the new edit,  the answer is the sum over all contributions, which are $\binom{4}{3}(x^2)^3(-1)$ and $\binom{4}{2}(x^2)^2(-3x)^2(-1)^2$, giving $-4+54=50$.
Comment: What about $(x^2)^2(-3x)^2$?
Comment: Well , yeah we need $(x²)³$ to make $x⁶$ but the coefficient is not 1 nor 4 i found 54 and my teacher found 50.
Comment: Back when it was a square, the answer would be $0$ as there was no $x^6$ term
Comment: Yeah , sorry my bad.
Comment: Well , I still think my teacher is wrong cause what you said is also what i did and it gives me 54
Comment: @BenAbderrahmene: No, look at the update.
Comment: @AlexR hi can I ask you a question when $(x²)³$  wouldn't it be multiplied by $-3x-1$ (I didn't understand where -1 came from) ,so it wouldn't be -4 in the final sum ?
Comment: @BenAbderrahmene: The total parenthetical is raised to the 4'th power, meaning that every term in the expansion (before grouping like-powers) is determined by choosing 4 terms from the parenthetical, with replacement. So we chose $x^2$ 3 times and $-1$ is chosen once. Contrast this with $(x^2)^4$ which won't have a $(-1)$ term since all 4 powers were used up. See Bernard's multinomial answer for the fact that the powers must sum to 4.
Answer: Hint:
You can use the multinomial formula: as the expansion is
$$\sum_{\substack{i,j,k\: \text{ s. t.}\\i+j+k=4}}\!\!\!\frac{4!}{i!\,j!\,k!}(x^2)^i(-3x)^j(-1)^k,$$
the coefficient will be
$$\sum_{\substack{i,j,k\: \text{ s. t.}\\i+j+k=4}}\!\!\!\frac{4!}{i!\,j!\,k!}(-1)^{j+k}3^{\mkern 1mu j}.$$
Answer: You want binomial, here's binomial.  Write $A$ as
$$((x^2-3x)-1)^4 = (x^2-3x)^4 - 4 (x^2-3x)^3 + 6 (x^2-3x)^2 - 4 (x^2-3x) + 1 $$
Coefficient of $x^6$ in $(x^2-3x)^4 = x^4 (x-3)^4$ is coefficient of $x^2$ in $(x-3)^4$
is $6 (-3)^2 = 54$.
Coefficient of $x^6$ in $-4(x^2-3x)^3$ is $-4$.
Coefficients of $x^6$ in the other terms are $0$.
So the result is $54-4=50$.
Answer: Let $x=1/y$ and multiply the resulting equation by $y^8$ to get
$$ g(y) = (1-3y-y^2)^4$$
Note that the coefficient of $x^6$ in the original equation is the coefficient of $y^2$ in the new equation.
The coefficient of $y^2$ is the new equation esily found by $$g'' (0)/2 =100/2 =50 $$


Run code only once after an application is installed on Android device

Question: I want to run a piece of code once only after the application is installed. After it has been executed, that particular piece of code should not be called again, even for an upgrade.
Comment: Shouldn't that just be a part of the installer?
Comment: @Woot4Moo - What do you mean by installer? I am not familiar with that (on android)
Comment: I don't develop on the platform I just thought Google would have made an extensible framework for installers.  Like installbuilder or installshield.
Comment: @Woot4Moo: Nope, nothing like that exists.
Answer:
Check if boolean X is True in shared preferences
If not:
a. Run the special code
b. Save x as true in shared preferences

For example:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false)) {
    // run your one time code
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean("firstTime", true);
    editor.commit();
}

Comment: This is NOT the right method to do this,because when you clear application data from the application manager then too it will take as a new run even though app didn;t get uninstalled
Comment: I think it's acceptable to run the code again if the user cleans the data. If you really think it shouldn't then, you could touch a file on the SD Card instead.
Comment: it always skips the if statement for me.. how did you manage to execute it. can you please share it with me... thanks...
Comment: @medampudi - I made a mistake, the condition should be the opposite. see edit.
Comment: @Rauf, You are right, so what would be your solution for this problem?
Comment: @EmilAdz still no solution found which satifies :(
Comment: @Rauf - long time, but still... This answer is meant for usability. e.g. - if you have code that should initialize stuff etc. If you look at it from security perspective, you can't trust pretty much anything on the user device, and then you will need to perform such a check by providing some kind of UUID to your server and performing the check there...
Comment: But before using the shared pref I need to initialize it, Where should I initialize it, so that it only runs once
Answer: I've used a shared preference in the past, but if you are wanting to do something onInstall you could also look at a install receiver. MyInstallReciever implements BroadcastReciever
<receiver
    android:name="com.MyInstallReciever"
    android:exported="true">
    <intent-filter>
        <action
            android:name="com.android.vending.INSTALL_REFERRER" />
    </intent-filter>
</receiver>

Comment: "com.android.vending.INSTALL_REFERRER" is not a safe way. because when installing app, application is in STOP status. maybe I could not explain it good but with a little research about "INSTALL_REFERRER" will know this.
Comment: also, it seems that this will only work when installing from Google Play (com.android.vending), not from "any source".
Answer: use this simple code
   if (getPreferences(MODE_PRIVATE).getBoolean("is_first_run", true)) {
        /*
         * your code here
         */
        getPreferences(MODE_PRIVATE).edit().putBoolean("is_first_run", false).commit();
    }

Answer: Use a boolean value to check if its first execution of code or not.
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedpreferences.edit();
if(sharedpreferences.getBoolean("is_first_exec",false))
    {
        editor.putBoolean("is_first_exec",false);
        //your code here ...
    }

The getBoolean() like every other get method of SharedPreference, takes a second default parameter which will return null the first time (as there is nothing in the SharedPreference file). Thus, the code inside the if(){...} block will execute only once.
Footnotes: SharedPreferences
Answer: Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
        //  Initialize SharedPreferences
        SharedPreferences getPrefs = PreferenceManager
                .getDefaultSharedPreferences(getBaseContext());

        //  Create a new boolean and preference and set it to true
        boolean isFirstStart = getPrefs.getBoolean("firstStart", true);

        //  If the activity has never started before...
        if (isFirstStart) {

            //  Launch app intro
            final Intent i = new Intent(MainActivity.this, DefaultIntro.class);

            runOnUiThread(new Runnable() {
              @Override public void run() {
                startActivity(i);
              }
            });

            //  Make a new preferences editor
            SharedPreferences.Editor e = getPrefs.edit();

            //  Edit preference to make it false because we don't want this to run again
            e.putBoolean("firstStart", false);

            //  Apply changes
            e.apply();
        }
    }
});

// Start the thread
t.start();


Counting groups based on PSU(4,3)

Question: How many almost quasisimple extensions of PSU(4,3) are there?
As noted in Constructing central extensions or Schur cover of U4(3) in GAP this group is too large to be in the perfect groups library (the order 3,265,920 is over 2 million) and it has abnormally large Schur Multiplier (36) and large automorphism group ($D_{8}$) so there are many almost quasisimple groups associated with it.
The Atlas only lists these eleven https://brauer.maths.qmul.ac.uk/Atlas/v3/clas/U43/ :
U4(3)
2.U4(3)
U4(3).2_1
U4(3).4
U4(3).2_2
U4(3).2_3
3_2.U4(3).2_3
3_2.U4(3).2_3'
U4(3):D8
3_2.U4(3):D8
2.U4(3).D8
I know GAP already contains some thing on this list such a CharacterTable("6_1.U4(3).2_2");
Is there a way to convince GAP to print out a list of all groups in the character table library defined by a string that contains "U4(3)" ? Because I guess that would be a
good start. Does GAP character table library even contain all the almost quasisimple groups based on PSU(4,3)?
Comment: I posted a permutation representation of the Schur cover of $U_4(3)$ in an answer under https://math.stackexchange.com/questions/4775608/constructing-central-extensions-or-schur-cover-of-u43-in-gap/4827195#4827195
Comment: @ahulpke that does look interesting! Also on an unrelated note I noticed that $ A_7, 3.A_7, 6.A_7 $ all have faithful 6d irreps. Is there a story here that's worth asking about? Or is it just a meaningless coincidence and I shouldn't bother making a MSE question?
Comment: oh wait I think I answered my own question the $ A_7 $ is just the standard deleted permutation representation so is a subgroup of $ SO(6) \subset SU(6) $ and then $ 3.A_7 $ is not a subgroup of the compact symplectic group $ Sp(3) \subset SU(6) $ but I think it might be a subgroup of the central product $ \zeta_6 \circ_2 Sp(3) \subset SU(6) $? And then $ 6.A_6 $ is the only Lie primitive one, for example it is the only one that is irreducible in the adjoint representation of $ SU(6) $. Maybe I'll try to find all maximal closed subgroups of $ SU(6) $ that could be fun
Answer: To get groups mapping onto $U_4(3)$, you could use:
c:=CharacterTable("U4(3)");
NamesOfFusionSources(c);

and eliminate the ones that are subgroups. You could do similarly for U4(3).2_1 and so on.

Counting groups based on PSU(4,3)


$1^{-1}+2^{-1}+\dots+\Big(\frac{p-1}{2}\Big)^{-1} \equiv -\frac{2^p - 2}{p} \mod p$ for an odd prime $p.$

Question: I've reduced a problem down to proving this identity. Unfortunately, I don't know where to even start. There has to be some way of expanding the RHS or combining terms on the LHS, but I don't see it. Any hints?
Comment: The key idea is to start from $a^{n/2} \equiv -1 \mod p$
Comment: @zeraouliarafik Where $n = p-1$?
Comment: yeah , I think it would be works try it out
Answer: David W. Boyd writes:

There is a relationship between values of certain $H_n$ and Fermat's quotient $q_a = {(a^{p-1}-1)}/p \bmod p$. For example, a result from Eisenstein from 1850 [Dickson 1952, p. 41] states that $H_{(p-1)/2} \equiv -2q_2 \mod p$; this is easily seen from the binomial expansion of ${(1 + 1)}^p$.

This is your hint, and if that's not enough, the reference where to find a proof.
[Dickson 1952]: L. E. Dickson, History of the Theory of Numbers.
[Boyd 1994]: David W. Boyd, A $p$-adic Study of the Partial Sums of the Harmonic Series.
Comment: Thanks. The binomial expansion gives $1^{-1} - 2^{-1} + \dots + (-1)^{p-1} (p-1)^{-1},$ but this is an expression I had earlier simplified to the LHS in the title. So my solution will be even shorter than expected.
Comment: @Displayname I have a proof using elementary number theory. Do you want me to write?
Comment: @ShubhrajitBhattacharya Binomial theorem and modular arithmetic is already elementary, but go ahead. I'm curious as to how you can get even simpler than expanding $((1+1)^p - 2)/p.$
Answer: This is not true, for example $\text{p}=47$. We get:
$$\sum_{\text{k}=1}^{23}\frac{1}{\text{k}}=\frac{444316699}{118982864}\tag1$$
Which is not congruent to:
$$\frac{2-2^{47}}{47}\mod{47}=-2994414645858\mod{47}=6\tag2$$
Comment: Check again. $47$ divides $6\cdot118982864 - 444316699.$
Comment: $118982864^{-1}  \equiv 37 \mod 47$ and $37 \cdot 444316699 \equiv 6 \mod 47$.
Comment: By the way, which calculator spit out a denominator of $2^4\cdot7\cdot11\cdot13\cdot17\cdot19\cdot23$? What happened to $3$ and $5$?
Comment: @Displayname Those got cancelled. $$\frac{1}{5} + \frac{1}{10} + \frac{1}{15} + \frac{1}{20} = \frac{12 + 6 + 4 + 3}{60} = \frac{25}{60} = \frac{5}{12}$$ and similar but longer for the multiples of $3$.
Answer: This is an additional part to the given answer by @orlp, The following theorem discovred by many Authors repeatedly ( A fried -mann and J Tamarkine ,M Lerch  and Nielson ], for $p \geq3$  and $1\leq m \leq p-2 $
$\sum_{j=1}^{p-1} j^m q_p(j) \equiv \frac{-B_m}{m} \bmod{p}$, here $q_p(j) =\frac{j^{p-1}-1}{p}$ denote the fermat quotient and $B_m$ are Bernouli numbers  such that $p\nmid j$, For reference you may check this Handbook (page 548)


In a regression is the Y-intercept a measure of unaccounted biases?

Question: I have been working on a set of data which contains information on the width, age, weight of statues and relate them to the price (I am not actually working on that, but I cannot disclose the topic of my work).
I came up with the following regression:
$Price = -9 -width + 4 log10(age) + 8  height$
the minimum-maximum interval for each parameter are:
<code>width = [0,1[
age = [200,4000]
height = [0.65,0.89]
</code>
My price therefore varies between about 4 and 12.
As the value of the constant is -9, which is of the same order of magnitude as my price range, I am wondering if this regression could be criticized for being to generic, with a lot of the price variation unaccounted for and "hidden" inside the constant.
Am I trying to over interpret my data here? Could my dataset be missing a crucial variable, for example the weight?
Comment: When you say "ranges for each parameter": is that the confidence interval or the min-max for each *variable*?
Comment: The min-max interval for each variable
Answer: The simple answer is no. Take a look at the following example. It shows a simple linear regression results between two variables $X$ and $Y$. The only difference between the black points and regression line, and the red ones, is that in the second case I changed $Y$ to $Y + 5$. In the "black scenario, the parameters are $\beta_0 = 0.1256, \beta_1 = 4.9122$, while in the "red" scenario $\beta_0 = 5.1256, \beta_1 = 4.9122$. Answer yourself: did the amount of unaccounted biases changed by five between the two scenarios? Is the "black" model worse because it has lower intercept?

The answer to both questions is "no". The only thing that has changed between the two models is that the mean of $Y$ has changed by five, what has led to intercept changing by the same value. That is exactly the role of intercept: to "shift" the regression line upwards, or downwards, on the $y$-axis, so to correct for the mean of the dependent variable. In fact, in most cases we do not expect the intercept to be anything close to zero, because this would mean regression line going through the origin what in many cases leads to inferior models as compared to the models that include the intercept (i.e. it is non-zero).
I guess that what you are looking for is rather the $R^2$ statistic, but beware that it can be misleading as describes in Is $R^2$ useful or dangerous?
Comment: @Sorade The answer to your question in the comment is also "no". First, in most cases it would be impossible to account for ALL the parameters. Second, it could happen that you have similar accuracy metrics for two different models, with different variables. Third, more variables does not mean that your model is going to be "better" (it can however lead to overfitting). In general, it's complicated. You should probably get some handbook on regression modeling if you find this unclear.
Comment: Thank you Tim, if I understood your answer correctly you are explaining why it is not okay to remove the intercept. I agree with that, my question was more whether the model could be criticised for being to general. Okay I get very good match with my data (adj. R2 > 0.97) but, still, maybe that the large intercept value, means that I don't have enough information to provide meaningful answers. Maybe the data only covered, very light statues. If somebody else was to use the regression for another dataset of heavy statues they wouldn't get a good R2.
Comment: @Sorade I said nothing about removing intercept, I linked the other thread for you to learn more about the role of intercept in regression. What I say is that intercept is related to the mean of Y and nothing more, it does not measure "bias" and I gave you example of identical models widh different intercepts that changed just because the mean of Y has changed.
Comment: @Sorade please look at the example once again. The models are identical and give identical predictions (that differ by 5), so how could one of them give less information then the another one?
Comment: Thank you. I still feel like I don't have an answer to my question, but you gave me material to think about. I'll brew on it a bit and see if I can maybe rephrase my question better. Maybe my question should be: " If my model has shown good predictability (say I have a divided my data into a test and train set) does it mean that I have accounted for ALL the important parameters for sure ? "
Answer: We rarely report or interpret the intercept in a linear regression model. In your case it is an extrapolation of the data. The intercept would be interpreted as a expected price for a product with width 0, an age of 1, and a height of 0. That is nonsense. A value of -9 is an artifact of the projection.
If you want a more interpretable intercept, center the covariates. Then the intercept is the average price for all covariates taking their average values.
Comment: @Sorade you refer to units, but no the units are not useless. The units are (presumably) dollars or revenue or... For -9 to "seem" off you need to become a statistician and look at plots and summary statistics: residuals vs. fitted values. Basically the only way that number is off is if you ran the model incorrectly, which is a software debugging question.
Comment: Thank you AdamO, your suggestion is interesting. As I am no statistician would you mind giving an example of how you would proceed ? Also, I understand that the "meaning" of the intercept is useless in terms of units of price. Yet the magnitude of it seems large compared to the value of the other terms.
Comment: Also, if he  centers the dependent variable, there will be no intercept at all!
Answer: Who is the audience that you expect will criticize the intercept? If it is a "business audience", they are much more likely to be concerned about model accuracy, which you haven't mentioned here.  The value of the parameter coefficients - showing the relative impact of each variable on price - is where you should focus your interpretation/discussion.


How to get xml file over http?

Question: A xml file with data will be sent over http to server my job is to get that xml file and parse it using web service and I am using Netbeans 6.9. How can i get that xml file can anyone tell me ?
Comment: possible duplicate of [To recieve Soap Message over Http using Java Web Service](http://stackoverflow.com/questions/4656489/to-recieve-soap-message-over-http-using-java-web-service)
Comment: i'm voting to close this because it seems to be the same question you posted a few days ago. you havn't got any answers to your other questions till now, i've seen that, but shouldn't you consider giving _more_ information about your problem instead of writing it in one confusing sentence? also, a link to your other question with would have been nice (but generally, reposting a question is never a good idea - you'll only get flames from that instead of answers... the best way would have been to edit you old question and try to rephrase it and giving more information about what you've tried)
Answer: Looking for something like this?
<code>URL xmlUrl = new URL("http://www.rekindle.co.za/rss.xml");
InputStream in = xmlUrl.openStream();
Document doc = parse(in);
</code>
Taken from a similar question about parsing at http://www.java-forums.org/xml/22674-get-xml-data-url.html
Comment: but problem is xml file will be generated automatically by another webservice for every 10 mins and sent to server using http. so i can't know xml file name then how can i read it from http port.
Comment: It sounds like you would need to use `HttpServletRequest`.
Answer: Assuming you're responsible for writing the service using servlets and the xml file will be POSTed to the server, you can access it using HttpServletRequest.getParameter(paramName).
Comment: tks but can you tell me briefly.
Answer: Use HttpClient for the same to recieve the XML , After recieving the xml use JAXB/XMLbeans parser to parse the xml.
You must have to sure about xml's xsd before parsing the same.
If already you are having xsd against the incoming xml then just created the classes by using using any above mentioned tool.

How to get xml file over http?


Expose AJAX application to Google

Question: I have one big web app that is basically one page where every content is created dynamically. It also has a forum, how do I expose the forum to Google or other search engines? Should I create a seperate view of the forum especially designed for search engines?
Answer: Use meta tag in your html. This metadata can be used by search engines (keywords).
<code><meta name="description" content="xyz your web site name etc">
<meta name="keywords" content="xyz your web site name etc">
<meta name="author" content="xyz your web site name etc">
</code>

Expose AJAX application to Google


Advice for a new JavaScript developer moving from Flash / ActionScript 3?

Question: I have been moving over to JavaScript (esp. canvas) from Flash / Flex / ActionScript 3 (JavaScript is a more open platform), and I was wondering if anyone has any advice on differences between the two platforms, important things to note, pitfalls, optimizations, etc.
Answer: First advice: Turn arround! ;-)
If you can't then I would tell you the following:

On the AVM2 everything is consistent in behaviour and how things were displayed. JavaScript is exactly the different. You can find parts of you code that work different in every browser. So you really need to test on different browsers.
Start learning JavaScript, NOT any framework (most people on Stackoverflow would suggest jQuery). Later if you are familiar with most of the pure JavaScript stuff you could chose a framework of you choice.
Comment: As crazy as it sounds, I don't wish to turn around because of the closed nature of Flash. I would rather have a semi-decent language that is free, than an excellent language that is closed.
Comment: then you maybe should have a look at: haXe (http://www.haxe.org) it is open source language and it compiles to flash movies (and JavaScript, PHP and other platforms too)
Comment: I have seen HaXe before, and it is very nice. I may consider teaching myself HaXe one of these days.
Answer: Canvas in particular does not work as consistently between browsers as Flash, which is almost completely consistent when its available. If you don't already, you will want to get used to testing things in multiple browsers.
Comment: I understand this, but I am more of a hobbyist, so I don't care about IE. (also, I could always use IECanvas)


SVM training method (or alg.)

Question: I'm using SVM classification (Matlab) within my research works, and I want to know:

The advantages and disadvantages of each training algorithm, i.e., SMO, LS and QP
In general case, what is the suitable algorithm?
If the choice of one of them can impact the classification performance?
If the are any relationship between the choice of training method (or algorithm) and the choice of the kernel function.
Answer:
1) The advantages and disadvantages of each training alg. i.e SMO, LS and QP

SMO: state-of-the-art for nonlinear SVM. Always use SMO over traditional QP as it is way faster. By LS I assume you refer to LS-SVM, which is a distinct algorithm from standard SVM and should not be compared directly.

2) In general case, what is the suitable alg. ?

SMO.

3) If the choice of one of them can impact the classification performance ?

No. Unless you heavily use additonal heuristics to decrease training time.

4) If the are any relationship between the choice of training method (or alg.) and the choice of the kernel function.

No. The choice of kernel defines the optimization problem. The methods you list are ways to solve said optimization problem (SMO and QP solve traditional SVM, LS-SVM is a different optimization problem).
Comment: Thank you for this response. But precisely, I would like to know the main difference(s) between SVM (SMO) and LS-SVM. The most performant in general case and the faster.
Comment: Performance-wise they are competitive. Nonlinear LS-SVM trains faster than nonlinear SVM (solving linear system vs. solving QP). Predicting with an SVM is faster than LS-SVM because SVM is sparse whereas LS-SVM is not.
Comment: Thank you. But what did you mean by "because SVM is sparse"?
Comment: An SVM model is based on the so-called *support vectors*, which is a subset of the training data (often a small fraction, hence sparse). In an LS-SVM model, all data instances become support vectors unless some additional measures are taken.
Comment: So can we said that LS-SVM is more efficient ?
Comment: Depends on your definition of efficiency. I roughly described the general tradeoff so now it's up to you to decide which method you prefer.
Comment: LS-SVM is basically ridge regression (L2 regularized least squares). Least squares is not really suited for classification (logistic regression would be). Therefore, I would always prefer a normal SVM over LS-SVM.
Comment: Can I then conclude that:

1) Training: LS-SVM is faster,
2) Classification: SVM is faster,
3) Accuracy: it depends on the context ?
@MarcClaesen: Can you please confirm or correct,

SVM training method (or alg.)


Existence of weak* limit of weak cauchy sequence.

Question:
Problem: Let $\{x_{n} \}$ be a weakly Cauchy sequence in a normed linear space $X$. Then, there exists $x^{**}$ in $X^{**}$ such that $x_{n}$ converges weak* to $x^{**}$ and $\|x^{**}\| \leq \lim\inf_{n \to \infty}\|x_{n}\|$.

My attempt: Since $x_{n}$ is weakly Cauchy, in the viewpoint of $X^{**}$, it is weak* Cauchy, thus, from boundedness of norm of $x_{n}$, and any closed ball is compact by the Alaoglu's theorem, there exists $x^{**}$ such that $x_{n} \to x^{**}$ in weak star sense.
However, I don't know how to show that $\|x^{**}\| \leq \lim\inf_{n \to \infty}\|x_{n}\|$. Could you give me a hint to approach this problem?
Comment: It is a weakly Cauchy sequence, not a net?
Comment: Your application of Alaoglu is not clear to me...
Answer: $\forall\varepsilon>0$, there exists some $x^*\in X^*$ with $\|x^*\|=1$ such that
\begin{align*}
\|x^{**}\|-\varepsilon\leq |x^{**}(x^*)|=\lim_{n} |x_n(x^*)|\leq \liminf_{n}\|x_n\|.
\end{align*}
The last inequality is because $|x_n(x^*)|\leq \|x_n\|\forall n$.
Hence, $ \|x^{**}\|\leq\liminf_{n}\|x_n\|$.
Answer: This has nothing to do with Alaoglu.
Since $(x_n)$ is weakly Cauchy, for every $x^*\in X^*$ the sequence $(x^*(x_n))$ is Cauchy, hence convergent. So we can define $$x^{**}:X^*\to\mathbb C$$by $$x^{**}(x^*)=\lim_nx^*(x_n).$$
Uniform boundedness shows that $||x_n||$ is  bounded, hence $x^{**}$ is bounded. And $$|x^{**}(x^*)|=\liminf|x^*(x_n)|\le\liminf||x^*||\,||x_n||
=(\liminf||x_n||)(||x^*||),$$ so $||x^{**}||\le\liminf||x_n||$.
Comment: Wow, I thought in wrong way. Thank you!


onclick function using attribute in jquery

Question: Trying to get an alert box on click, but it doesn't alert. when I try on my localhost. But it alerts on JSFiddle. Why so?
My localhost code:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.10/css/bootstrap-select.css">

      <select id="right_option" class="form-control selectpicker" name="part" data-live-search="true" required>
        <option value="" selected disabled hidden>Select Name</option>
        <option value="Alexa" data-tokens="Alexa">Alexa</option>
        <option value="John" data-tokens="John">John</option>
        </select>

Comment: I tried your code and it seems to work fine
Comment: check your dev tools console for errors. Most chances are any of the libraries you're using (in particular, jQuery) are not loading.
Comment: @ludovico I checked dev tools console no warning and errors there...
Comment: @Echolot for JSFiddle it works, but when I try it on my localhost it doesn't for me
Comment: have you tried doing a console.log at the beginning of your ```$(document).ready(function() {``` ?
Comment: What is the result of $("[aria-owns='bs-select-1']").length ?
Comment: @xomunita I tried this on my local computer using the Live Server extension in Visual Studio Code
Comment: @JeroenHeier it's **0**
Comment: @ludovico you mean something like: `$(document).ready(function() {
console.log('Happens'); });`? If yes, console display *Happens*
Comment: So that's the problem. Review your selector. This should be > 0 in order to get any results.
Comment: @JeroenHeier the same codes and selector which I try at local gives length as *1* in jsfiddle
Answer: looks like localhost is taking time to render try giving some time to registering the onclick listener. following code worked for me. try tweaking the timeout milliseconds argument.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.10/css/bootstrap-select.css">

      <select id="right_option" class="form-control selectpicker" name="part" data-live-search="true" required>
        <option value="" selected disabled hidden>Select Name</option>
        <option value="Alexa" data-tokens="Alexa">Alexa</option>
        <option value="John" data-tokens="John">John</option>
        </select>


xmlhttprequest in chrome extension

Question: I am developing a chrome extension and I have an iframe which I use in my extension. This is what I do with my iframe
"When I drag and drop a image to my iframe I handle the drop event in one of the content scripts and pass that function call my extension code. There I create a xmlhttprequest object and then send the URL of the image to a php file in my server."
This is what is happening. I get a readyState of "4" but there is no POST request going out of my browser. I checked with the "NETWORK" tab in the browser but there is no POST request going out of the browser (I have listed my site in the permissions section of the manifest file).
This is my code --.>
JScript.js(One of the content scripts )
drop: function(event, ui) {
    var imgurl=$(ui.draggable).attr('src');
    imgurl="IMGURL="+imgurl;
    _post("www.somedomain.come/testing.php",imgurl,function(result){ alert("success")});
    }

This is my proxy in the same content script-->
  _post = function(url, data, callback)
    {
      console.log("sending post");
      chrome.extension.sendRequest({
      msgType:'post',
      data: data,
      url:url
      }, function(response){
        alert(response);
     });
    }

This my OnRequest function handler in background.html -->
 chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
  if (request.msgType === 'post') {
        alert("Now in OnRequest function");
        // console.log("Now in Onrequest Function");
        alert("Url: "+request.url + "\n Data : "+ request.data);
        ajaxcallingfunction(request);
        alert("completed the ajax call");
        sendResponse("success");
      }

    });

var ajaxcallingfunction = function(request){
     var xhr = new XMLHttpRequest();
   xhr.open("POST",request.url, false);
    xhr.onreadystatechange = function(){
    alert(xhr.readyState);
    if (xhr.readyState == 4) {
            alert(xhr.readyState);
        }
    }
    xhr.send(request.data);
   alert("after xhr call");
};

Answer: You have http:// in front of your url, right?
xhr.readyState doesn't tell much, it just means that it is done. Check out what's inside xhr.status, it would contain error code. If everything is ok it should be 200:
xhr.onreadystatechange = function(){
    if (xhr.readyState == 4) {
        alert(xhr.status);
    }
}

Comment: Thanks! that worked but now the problem is I am able to send the request but not the data. Whenever I try to get the URL of the image it is coming as an empty string. My php script uses simple $_POST["IMGURL"] array to get the url of the image. Any idea why I am always getting an empty string? I am sure I am having the data(url of the image) before sending it to the server. Am I missing something fundamental?
Comment: @Ajai Open network tab in chrome console and check what data is sent in that request. If all looks ok then do `print_r($_POST)` on php side and check what is received.

xmlhttprequest in chrome extension


MLE of the Uniform Distribution

Question: In a uniform distribution where $0\leq X \leq \theta$, the pdf is represented as $f(X|\theta) = \frac{1}{\theta}I(0\leq X \leq \theta)$, and the likelihood is $L(\theta) = \prod\frac{1}{\theta}I(0\leq X \leq \theta) = \frac{1}{\theta^n}I(\max \ x_i < \theta, \min \ x_i > 0)$. This makes logical sense to me, as the $x_i$ must be smaller than $\theta$ and larger than 0.
What I don't understand is that I'm supposed to be able to logically conclude from this information that the MLE of $\theta$ is therefore the MAXIMUM of $x_i$. I am reading that the correct answer to the question of "what is the MLE of $\theta$?" for this question is that it is the MAXIMUM of $X$.
That doesn't make sense. Say that $x_1 = 1, x_2 = 2, x_3 = 3$, and these values are plugged in as $\theta$ in the likelihood function to see which of them maximizes our likelihood function. Then clearly 1 is the maximizer here, since for X=1, $\frac{1}{1^n}*I(true)=1$, whereas for X=3,  $\frac{1}{3^n}*I(true)=0.333$ at MOST and is even smaller when n > 1, and that is all smaller than what we got for x = 1, so since x = 3 has a smaller likelihood, it wouldn't be the maximum likelihood estimator.
Explain where my logic here is wrong?
Answer: In your example $n=3$, $\min x_i = 1$, & $\max x_i = 3$. When $\theta=1$,
$$I(\max x_i \leq \theta, \min x_i \geq 0)=I(3\leq 1,1\geq 0)=I(\mathit{false})=0$$
This factor, & therefore the likelihood, will be zero for any $\theta<\max x_i$.

MLE of the Uniform Distribution


Interseção entre mesma tabela, auto relacionamento, mysql com INNER JOIN

Question: Olá, estou fazendo um banco de dados clone facebook. Tenho duas tabelas, uma de usuários e outra amizade. A tabela amizades é um auto relacionamento de usuários como mostra a imagem.

Esta tabela de amizades contém os IDs de cada usuário e preciso selecionar as amizades em comum entre dois usuários selecionados.
Por exemplo:

| idUsuario1    | idUsuario2    |
| ------------- | ------------- |
| 1.            | 2.            |
| 2.            | 3.            |
| 2.            | 4.            |
| 1.            | 3.            |

Preciso buscar nesta tabela os amigos comuns de usuario1 e usuario2. Ou seja, o retorno será 3,4. Porém não estou conseguindo filtrar corretamente a saida.
Answer: Veja a querie abaixo, ele liga as amizades do usuario 1 com as do usuario 2 e trás apenas os usuários das intersecções:
select u.*
from amizade a1, amizade a2 , usuario u
where  a1.idUsuario2 =  a2.idUsuario2
    and u.id  =  a1.idUsuario2
    and a1.idUsuario1  = 1 --id do primeiro usuario
    and a2.idUsuario1  = 2 --id do segundo usuario


Bivariate distribution: beta and binomial

Question: Consider a pair of RVs $X$ and $Y$, with the following conditional distributions:
$$X | Y=y  \sim Binom(L, y)$$
$$Y | X=x  \sim  Beta(\alpha + x, \nu)$$
where $L$, $\alpha$, and $\nu$; are all positive ($L$ is an integer of course).  Is there a name for the joint distribution of $(X,Y)$?  Or perhaps for the marginal distribution of $Y$?  I think that if $x$ is eliminated from the shape "parameter" of the beta distribution, then $X$ is beta-binomial distributed.  But in the above bivariate model, $X=x$ affects the shape parameter for the conditional distribution of $Y$, so I do not think $X$ is beta-binomial distributed.  Apologies if the above makes no sense; I am not very knowledgeable about probability and statistics.
Comment: Thanks for the formatting edits, mpiktas.  Didn't realize that the CV site engine can process LaTeX-style formatting.  Nice.
Answer: $\begin{align}
P(x,y) &= \frac{\binom{n}{x}}{\beta(\alpha+x,\nu)} \times y^{\alpha + 2x-1 }(1-y)^{n-x+\nu-1}  \\&= \frac{\binom{n}{x}}{\beta(\alpha+x,\nu)} \times \frac{y^{\alpha + 2x-1 }(1-y)^{n-x+\nu-1}}{\beta(\alpha+2x,n-x+\nu)} \times
\beta(\alpha+2x,n-x+\nu) \end{align}$
Integrating w.r.t $y$:
$\begin{align}P(x) &= \frac{\binom{n}{x}}{\beta(\alpha+x,\nu)} \times 1 \times
\beta(\alpha+2x,n-x+\nu) \\&= \binom{n}{x} \times \frac{\Gamma(\alpha+2x) \Gamma(n-x+v)}{\Gamma(\alpha +n +x + \nu)} \times \frac{\Gamma(\alpha+x+\nu)}{\Gamma(\alpha+x)\Gamma(\nu)}  \end{align} $
This can be further simplified by using properties of the Gamma function, but doesn't lead to a beta binomial  $X$


Question about playing chords

Question: I have read that:

In elementary piano, the left hand (lower notes) typically plays chords, while the right hand plays the melody. If you're playing pop or rock and singing, you might want to play the chords with the right hand and the bass note of each chord with the left hand.

1-So if you play the chords with the right hand, there needs to be someone else to play the melody? i.e. are you actually the bassist of the band in this situation?
2- I have seen sheet musics that have notes in both treble and bass clefs and also chord symbols above the treble clef. Are those only for bands? Cause you can't play a chord when you are using your both hands.
thanks
Comment: I've asked the keyboard guy to move it up an octave because his left hand was frequency-blocking me.
Comment: @DaveJacoby that is a convenient option and I think it is good to listen to what sounds best. The guy could also move it up more than an octave by using chord translations. The piano player should not in any case play very low notes in a band because the bassist and guitarist take care of those (like you said).
Answer:
If you're playing the chords with the right hand and your left hand is playing the bass line, you have a couple options. The book suggests that you sing to it, but somebody else can play the melody using another piano, sing, or even play it on instruments like the harmonica, violin, or saxophone, which can closely mimic the human voice.
Piano sheet music with chords on top can be used when the piano is accompanied by a guitar or another piano. Lazy musicians like me use the chords when learning a song quickly because chords are easier to play instantly than proper music. They can also be used in improvisation at more advanced levels because they give you an idea of what the music sounds like so that you can invent a melody line that goes with it.

Also, usually the left hand in a song plays music that resembles chords in some way (either through split chords, arpeggios, thirds, etc) so the actual chord names are just extras.
Answer: re 1)
I think what the text might mean is ..
If the melody is the sung melody, you probably don't want to play it while you're singing it. You'd just be playing over your own singing. Normally this doesn't work too well.
Answer: In fact it is possible to play chords with both hands and a melody at the same time. The trick is to play the melody as the brightest tone, and add one or two chord tones below it in the right hand. The left hand can play the entire chord or just the bas tone (maybe doubled in two octaves). - It is a bit tricky to teach the brain to automatically add chord tones to the melody, but it's worth the effort!
Comment: This should also be an accepted answer. This is how I play contemporary music or improvise on the piano.
Answer: If your local TV system has the "Play Piano in a Flash" infomercials, that sounds like it's right where you are developmentally.  I'm not suggesting you buy the course, just that you watch the show.  You can see a lot just by observing.  Learning to play from lead sheets/fake books, which is what you're looking at, is of enormous benefit and very enjoyable.  I'm talking fun!  In spite of all the mistakes you'll make. :)

Question about playing chords


Is it possible to hook_form_alter by path?

Question: I have a basic hook_form_alter working but the issue is I cannot do it by form id as the id might be different in various environments, i.e. local, dev, production. So the usual method of altering by targeting a form ID is not ideal then.
I figured I could do this by path (as that won't change) but none of the usual methods work. I'd like to keep this in code so that's why I'm not simply changing the UI for this setting.
Here's my basic alter which works:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['submitted']['donation']['amount']['#title'] = t('My new title');
}

However, if I do this, it does not work:
function MYMODULE_form_alter(&$form, &$form_state, $form_id, $host) {
  $host = $_SERVER['HTTP_HOST'];
  if ($host == "m.local.dev/donate" or  $host == "m.live.com/donate") {
  $form['submitted']['donation']['amount']['#title'] = t('My new title');
   }
}

I'm guessing what I'm trying to do is not even possible and therefore I'll try to figure out a different method.
Comment: I would check to make sure what `$host` is being set to as this approach does work...
Answer: I think you should use  $_SERVER['HTTP_HOST'] . request_uri();
This will give you the complete path.
So your code should be
function MYMODULE_form_alter(&$form, &$form_state, $form_id, $host) {
  $host = $_SERVER['HTTP_HOST'] . request_uri();
  if ($host == "m.local.dev/donate" or  $host == "m.live.com/donate") {
  $form['submitted']['donation']['amount']['#title'] = t('My new title');
   }
}


Alternância de logotipo automaticamente com Fade

Question: Gostaria de adicionar em meu site HTML, um efeito de mudança de cor do logotipo com fade, seja javascript ou jquery.
Por exemplo:
Mudar de:

Para:

Dentre outras imagens, somando todas: 10 img's.
Com efeito Fade e automaticamente, sem que seja aparente algum tipo de slide ou código, ficando como logotipo normal. Alguém pode me ajudar?
HTML:

Answer: A resposta é simples cara: "Use apenas CSS".
CSS3 te permite fazer animações com transições do jeito que você quiser!
Deixe o jQuery só para aplicações que não se pode fazer com CSS3!

.slider {
  max-width: 300px;
  height: 200px;
  margin: 20px auto;
  position: relative;
}
.slide1,.slide2,.slide3,.slide4,.slide5 {
  position: absolute;
  width: 100%;
  height: 100%;
}
.slide1 {
  background: url(http://media.dunkedcdn.com/assets/prod/40946/580x0-9_cropped_1371566801_p17tbs0rrjqdt1u4dnk94fe4b63.jpg)no-repeat center;
      background-size: cover;
    animation:fade 8s infinite;
-webkit-animation:fade 8s infinite;

}
.slide2 {
  background: url(http://media.dunkedcdn.com/assets/prod/40946/580x0-9_cropped_1371565525_p17tbqpu0d69c21hetd77dh483.jpeg)no-repeat center;
      background-size: cover;
    animation:fade2 8s infinite;
-webkit-animation:fade2 8s infinite;
}
.slide3 {
    background: url(http://media.dunkedcdn.com/assets/prod/40946/580x0-9_cropped_1371564896_p17tbq6n86jdo3ishhta3fv1i3.jpg)no-repeat center;
      background-size: cover;
    animation:fade3 8s infinite;
-webkit-animation:fade3 8s infinite;
}
@keyframes fade
{
  0%   {opacity:1}
  33.333% { opacity: 0}
  66.666% { opacity: 0}
  100% { opacity: 1}
}
@keyframes fade2
{
  0%   {opacity:0}
  33.333% { opacity: 1}
  66.666% { opacity: 0 }
  100% { opacity: 0}
}
@keyframes fade3
{
  0%   {opacity:0}
  33.333% { opacity: 0}
  66.666% { opacity: 1}
  100% { opacity: 0}
}

http://codepen.io/davidhc/pen/nLpJk
Comment: http://codepen.io/anon/pen/RWNOwp
Comment: Eu enfrentei problemas ao tentar alinhar a imagem no site, pode me ajudar? Ficou assim:
 http://i.stack.imgur.com/2l9bO.png
Comment: Os arquivos:

CSS:
http://core-webhosting.com.br/downloads/style.css

HTML:
http://core-webhosting.com.br/downloads/index.txt
Comment: Esse CSS3 não alinhou bem o logotipo na página! Alguém pra ajudar?


pumpEvents errors cardLayout Java

Question: I haven't completely finished the code, but I am having issues after creating the GUI with making the cardLayout be able to switch from one panel to the next. What I am wanting to happen is you can click the "Add" button and you can add all of the information for one student, and have it display on the displayAll panel (haven't written that code yet). However I am getting many errors, and don't know why.
    import javax.swing.*;

    import java.awt.*;
    import java.util.ArrayList;
    import java.util.Scanner;
    import java.awt.event.*;

    public class Lab12 extends JFrame{
private static final long serialVersionUID = 1L;
Scanner input = new Scanner(System.in);

private JButton add;
private JButton remove;
private JButton sort;
private JButton enterAdd;
private JButton enterRemove;
private JButton enterSort;

public String FirstName;
public String LastName;
public String Major;
public String GPA;
public String UIN;
public String NetID;
public String Age;
public String Gender;

private JLabel FNameLbl;
private JLabel LNameLbl;
private JLabel MajorLbl;
private JLabel GPALbl;
private JLabel UINLbl;
private JLabel NetIDLbl;
private JLabel AgeLbl;
private JLabel GenderLbl;

private JTextField FNameTxt;
private JTextField LNameTxt;
private JTextField MajorTxt;
private JTextField GPATxt;
private JTextField UINTxt;
private JTextField NetIDTxt;
private JTextField AgeTxt;
private JComboBox GenderCmbo;

private JRadioButton Student1;
private JRadioButton Student2;
private JRadioButton Student3;
private JRadioButton Student4;
private JRadioButton Student5;
private JRadioButton Student6;
private JRadioButton Student7;
private JRadioButton Student8;
private JRadioButton Student9;
private JRadioButton Student10;

private JRadioButton FNameRB;
private JRadioButton LNameRB;
private JRadioButton MajorRB;
private JRadioButton GPARB;
private JRadioButton UINRB;
private JRadioButton NetIDRB;
private JRadioButton AgeRB;
private JRadioButton GenderRB;

@SuppressWarnings("rawtypes")
static DefaultListModel listStudents;
private static JList<String>list;

private JPanel combo;
private JPanel selection;
private JPanel addInfo;
private JPanel removeInfo;
private JPanel sortInfo;
private JPanel displayAll;
private JPanel placeHolder;

public static ArrayList <Student> students;

public Lab12(){
    FirstName = " ";
    LastName = " ";
    Major = " ";
    GPA = " ";
    UIN = " ";
    NetID = " ";
    Age = " ";
    Gender = " ";

    String Add = "Add";
    String Remove = "Remove";
    String Sort = "Sort";
    String Display = "Display";
    final ArrayList <Student> students = new ArrayList<Student>(10);

    add = new JButton("Add");
    remove = new JButton("Remove");
    sort = new JButton("Sort");
    enterAdd = new JButton("Enter");
    enterRemove = new JButton("Enter");
    enterSort = new JButton("Enter");

    FNameLbl = new JLabel("First Name: ");
    LNameLbl = new JLabel("Last Name: ");
    MajorLbl = new JLabel("Major: ");
    GPALbl = new JLabel("GPA: ");
    UINLbl = new JLabel("UIN: ");
    NetIDLbl = new JLabel("NetID: ");
    AgeLbl = new JLabel("Age: ");
    GenderLbl = new JLabel("Gender: ");

    FNameTxt = new JTextField();
    LNameTxt = new JTextField();
    MajorTxt = new JTextField();
    GPATxt = new JTextField();
    UINTxt = new JTextField();
    NetIDTxt = new JTextField();
    AgeTxt = new JTextField();
    GenderCmbo = new JComboBox(new String[]{"Male", "Female"});

    Student1 = new JRadioButton();
    Student2 = new JRadioButton();
    Student3 = new JRadioButton();
    Student4 = new JRadioButton();
    Student5 = new JRadioButton();
    Student6 = new JRadioButton();
    Student7 = new JRadioButton();
    Student8 = new JRadioButton();
    Student9 = new JRadioButton();
    Student10 = new JRadioButton();

    FNameRB = new JRadioButton("First Name");
    LNameRB = new JRadioButton("Last Name");
    MajorRB = new JRadioButton("Major");
    GPARB = new JRadioButton("GPA");
    UINRB = new JRadioButton("UIN");
    NetIDRB = new JRadioButton("NetID");
    AgeRB = new JRadioButton("Age");
    GenderRB = new JRadioButton("Gender");

    listStudents = new DefaultListModel();
    list = new JList(listStudents);

    combo = new JPanel(new CardLayout());
    selection = new JPanel();
    addInfo = new JPanel();
    removeInfo = new JPanel();
    sortInfo = new JPanel();
    displayAll = new JPanel();
    placeHolder = new JPanel();

    //create panel for displaying all students- should stay on screen
    displayAll.setLayout(new FlowLayout());
    displayAll.add(list);

    //create panel for adding info for a student
    addInfo.setLayout(new GridLayout(9,2,5,5));
    addInfo.add(FNameLbl);
    addInfo.add(LNameLbl);
    addInfo.add(MajorLbl);
    addInfo.add(GPALbl);
    addInfo.add(UINLbl);
    addInfo.add(NetIDLbl);
    addInfo.add(AgeLbl);
    addInfo.add(GenderLbl);
    addInfo.add(FNameTxt);
    addInfo.add(LNameTxt);
    addInfo.add(MajorTxt);
    addInfo.add(GPATxt);
    addInfo.add(UINTxt);
    addInfo.add(NetIDTxt);
    addInfo.add(AgeTxt);
    addInfo.add(GenderCmbo);
    addInfo.add(enterAdd);

    //create panel for selecting the student to remove
    removeInfo.setLayout(new GridLayout(9,1,5,5));
    removeInfo.add(Student1);
    removeInfo.add(Student2);
    removeInfo.add(Student3);
    removeInfo.add(Student4);
    removeInfo.add(Student5);
    removeInfo.add(Student6);
    removeInfo.add(Student7);
    removeInfo.add(Student8);
    removeInfo.add(Student9);
    removeInfo.add(Student10);
    removeInfo.add(enterRemove);

    //create panel for selecting which property to sort
    sortInfo.setLayout(new GridLayout(9,1,5,5));
    sortInfo.add(FNameRB);
    sortInfo.add(LNameRB);
    sortInfo.add(MajorRB);
    sortInfo.add(GPARB);
    sortInfo.add(UINRB);
    sortInfo.add(NetIDRB);
    sortInfo.add(AgeRB);
    sortInfo.add(GenderRB);
    sortInfo.add(enterSort);

    //create panel for the cardLayout
    combo.add(displayAll, Display);
    combo.add(addInfo, Add);
    combo.add(removeInfo, Remove);
    combo.add(sortInfo, Sort);

    //create permanent panel for the buttons
    selection.setLayout(new GridLayout(3,1,5,5));
    selection.add(add);
    selection.add(remove);
    selection.add(sort);

    //combine the selection and the shifting combo panel to one panel to add to the whole screen
    placeHolder.setLayout(new FlowLayout());
    placeHolder.add(selection);
    placeHolder.add(combo);

    //add to the main screen
    add(placeHolder);

    //add all event handling below

    //gives action to "add"
     add.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                CardLayout combo = (CardLayout) addInfo.getLayout();
                combo.show(addInfo, "add");
            }
        }
        );

    //this obtains all info for each student
     enterAdd.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                FirstName = FNameTxt.getText();
                LastName = LNameTxt.getText();
                Major = MajorTxt.getText();
                GPA = GPATxt.getText();
                UIN = UINTxt.getText();
                NetID = NetIDTxt.getText();
                Age = AgeTxt.getText();
                Gender = (String) GenderCmbo.getSelectedItem();

                students.add(new Student (FirstName, LastName, Major, GPA, UIN, NetID, Age, Gender));
                (listStudents).addElement(students.get(students.lastIndexOf(students)));
            }
        }
        );

}

public static void display(ArrayList<Student> students){
    for (int n = 0; n < 10; n++) {
        Student Student = students.get(n);
        System.out.println(n + ": " + ((Student)students.get(n)).getFName() + ", " + ((Student)students.get(n)).getLName() + ", " + ((Student)students.get(n)).getMajor() + ", " + ((Student)students.get(n)).getGPA() + ", " + ((Student)students.get(n)).getUIN() + ", " + ((Student)students.get(n)).getNetID() + ", " + ((Student)students.get(n)).getAge() + ", " + ((Student)students.get(n)).getGender());
    }
    System.out.println("");
}
@SuppressWarnings("unchecked")
public static void populateJList(ArrayList<Student> students){
    for(int n = 0; n < 10; n++){
    (listStudents).addElement(students.get(n));
    }
}

public static void main(String[] args) {
    Lab12 frame = new Lab12();
    frame.setTitle("Student Database");
    frame.setSize(700,700);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

    }

The errors I am getting are:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.awt.GridLayout cannot be cast to java.awt.CardLayout
at Lab12$1.actionPerformed(Lab12.java:228)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

I was trying to use these as guides:
http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html
Changing Panels using the Card layout
Any help would be appreciated. The errors don't have any lines, so I have no idea where to start. Thank you!
Comment: *"The errors don't have any lines"*  Sure they do `..at Lab12$1.actionPerformed(Lab12.java:228)`  For better help sooner, post an [SSCCE](http://sscce.org/).  (Compile often, and ask us about the 20 lines of code with the one compilation error, rather that the 200+ LOC with multiple errors).
Answer: OK, I slogged through your code, and I see this:
addInfo.setLayout(new GridLayout(9, 2, 5, 5));

And then this:
CardLayout combo = (CardLayout) addInfo.getLayout();

You're casting the JPanel's layout to one that it's not using.
So this error is self explanatory:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.awt.GridLayout cannot be cast to java.awt.CardLayout

Solution: don't do this! Don't cast an object (here the GridLayout) to something it's not (here CardLayout). If you want a component to use a CardLayout, first you must add a CardLayout to a container.
A lesson from all of this: read the exception message critically as it will often tell you exactly what you're doing wrong. It certainly does in your case.
Comment: Thank you Hovercraft for your response. I suppose I was trying to follow someone else's example without realizing exactly what I was doing. I went back and made a separate panel to put each of the panels I wanted to add to the cardLayout and added the cardLayout in the parenthesis:
Comment: p1Add = new JPanel(new CardLayout());
Comment: Then I changed combo.add(P1Add, Add);
Comment: and I changed CardLayout combo = (CardLayout) p1Add.getLayout();
Comment: I still haven't gotten it to show up, but all of the errors are gone. Thanks for the help!
Comment: @user2758501: you haven't read the CardLayout tutorial yet. Please do so without delay.

pumpEvents errors cardLayout Java


Paginação com grande quantidade de dados

Question: Pensando em desempenho, qual a melhor maneira de paginar uma grande quantidade de dados?
Atualmente estou usando um List<Produtos>, guardando em torno de 500 produtos nela, e utilizando subList(min,max), retorna o que preciso. Porem, creio que essa não sejá a melhor solução e gostaria de saber outras alternativas para esse problema.
Edit
A ideia é maximizar o desempenho entre consultas desnecessarias no banco, pois o pool maximo do banco é 4.
Comment: Você pode utilizar o `setFirstResult` e `setMaxResults`. http://www.baeldung.com/jpa-pagination
Comment: @Matheus vou formular uma resposta e posto mais tarde, vai demorar um pouco
Comment: Você usa hibernate? Ou os dados não estão em um bd?
Comment: Sim, estou usando hibernate.
Comment: A lista de objetos é resultado de algum filtro? Ex:  usuário só quer produtos femininos. Você está usando SQL nativo ou HQL?
Comment: Não, é resultado de um SQL em uma tabela, no caso select *.
Comment: @adelmo00 Na primeira tela não, apenas um where buscando por empresa. Posteriormente caso o cliente clique, é realizado um filtro.
Comment: Dê mais contexto, o que você está fazendo exatamente? algo como estar buscando 500 produtos mas sempre exibe apenas 50 deles na página? se seu banco tiver mais que 500 produtos o seu código já falha porque não consegue exibir os >=501?
Comment: @BrunoRB Por se tratar de uma paginação, obviamente não será exibidos todos ao mesmo tempo.
Answer: Tive esse problema, resolvi com a dica da algaworks:
public List<Produto> filtrados(FiltroProduto filtro) {
    Criteria criteria = criarCriteriaParaFiltro(filtro);

    criteria.setFirstResult(filtro.getPrimeiroRegistro());
    criteria.setMaxResults(filtro.getQuantidadeRegistros());

    if (filtro.isAscendente() && filtro.getPropriedadeOrdenacao() != null) {
        criteria.addOrder(Order.asc(filtro.getPropriedadeOrdenacao()));
    } else if (filtro.getPropriedadeOrdenacao() != null) {
        criteria.addOrder(Order.desc(filtro.getPropriedadeOrdenacao()));
    }

    return criteria.list();
}

É claro que pode-se melhorar o filtro.
https://github.com/algaworks/aula-datatable-lazy-loading-primefaces
Comment: @Matheus O que seria mais vantajoso, fazer uma consulta de 80000 itens e armazenar em uma lista ou implementar a paginação direto na query? Imagine todos esses itens sendo armazenados em um array, e agora imagine uma consulta que sempre retorna a quantidade de itens que você precisa. Ex: 20 a 20.
Comment: @Matheus então é isso que tu tem que analisar, a primeira carga da lista sempre irá demorar um tempo a mais e também creio que vai exigir um pouco mais da `VM`. Se você fizer a paginação direto no banco vc poupa um pouco de memória e também ganha performance na primeira consulta. Eu necessariamente faria paginação direto no banco, pois dessa forma eu não precisaria fazer uma carga "inútil" pois só mostraria o necessário para o cliente
Comment: @Matheus O ponto não é o *Criteria* mas sim o fato de setar a query para retornar apenas uma certa quantidade de registros, a partir de uma certa linha (*firstResult* e *maxResults*). A resposta usa *Criteria* porque ela tinha que usar algum método (você não mostrou seu código, qual técnica de consulta está usando, então qualquer técnica de acesso a dados deve servir). Se você precisa de uma resposta mais próxima do seu código atual, mostre o seu código atual e dê mais detalhes da sua implementação.
Comment: Tiago, o que me traz em desempenho usar criteria ao invés de carregar todos os produtos em uma lista? Essa é a questão. Como fazer uma paginação já foi respondido em outros comentarios.
Comment: @DiegoAugusto Não sei oq seria melhor, 20 clientes acessando um array que já tem os produtos carregados, ou os 20 clientes consultando o banco toda hora, sendo que apenas 4 cliente podem acessar o banco p/vez.
Comment: @Matheus ai você que terá que analisar, quantas vezes vc irá carregar esse array?
Qual o volume de dados?
Comment: @DiegoAugusto Atualmente eu carrego esse array quando o primeiro cliente acessa a home do sistema. Outros clientes apenas consultam o array já carregado em uma forma de cache. O que eu não entendi é se a melhor forma é carregar tudo ou cada cliente buscar no banco a pagina que precisa, supondo que cada pagina contem 20 produtos.
Comment: Tá entendi, e depois que esse primeiro cliente entra na home os dados do banco não são modificados, ou seja, não tem nenhuma inclusão?
Comment: @DiegoAugusto Não, a inclusão de novos produtos é gerenciado de outra forma, onde quando é atualizado a base, é bloqueado o acesso ao sistema. Então enquando o sistema ta liberado, os produtos não são modificados.
Comment: @DiegoAugusto Ok, Obrigado pelas responstas.
Comment: @Matheus Por nada, boa sorte :)
Comment: @Matheus a edição foi rejeitada, pois a edição não pode acrescentar nada na resposta, que o autor não tenha adicionando anteriormente.


Mask Moeda Input readonly

Question: Gostaria de saber como posso estar colocando máscara de moeda, ja que meu input="campoResultado" é bloqueado e adicionado valor automaticamente após colocado um valor no input acima.
Tentei adicionar a mascara no próprio input="campoResultado", mas sem sucesso.
Obrigado!
<!DOCTYPE html>

    <title>Título da página</title>
    <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
        <link href="https://fonts.googleapis.com/css?family=Titillium+Web" rel="stylesheet">

Número de corridas por dia <input class="w3-input w3-border" type="number" name="ncorridas" id="ncorridas" min="0" onChange="troca(this.value)" />

    Valor:<input readonly="true" class="w3-input w3-border" type="text" name="campoResultado" id="campoResultado" />

Answer: Convertendo números para moeda sem framework
1 - Solução aproveitando seu script
Com apenas mais 3 linhas de javascript puro na sua função se obtém o resultado esperado.

function troca(valor){
var campo1 = document.getElementById("ncorridas").value;
var resultado = parseFloat(campo1);
//formata para duas casas decimais utilizando notação de ponto fixo
resultado = (resultado*5400).toFixed(2);
//substitui separador decimal ponto por virgula
resultado=resultado.replace(".", ",");
//a regex abaixo coloca um ponto a esquerda de cada grupo de 3 digitos desde que não seja no inicio do numero
resultado = resultado.replace(/\B(?=(\d{3})+(?!\d))/g, ".");

document.getElementById('campoResultado').value = ('R$ ') + resultado + (' por ano!');
}
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link href="https://fonts.googleapis.com/css?family=Titillium+Web" rel="stylesheet">
Número de corridas por dia <input class="w3-input w3-border" type="number" name="ncorridas" id="ncorridas" min="0" onChange="troca(this.value)" />

    Valor:<input readonly="true" class="w3-input w3-border" type="text" name="campoResultado" id="campoResultado" />

2 - Para navegadores modernos utilize toLocaleString() - Converte um número em uma cadeia de caracteres usando a localidade atual ou especificada.
Para formatar o valor em Moeda configure .toLocaleString() com minimumFractionDigits e maximumFractionDigits

minimumFractionDigits - exibe a parte fracionária com quantidade mínima de dígitos.
maximumFractionDigits - exibe a parte fracionária com quantidade máxima de dígitos.

const [corridas, Valor] = [...document.querySelectorAll('input.w3-border')];

       function formatar$(moeda) {
          return moeda.toLocaleString('pt-BR',{style: 'currency', currency: 'BRL'}, {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2
          });
       }

       corridas.addEventListener('keyup', function() {
         const moeda = Number(this.value);
         const _Valor = moeda * 5400;
         Valor.value = formatar$(_Valor) + ' por ano';
       });

    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <link href="https://fonts.googleapis.com/css?family=Titillium+Web" rel="stylesheet">

    Número de corridas por dia <input class="w3-input w3-border" type="number" name="ncorridas" id="ncorridas" min="0"/>

    Valor:<input readonly="true" class="w3-input w3-border" type="text" name="campoResultado" id="campoResultado" />

Retirei a palavra reais do resultado porque já consta o simbolo R$, mas isso fica a seu critério!

Mask Moeda Input readonly


new to android - how to display text than picture in rows

Question: I would like to display all the pictures taken by a camera and arrange them by date. So, I would like the screen to look something like this:
2011
picture1 picture2 picture3
2012
picture1 picture2 picture3
2013
picture1 picture2 picture3
I tried to look through some tutorials, but could not find anything...
Comment: Can I "slap some code down"? No. But now you have somewhere to start. Look up a tutorial and repost when you have a more specific question
Comment: [ListView](http://developer.android.com/reference/android/widget/ListView.html)
Comment: cuz im new, can you slap some code down :)
Answer: You can use ListView with a custom layout. Here's a tutorial.


Como executar uma query com grande volume de dados?

Question: Existe alguma forma de executar um arquivo com um grande volume de dados sem ser direto no SQL Server 2014 Management Studio, pois tento abrir para executar e obtenho o seguinte erro:

Não é possível executar o script. Memória insuficiente para continuar
  a execução do programa. (mscorlib)

Local do Programa:

   em System.Runtime.InteropServices.Marshal.AllocCoTaskMem(Int32 cb)
   em Microsoft.SqlServer.Management.UI.VSIntegration.ShellTextBuffer.GetText(Int32 startPosition, Int32 chars)
   em Microsoft.SqlServer.Management.UI.VSIntegration.ShellTextBuffer.get_Text()
   em Microsoft.SqlServer.Management.UI.VSIntegration.ShellCodeWindowControl.GetSelectedTextSpan()
   em Microsoft.SqlServer.Management.UI.VSIntegration.Editors.ScriptEditorControl.GetSelectedTextSpan()
   em Microsoft.SqlServer.Management.UI.VSIntegration.Editors.ScriptAndResultsEditorControl.OnExecScript(Object sender, EventArgs a)

Answer: Para estes casos, o jeito é usar o prompt de comando ou o Powershell e executar o script usando:
> sqlcmd -S COMPUTADOR\INSTANCIA -i .\MeuScript.sql -d MeuDatabase

Normalmente executo assim:
> sqlcmd -S .\SQLEXPRESS -i .\MeuScript.sql -d MeuDatabase

Leia mais sobre o sqlcmd aqui.
Comment: No meu caso vou roda no servidor, o script tem que ser executado direto do servido ou pode ser de outra maquina ?
Comment: Pode ser de outra máquina. Você só precisa ter acesso a ela.
Comment: É uma resposta bem valida, mas como não tenho acesso, tive que transformar em um arquivo Excel e importar com o assistente do Server 2014 Management Studio....
Comment: Ah, sim. Funciona também.