Find the exact value of $\int_{0}^{2}x[\frac{1}{x}]dx$.

Question: Find the exact value of $\int_{0}^{2}x\left[\frac{1}{x}\right]dx$.
Let $[x]$ denote $\lceil{x-\frac{1}{2}}\rceil$.
Using Desmos, I got $2.46736022133$ and WolframAlpha does not give me a solution. My intuition tells me that it might be possible to find an exact value using Trapezoidal Reimann Sums but I am not really sure how to go about doing it. After my attempt, I got stuck but I was at a point where I could plug it into WolframAlpha and it gave me $\frac{\pi^2}{4}$. Why did it come out so nicely?
My attempt:
Where $A_n$ denotes the area of the $nth$ trapezoid from the right:
$$A=\frac{h}{2}(a+b)$$
$$A_n=\frac{\frac{2}{2n-1}-\frac{2}{2n+1}}{2}(\frac{2n}{2n-1}+\frac{2n}{2n+1})$$
$$A_n=\frac{\frac{4n+2}{4n^{2}-1}-\frac{4n-2}{4n^{2}-1}}{2}\left(\frac{4n^{2}+2n}{4n^{2}-1}+\frac{4n^{2}-2n}{4n^{2}-1}\right)$$
$$A_n=\frac{2}{4n^{2}-1}\left(\frac{8n^{2}}{4n^{2}-1}\right)$$
$$A_n=\frac{16n^{2}}{\left(4n^{2}-1\right)^{2}}$$
Then:
$$\int_{0}^{2}x\left[\frac{1}{x}\right]dx=\sum_{n=1}^{\infty}A_n=\sum_{n=1}^{\infty}\frac{16n^{2}}{\left(4n^{2}-1\right)^{2}}$$
I do not know how to solve this infinite summation so I plugged it into WolframAlpha and it gave me $\frac{\pi^2}{4}$. How did it get to this conclusion? Is there a more efficient way to solve this?
Comment: See https://math.stackexchange.com/q/636137/42969 or https://math.stackexchange.com/q/810398/42969
Comment: What is the definition $[\cdot ]$? You say "standard rounding function" but there exists for example floor $\lfloor \cdot \rfloor$ and $\lceil\cdot \rceil$ functions that and both round (one down and one up).
Comment: @A.P. based on the Desmos link it seems to be "round to nearest".
Comment: WA's definition of `round` seems to be$$\left[\frac1x\right]:=\left\lceil\frac1x-\frac12\right\rceil=\left\lfloor\frac1x+\frac12\right\rfloor$$
Comment: There is no standard definition for the rounding function. Particularly because there's no natural choice to round the number of the form $n + \frac{1}{2}$. You'll find different definitions in various sources.
Comment: Assuming your calculation is right so far, telescope with$$\frac{16n^2}{(4n^2-1)^2}-\frac{2}{(2n+1)^2}=a_n-a_{n+1},\,a_n:=\frac{2n}{(2n-1)^2},$$then use $\sum_{n=1}\frac{1}{(2n+1)^2}=\frac{\pi^2}{8}-1$.
Comment: [Wolfram Alpha knows](https://www.wolframalpha.com/input?i=approximate+integral+x+round%281%2Fx%29%2C+x%3D+0+..+2) how to approximate the integral
Answer: Continuing where you left off. Note
\begin{align*}
&\sum_{n=1}^\infty\frac{16n^2}{4n^2-1} \\
&= 2\sum_{n=1}^\infty n\left(\frac{1}{(2n-1)^2} - \frac{1}{(2n+1)^2}\right)\\
&= 2\sum_{n=1}^\infty \left(\sum_{k=1}^n 1\right) \left(\frac{1}{(2n-1)^2} - \frac{1}{(2n+1)^2}\right)\\
&= 2\sum_{n=1}^\infty \sum_{k=1}^n \left(\frac{1}{(2n-1)^2} - \frac{1}{(2n+1)^2}\right)\\
&= 2\sum_{k=1}^\infty \sum_{n=k}^\infty \left(\frac{1}{(2n-1)^2} - \frac{1}{(2n+1)^2}\right)\\
&= 2\sum_{k=1}^\infty \sum_{n=k}^\infty \left(\frac{1}{(2n-1)^2}\right) - \sum_{n=k+1}^\infty\left(\frac{1}{(2n-1)^2}\right)\\
&= 2\sum_{k=1}^\infty \frac{1}{(2k-1)^2} \\
&= 2\left(\sum_{k=1}^\infty \frac{1}{k^2} - \sum_{k=1}^\infty \frac{1}{(2k)^2}\right) \\
&= 2\cdot\frac{3}{4}\sum_{k=1}^\infty\frac{1}{k^2} \\
&= 2\cdot\frac{3}{4}\cdot\frac{\pi^2}{6} = \frac{\pi^2}{4}
\end{align*}
Comment: Between lines 4-5, I use a similar trick to switching the order of integration for iterated integrals. Between 5-7, it's the telescoping series stuff. For line 7, I note that it's the sum of reciporals of squares of odd naturals, so it's the sum of recip square all naturals minus recip square even naturals
Answer:
If $[x]:=n$ iff $n-\tfrac12< x\leq n+\tfrac12$ (i.e. $[x]=\lceil x-\tfrac12\rceil$, which seems to be what the OP had in mind), then
\begin{align}
\int^2_0  x[1/x]\,dx & =\sum^\infty_{n=1}\int_{[\tfrac{2}{2n+1},\tfrac2{2n-1})}nx\,dx\\
&=\sum^\infty_{n=1}\Big(\frac{2n-1+1}{(2n-1)^2}-\frac{2n+1-1}{(2n+1)^2}\Big)\\
&=\sum^\infty_{n=1}\Big(\frac{1}{2n-1}-\frac{1}{2n+1}+\frac{1}{(2n-1)^2}+\frac{1}{(2n+1)^2}\Big)\\
&=1+2\sum^\infty_{n=1}\frac{1}{(2n-1)^2}-1=2\Big(\sum^\infty_{n=1}\frac{1}{n^2}-\frac14\sum^\infty_{n=1}\frac1{n^2}\Big)\\
&=\frac{\pi^2}{4}
\end{align}

The same estimate holds when $[x]:=n$ iff $n-\tfrac12 \leq x<n+\tfrac12$ (i.e., $[x]=\lfloor x+\tfrac12\rfloor$) since $\lceil x-\tfrac12\rceil=\lfloor x+\tfrac12\rfloor$ a.s.

If by $[\cdot]$ the OP means the ceiling function $\lceil x\rceil=n$ where $n-1<x\leq n$, then
$$\int^2_0 x\lceil 1/x \rceil\,dx=\int^1_0  x\lceil 1/x \rceil\,dx +\int^2_1 x\,dx=\int^1_0 x\lceil 1/x\rceil \,dx + \frac32$$
From
\begin{align}
\int^1_0  x\lceil 1/x \rceil\,dx & =\sum^\infty_{n=2}\int_{[\tfrac{1}{n},\tfrac1{n-1})}nx\,dx=\sum^\infty_{n=2}\frac{n}{2}\Big(\frac{1}{(n-1)^2}-\frac{1}{n^2}\Big)\\
&=\sum^\infty_{n=2}\frac{2n-1}{2n(n-1)^2}=\sum^\infty_{n=2}\frac{1}{(n-1)^2}+\frac{n-1-n}{2n(n-1)^2}\\
&=\frac12\sum^\infty_{n=1}\frac{1}{n^2}+\frac12\sum^\infty_{n=2}\frac{1}{n(n-1)} =\frac{\pi^2}{12}+\frac12
\end{align}
The value of the integral in this case is  $\frac{\pi^2}{12}+2\approx 2.822467$

If the OP means $[\cdot]$ to be the integer part function (floor function) $\lfloor x\rfloor =n$ iff $n\leq x<n+1$, then
$$\int^2_0 x\lfloor 1/x \lfloor\,dx=\int^1_0  x\lfloor 1/x \rfloor\,dx +\int^2_1 0\cdot x\,dx=\int^1_0 x\lfloor 1/x\rfloor \,dx $$
The value of the integral is then given by
\begin{align}
\int^1_0  x\lfloor 1/x \rfloor\,dx & =\sum^\infty_{n=1}\int_{(\tfrac{1}{n+1},\tfrac1n]}nx\,dx=\sum^\infty_{n=1}\frac{n}{2}\Big(\frac{1}{n^2}-\frac{1}{(n+1)^2}\Big)\\
&=\sum^\infty_{n=1}\frac{2n+1}{2n(n+1)^2}=\sum^\infty_{n=1}\frac{1}{(n+1)^2}+\frac{n+1-n}{2n(n+1)^2}\\
&=\frac12\sum^\infty_{n=2}\frac{1}{n^2}-\frac12\sum^\infty_{n=1}\frac{1}{n(n+1)} =\frac{\pi^2}{12}
\end{align}
Answer: An alternate solution:
$$
\begin{align}
\int_{0}^{2}x\operatorname{round}\left(\frac{1}{x}\right)dx &= \int_0^2 x\Biggl\lfloor{\frac{1}{x}+\frac{1}{2}\Biggr\rfloor}dx \tag{1}\\
&= 8\int_{1}^{\infty}\frac{\lfloor{x\rfloor}}{\left(2x-1\right)^{3}}dx \tag{2}\\
&= 8\sum_{n=1}^{\infty}n\int_{n}^{n+1}\frac{dx}{\left(2x-1\right)^{3}} \\
&= 16\sum_{n=1}^{\infty}\frac{n^{2}}{\left(1-4n^{2}\right)^{2}} \\
\end{align}
$$
where in $(1)$ we used the Desmos interpretation $\displaystyle \operatorname{round}\left(\frac{1}{x}\right) := \Biggl\lfloor{\frac{1}{x}+\frac{1}{2}\Biggr\rfloor}$ and in $(2)$ we used the mapping $\displaystyle \frac{1}{x}+\frac{1}{2} \mapsto x$.
Next, let $f$ be a piecewise smooth function on $[0,L]$. Then the Fourier sine expansion is given by
$$f\left(x\right)\ =\ \sum_{n=1}^{\infty}b_{n}\sin\left(\frac{\pi nx}{L}\right)$$
where we have the sequence
$$b_{n}=\frac{2}{L}\int_{0}^{L}f\left(x\right)\sin\left(\frac{\pi nx}{L}\right)dx.$$
Let $f(x) = \cos(x)$ and $L = \dfrac{\pi}{2}$. Then using some basic integration, we can prove that
$$b_{n}=\frac{4}{\pi}\int_{0}^{\frac{\pi}{2}}\cos\left(x\right)\sin\left(2nx\right)dx\ =\ \frac{4}{\pi}\cdot\frac{2n}{4n^{2}-1}.$$
This means
$$
\begin{align}
\cos\left(x\right) &= \frac{4}{\pi}\sum_{n=1}^{\infty}\frac{2n}{4n^{2}-1}\sin\left(2nx\right) \\
\implies \cos^2(x) &=  \frac{8}{\pi}\sum_{n=1}^{\infty}\frac{n\cos\left(x\right)\sin\left(2nx\right)}{4n^{2}-1} \\
\implies \int_{0}^{\frac{\pi}{2}}\cos^{2}\left(x\right)dx &= \frac{8}{\pi}\sum_{n=1}^{\infty}\frac{n}{4n^{2}-1}\int_{0}^{\frac{\pi}{2}}\cos\left(x\right)\sin\left(2nx\right)dx \\
&= \frac{8}{\pi}\sum_{n=1}^{\infty}\frac{n}{4n^{2}-1}\cdot\frac{2n}{4n^{2}-1}. \\
&= \frac{16}{\pi}\sum_{n=1}^{\infty}\frac{n^{2}}{\left(4n^{2}-1\right)^{2}} \\
\end{align}
$$
But $\displaystyle \int_{0}^{\frac{\pi}{2}}\cos^{2}\left(x\right)dx=\frac{\pi}{4}$. By transitivity, we get
$$\frac{\pi}{4}=\frac{16}{\pi}\sum_{n=1}^{\infty}\frac{n^{2}}{\left(4n^{2}-1\right)^{2}}.$$
Therefore,
$$\int_{0}^{2}x\operatorname{round}\left(\frac{1}{x}\right)dx = \frac{\pi^{2}}{4}.$$
Answer: $$\frac{16 n^2}{\left(4 n^2-1\right)^2}=-\frac{1}{2 n+1}+\frac{1}{(2 n+1)^2}+\frac{1}{2 n-1}+\frac{1}{(2 n-1)^2}$$
$$\sum_{n=1}^p\frac{16 n^2}{\left(4 n^2-1\right)^2}=\frac{1}{2} \left(\psi ^{(0)}\left(\frac{3}{2}\right)-\psi
   ^{(0)}\left(p+\frac{3}{2}\right)\right)+$$
$$\frac{1}{8} \left(-2 \psi ^{(1)}\left(p+\frac{3}{2}\right)+\pi
   ^2-8\right)+$$ $$\frac{1}{2} \left(\psi ^{(0)}\left(p+\frac{1}{2}\right)-\psi
   ^{(0)}\left(\frac{1}{2}\right)\right)+
\frac{1}{8} \left(\pi ^2-2 \psi
   ^{(1)}\left(p+\frac{1}{2}\right)\right)$$
Using the asymptotics
$$\sum_{n=1}^p\frac{16 n^2}{\left(4 n^2-1\right)^2}=\frac{\pi ^2}{4}-\frac{1}{p}+\frac{1}{2
   p^2}+O\left(\frac{1}{p^3}\right)$$
Answer: Another way to get the sum of the series
$$\sum_{n=1}^{\infty} \frac{16n^2}{(4n^2-1)^2}
$$
without double summations and without switching the order of the sums.
\begin{align}
\sum_{n=1}^N \frac{16n^2}{(4n^2-1)^2}
&= \sum_{n=1}^N \left[ \frac{2n}{(2n-1)^2} - \frac{2n}{(2n+1)^2} \right] \\[2pt]
&= 2 \sum_{n=1}^N \frac1{(2n-1)^2}
+ \sum_{n=1}^N \left[ \frac{2(n-1)}{(2n-1)^2} - \frac{2n}{(2n+1)^2} \right] \\[2pt]
&= 2 \left( \sum_{n=1}^{2N-1} \frac1{n^2}
- \sum_{n=1}^{N-1} \frac1{(2n)^2} \right)
+ \left[ 0 - \frac2{3^2} + \frac2{3^2} -\frac4{5^2} + \dots{} \right. \\[2pt]
&\quad+ \left. \frac{2(N-1)}{(2N-1)^2} - \frac{2N}{(2N+1)^2} \right] \\[2pt]
&= 2 \left( \sum_{n=1}^{2N-1} \frac1{n^2}
- \frac14 \sum_{n=1}^{N-1} \frac1{n^2} \right)
- \frac{2N}{(2N+1)^2}\,.
\end{align}
Hence,
\begin{align}
\sum_{n=1}^{\infty} \frac{16n^2}{(4n^2-1)^2}
&= \lim_{N\to\infty} \left[ \sum_{n=1}^N \frac{16n^2}{(4n^2-1)^2} \right] \\[2pt]
&= \lim_{N\to\infty}\left[2\left(\sum_{n=1}^{2N-1}\frac1{n^2}-\frac14\sum_{n=1}^{N-1}\frac1{n^2}\right)-\frac{2N}{\left(2N+1\right)^2}\right] \\[2pt]
&= 2 \left( \sum_{n=1}^{\infty} \frac1{n^2} -\frac14 \sum_{n=1}^{\infty} \frac1{n^2} \right) \\[2pt]
&= 2 \left( \frac{\pi^2}6 - \frac14\!\cdot\!\frac{\pi^2}6 \right) \\[2pt]
&= 2 \left(1 - \frac14\right) \frac{\pi^2}6 \\[2pt]
&= 2 \!\cdot\! \frac34\!\cdot\! \frac{\pi^2}6 \\[2pt]
&= \frac{\pi^2}4\,.
\end{align}
Comment: Instead of `$\displaystyle $` you can use the default *displaystyle* formatting (and it comes out centered) with `$$  $$` which is just shorthand for wrapping your math in the *equation* environment: `\begin{equation}  \end{equation}`. Also, for line up equal signs, the *align* environment is very nice. More formatting info [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: Great solution, btw! It's good to remember that infinite series are limits of finite sums *by definition* and those finite sums are sometimes easier to deal with.
Answer: Here is a crazy and over-the-top method using contour integration.
$$
\bbox[15px,#FFFAFD,border:6px groove #0712FF  ]{\int_0^2 x \Biggl\lceil{\frac{1}{x}-\frac{1}{2}\Biggl\rceil}dx = \frac{\pi^2}{4}}
$$

PROOF. Let the integral equal $\mathcal{I}$. Using the transformation $\displaystyle \frac{1}{x}+\frac{1}{2} \mapsto x$, we get
$$
\begin{align}
\mathcal{I} &= \int_0^2 x \Biggl\lceil{\frac{1}{x}-\frac{1}{2}\Biggl\rceil}dx \\
&= \int_0^2 x \Biggl\lfloor{\frac{1}{x}+\frac{1}{2}\Biggl\rfloor}dx \\
&\overset{\frac{1}{x}+\frac{1}{2} \mapsto x}= 8\int_{1}^{\infty}\frac{\lfloor{x\rfloor}}{\left(2x-1\right)^{3}}dx \\
&= 8\sum_{k \in \mathbb{Z}^+} k\int_{k}^{k+1}\frac{dx}{\left(2x-1\right)^{3}} \\
&= 16\sum_{k \in \mathbb{Z}^+}\frac{k^{2}}{\left(4k^{2}-1\right)^{2}} \\
&= 8\sum_{k \in \mathbb{Z}}\frac{k^{2}}{\left(4k^{2}-1\right)^{2}}\,. \\
\end{align}
$$
In that last equality, note that the sequence of terms $\displaystyle \frac{k^2}{(4k^2-1)^2}$ for negative $k$ equals that of positive $k$.

We define a function $\displaystyle f: \mathbb{C} \,\backslash \left(\mathbb{Z}^+ \cup \mathbb{Z}^- \cup \left\{-\frac{1}{2},\frac{1}{2}\right\}\right) \to \mathbb{C}$ such that $\displaystyle z \mapsto \frac{z^2 \cot(\pi z)}{(4z^2-1)^2}$. We also construct a counterclockwise circular contour and a set of poles
$$
\begin{align}
C_n &:= \left\{t \in [0,2\pi]\,:\,\left(n+\frac{1}{2}\right)e^{it}\right\} \\
\mathcal{P}_n &:= \overbrace{\left(\left\{-n,-n+1,\ldots,n-1,n\right\}\,\backslash \left\{0\right\}\right) \cup \left\{-\frac{1}{2},\frac{1}{2}\right\}}^\text{set of simple poles}
\end{align}
$$
where $n \in \mathbb{Z}^+$. The visual above depicts the contour $C_n$ enclosing $\mathcal{P}_n$ over the rainbow phase plot of $f$ with shading.

Notice that $z=0$ is a removable singularity. Writing $\displaystyle \frac{z}{e^{\pi iz}-1}$ as an asymptotic Taylor expansion centered at $z=0$, we get
$$
\begin{align}
f(z) &= \frac{z^2\cot(\pi z)}{(4z^2-1)^2} \\
&= \frac{iz\left(1+e^{2\pi iz}\right)}{\left(4z^{2}-1\right)^{2}\left(e^{\pi iz}+1\right)}\cdot\frac{z}{e^{\pi iz}-1} \\
&= \frac{iz\left(1+e^{2\pi iz}\right)}{\left(4z^{2}-1\right)^{2}\left(e^{\pi iz}+1\right)}\cdot\left(-\frac{i}{\pi}-\frac{1}{2}z+\frac{i\pi}{12}z^{2}+\mathcal{O}\left(z^{4}\right)\right)\,.
\end{align}
$$
This expansion makes it possible to redefine $f$ such that it's analytic in a neighborhood of $0$ and remove $z=0$ as a singularity.
Employing Cauchy's Residue Theorem, we get
$$
\oint_{C_n}f(z)dz = 2\pi i\sum_{k \,\in\, P_n}\mathop{\mathrm{Res}}_{z\,=\,k}f(z) = 2\pi i \left(\sum_{k\,=\,-n}^{n}\mathop{\mathrm{Res}}_{z\,=\,k} f(z) +\mathop{\mathrm{Res}}_{z\,=\,-\frac{1}{2}}f(z) + \mathop{\mathrm{Res}}_{z\,=\,\frac{1}{2}}f(z)\right)
$$

Evaluating the residue at $\displaystyle z=-\frac{1}{2}$ of $f(z)dz$, we get
$$
\begin{align}
2\pi i\mathop{\mathrm{Res}}_{z\,=\,-\frac{1}{2}}f(z) &= 2\pi i \lim_{z\,\to\,-\frac{1}{2}}\left(z+\frac{1}{2}\right)\cdot\frac{iz^{2}\left(1+e^{2\pi iz}\right)}{16\left(z-\frac{1}{2}\right)^{2}\left(z+\frac{1}{2}\right)^{2}\left(e^{2\pi iz}-1\right)} \\
&= -\frac{\pi}{8}\lim_{z\,\to\,-\frac{1}{2}}\frac{z^{2}}{\left(z-\frac{1}{2}\right)^{2}\left(e^{2\pi iz}-1\right)} \lim_{z\,\to\,-\frac{1}{2}}\frac{1+e^{2\pi iz}}{z+\frac{1}{2}} \\
&= -\frac{\pi}{8}\cdot\frac{\left(-\frac{1}{2}\right)^{2}}{\left(-\frac{1}{2}-\frac{1}{2}\right)^{2}\left(e^{2\pi i\left(-\frac{1}{2}\right)}-1\right)}\cdot \lim_{z\,\to\,-\frac{1}{2}}\frac{\frac{d}{dz}\left(1+e^{2\pi iz}\right)}{\frac{d}{dz}\left(z+\frac{1}{2}\right)} \\
&= \frac{\pi}{64}\lim_{z\,\to\,-\frac{1}{2}}\frac{2\pi ie^{2\pi iz}}{1} \\
&= \frac{\pi}{64}\cdot2\pi ie^{2\pi i\left(-\frac{1}{2}\right)} \\
&= -\frac{i\pi^{2}}{32}\,. \\
\end{align}
$$
The same process should apply for calculating the residue at $\displaystyle z=\frac{1}{2}$. It should be
$$
2\pi i\mathop{\mathrm{Res}}_{z\,=\,\frac{1}{2}}f(z) = -\frac{i\pi^2}{32}\,.
$$
Calculating the rest of the residues, we get
$$
\begin{align}
2\pi i \sum_{k\,=\,-n}^{n}\mathop{\mathrm{Res}}_{z\,=\,k} f(z) &= 2\pi i \lim_{z\,\to\,k} \frac{iz^{2}\left(1+e^{2\pi iz}\right)}{\frac{d}{dz}\left(4z^{2}-1\right)^{2}\left(e^{2\pi iz}-1\right)}\\
&= -2\pi\sum_{k\,=\,-n}^{n}\lim_{z\,\to\,k}\frac{z^{2}\left(1+e^{2\pi iz}\right)}{2\left(4z^{2}-1\right)\left(4\pi iz^{2}e^{2\pi iz}+8ze^{2\pi iz}-8z-i\pi e^{2\pi iz}\right)}\\
&=-2\pi\sum_{k=-n}^{n}\frac{k^{2}\left(1+e^{2\pi ik}\right)}{2\left(4k^{2}-1\right)\left(4\pi ik^{2}e^{2\pi ik}+8ke^{2\pi ik}-8k-i\pi e^{2\pi ik}\right)} \tag{1}\\
&= 2i\sum_{k=-n}^{n}\frac{k^{2}}{\left(4k^{2}-1\right)^{2}}\,. \\
\end{align}
$$
In $(1)$, we use the piecewise equality
$$
e^{k\pi i} =
\begin{cases}
  1 & k \equiv 0 \pmod{2} \\
  -1 & k \equiv 1 \pmod{2}\,. \\
\end{cases}
$$
Equating the imaginary part on both sides of the equality that resulted from Cauchy's Residue Theorem and applying $n \to \infty$, we recover the infinite series we want as follows:
$$
\lim_{n\,\to\,\infty}\Im\oint_{C_n}\frac{z^{2}\cot\left(\pi z\right)}{\left(4z^{2}-1\right)^{2}} = \sum_{k\,\in\,\mathbb{Z}}\frac{2k^{2}}{\left(4k^{2}-1\right)^{2}} - \frac{\pi^{2}}{16}
$$
$$
\implies \sum_{k\,\in\,\mathbb{Z}}\frac{k^{2}}{\left(4k^{2}-1\right)^{2}} = \frac{1}{2}\lim_{n\,\to\,\infty}\Im\oint_{C_n}\frac{z^{2}\cot\left(\pi z\right)}{\left(4z^{2}-1\right)^{2}}+\frac{\pi^2}{32}\,.
$$
All that's left is to evaluate the limit of that contour integral and multiply both sides by $8$ to get the desired answer.

We construct a sequence of contour integrals $\displaystyle \oint_{C_n}f$ such that $\displaystyle  \oint_{C_n}f$ converges as $n \to \infty$. As the contour grows bigger, none of the integer poles touch it because we judiciously constructed $C_n$ such that $\displaystyle \Re\left(n+\frac{1}{2}\right)e^{it}$ always lies in between two poles. A visual I made on Desmos can be found here and playing with the $n$ slider.
Letting $z \in C_n$, we use the parameterization $\displaystyle z = \left(n+\frac{1}{2}\right)e^{it}$ on $[0,2\pi]$. We bound the contour integral's modulus and have the following chain of inequalities below:
$$
\begin{align}
0 &\leq \left|\Im \oint_{C_n}f(z)dz\right| \\
&\leq \left|\oint_{C_n}f(z)dz\right| \\
&= \underbrace{\left|\operatorname{\Large\int_{0}^{2\pi}}\frac{\left(n+\frac{1}{2}\right)^{2}e^{2it}\cot\left(\pi\left(n+\frac{1}{2}\right)e^{it}\right)}{\left(4\left(n+\frac{1}{2}\right)^{2}e^{2it}-1\right)^{2}}\left(n+\frac{1}{2}\right)ie^{it}dt\right|}_{z \, \in\, C_n} \\
&\leq \operatorname{\Large\int_{0}^{2\pi}}\left|\frac{\left(n+\frac{1}{2}\right)^{2}e^{2it}\cot\left(\pi\left(n+\frac{1}{2}\right)e^{it}\right)}{\left(4\left(n+\frac{1}{2}\right)^{2}e^{2it}-1\right)^{2}}\left(n+\frac{1}{2}\right)ie^{it}\right|dt \\
&= \operatorname{\Large\int_{0}^{2\pi}}\frac{\left(n+\frac{1}{2}\right)^{3}\left|\cot\left(\pi\left(n+\frac{1}{2}\right)e^{it}\right)\right|}{\left|4\left(n+\frac{1}{2}\right)^{2}e^{2it}-1\right|^{2}}dt \\
&\leq \frac{\left(n+\frac{1}{2}\right)^{3}}{\left(4\left(n+\frac{1}{2}\right)^{2}-1\right)^{2}}\int_{0}^{2\pi}\left|\cot\left(\pi\left(n+\frac{1}{2}\right)e^{it}\right)\right|dt \\
&= \frac{\left(n+\frac{1}{2}\right)^{3}}{\left(4\left(n+\frac{1}{2}\right)^{2}-1\right)^{2}}\operatorname{\large\int_{0}^{2\pi}}\left|i+\frac{2i}{\exp\left(2\pi\left(n+\frac{1}{2}\right)ie^{it}\right)-1}\right|dt \\
&\leq \frac{\left(n+\frac{1}{2}\right)^{3}}{\left(4\left(n+\frac{1}{2}\right)^{2}-1\right)^{2}}\operatorname{\large\int_{0}^{2\pi}}\left(1+\frac{2}{\left|\exp\left(2\pi\left(n+\frac{1}{2}\right)ie^{it}\right)-1\right|}\right)dt \\
&\leq \frac{\left(n+\frac{1}{2}\right)^{3}}{\left(4\left(n+\frac{1}{2}\right)^{2}-1\right)^{2}}\operatorname{\large\int_{0}^{2\pi}}\mathop{\mathrm{sup}}_{t \in [0,2\pi]}\left(1+\frac{2}{\left|\exp\left(2\pi\left(n+\frac{1}{2}\right)ie^{it}\right)-1\right|}\right)dt \\
&= \frac{2\pi\left(n+\frac{1}{2}\right)^{3}}{\left(4\left(n+\frac{1}{2}\right)^{2}-1\right)^{2}}\mathop{\mathrm{sup}}_{t \in [0,2\pi]}\left(1+\frac{2}{\left|\exp\left(2\pi\left(n+\frac{1}{2}\right)ie^{it}\right)-1\right|}\right)\,.
\end{align}
$$
Here, we bound the integral by its supremum because the graph of $\displaystyle 1+\frac{2}{\left|\exp\left(2\pi\left(n+\frac{1}{2}\right)ie^{it}\right)-1\right|}$ is a square-looking wave for large $n$ periodic on $2\pi$.
Applying $n \to \infty$, we get
$$
\lim_{n \to \infty} 0 \leq \lim_{n\to\infty}\left|\Im \oint_{C_n}f(z)dz\right| \leq \frac{2\pi\left(n+\frac{1}{2}\right)^{3}}{\left(4\left(n+\frac{1}{2}\right)^{2}-1\right)^{2}}\mathop{\mathrm{sup}}_{t \in [0,2\pi]}\left(1+\frac{2}{\left|\exp\left(2\pi\left(n+\frac{1}{2}\right)ie^{it}\right)-1\right|}\right)\,.
$$
Since the supremum is fixed and the numerator grows slower than the denominator, we can use the Squeeze Theorem for sequences to get
$$
\begin{align}
&\lim_{n\to\infty}\left|\Im \oint_{C_n}f(z)dz\right| = 0 \\
\implies
&\bbox[15px,#DBFFEA]{\lim_{n\to\infty}\Im \oint_{C_n}f(z)dz = 0\,.} \\
\end{align}
$$

Wrapping things up,
$$
\require{cancel}{\sum_{k\,\in\,\mathbb{Z}}\frac{k^{2}}{\left(4k^{2}-1\right)^{2}} = \frac{1}{2}\cancelto{0}{\lim_{n\,\to\,\infty}\Im\oint_{C_n}\frac{z^{2}\cot\left(\pi z\right)}{\left(4z^{2}-1\right)^{2}}}+\frac{\pi^2}{32}\,.}
$$
Then we just multiply both sides by $8$. Finally, we conclude that
$$
\bbox[15px,#E7FCFF,border:6px groove #51008C ]{\int_0^2 x \Biggl\lceil{\frac{1}{x}-\frac{1}{2}\Biggl\rceil}dx = \frac{\pi^2}{4}}
$$
and we're finally done! $\blacksquare$
Happy New Year :)


Keep getting errors using Join function in CloudFormation

Question: Using the Join function in CFN is driving me nuts.
It sometimes works and sometimes it doesn't and there seems to be nothing wrong with the sintaxes I'm using, the erros are not consistent. The validation of the template ALWAYS returns Ok but at the very last step of the stack creation, it fails, sometimes throwing an error while creating the resource (because of a badly formed name) or giving me this error message every Fn::Join object requires two parameters, (1) a string delimiter and (2) a list of strings to be joined or a function that returns a list of strings (such as Fn::GetAZs) to be joined..
Is there a good way of debuggin this instead of going all the way to creating the resources?
For instance, what is wrong with this syntax?
  BucketName: !Join
    - ''
    - - !FindInMap
        - Naming
        - BasicPrefix
        - Name
      - '-'
      - !Ref BusinessUnitName
      - '-'
      - !Ref EnvType

Or, why can't use a syntax like the one below for the same result?
  BucketName: !Join
    - '-'
    - - !FindInMap
        - Naming
        - BasicPrefix
        - Name
      - !Ref BusinessUnitName
      - !Ref EnvType

Or this shorthand one:
BucketName: !Join ['-', [!FindInMap [Naming, BasicPrefix, Name], !Ref BusinessUnitName, !Ref EnvType]]

None will work. I have to keep trying different ways of doing it, until CFN will accept it. It's exhausting.
Please help.
Answer: Your syntax looks correct but would require complete template to get to identify the cause for the error.
However for your scenario, Fn::Sub is much better option compared to Fn::Join, try using Fn::Sub with a mapping as below
BucketName: !Sub
  - ${MapResult}-${BU}-${Env}
  - { MapResult: !FindInMap [Naming, BasicPrefix, Name] }
  - { BU: !Ref BusinessUnitName }
  - { Env: !Ref EnvType }

Comment: I found the problem finally, It had to do with the type of the "EnvType" parameter, which should be String but was CommaDelimitedList.


Angles in nine-point circle scenario

Question:
Let the sides $AD$ and $BC$ of the quadrilateral $ABCD$ (such that $AB$ is not parallel to $CD$) intersect at point $P$. Points $O_1$ and $O_2$ are the circumcenters and points $H_1$ and $H_2$ are the orthocenters of triangles $ABP$ and $DCP$, respectively. Denote the midpoints of segments $O_1 H_1$ and $O_2 H_2$ by $E_1$ and $E_2$, respectively. Prove that the perpendicular from $E_1$ on $CD$, the perpendicular from $E_2$ on $AB$ and the line $H_1 H_2$ are concurrent.

Solution 2. Let the perpendicular from $E_1$ on $CD$ meet $PH_1$ at $X$, and the perpendicular from $E_2$ on $AB$ meet $PH_2$ at $Y$ (see Figure 3). Let $φ$ be the intersection angle of $AB$ and $CD$. Denote by $M$, $N$ the midpoints of $PH_1$m $PH_2$, respectively.

We will prove now that triangles $EX_1M$ and $E_2YN$ have equal angles at $E_1$, $E_2$, and supplementary angles at $X$, $Y$.
In the following, angles are understood as oriented, and equalities of angles modulo $180°$.
Let $α = ∠H_2PD$, $ψ = ∠DPC$, $β = ∠CPH_1$. Then $α + ψ + β = φ$, $∠E_1XH_1 = ∠H_2YE_2 = φ$, thus $∠MXE_1 + ∠NYE_1 = 180°$.
By considering the Feuerbach circle of $\mathord{△}ABP$ whose center is $E_1$ and which goes through $M$, we have $∠E_1MH_1 = ψ + 2β$. Analogous consideration with the Feuerbach circle of $\mathord{△}DCP$ yield $∠H_2NE_2 = ψ + 2α$. Hence indeed $∠XE_1M = φ - (ψ + 2β) = (ψ + 2α) - φ = ∠YE_2N$.

This is from IMO'09 (full pdf is here: http://www.imo-official.org/problems/IMO2009SL.pdf). Could someone please explain why angles $E_1MH_1$ and $H_2NE_2$ are what they are in the last paragraph?
Answer:
$\def\tri{\mathord{△}}$It suffices to consider $\tri PAB$. In the figure above, $K$ is the perpendicular foot of $B$ on line $AP$, and $S$ is the midpoint of segment $BH$. Note that circle $KSM$ is the nine-point circle of $\tri PAB$. Since $MS$ is parallel to $PB$, then$$
∠SMH = ∠BPH = β.
$$
Because $E$ is the center of circle $KSM$. then$$
∠EMS = \frac{π}{2} - \frac{1}{2} ∠SEM = \frac{π}{2} - ∠SKM = \frac{π}{2} - ∠KHM = ∠KPH = ψ + β.
$$
Thus,$$
∠EMH = ∠EMS + ∠SMH = ψ + 2β.
$$
Comment: Why is $\angle SKM$ equal to $\angle KHM$?
Comment: @user75619 Because $M$ is the midpoint of $PH$ and $∠PKH=\frac π2$.
Comment: ok, looks like i got it... $M$ is the center of the circumcircle of triangle $PKH$, $MK$ is its radius and hence $MK=MH$.

Angles in nine-point circle scenario


Jeffreys' invariance principle - A doubt on the one-dim case

Question: In this wiki link concerning a change of parameterization of a likelihood $L$ from $\theta$ to $\varphi$, why can the $d\theta/d \varphi$ go inside the expectation?
$$\eqalign{
p(\varphi) &= p(\theta)\left|\frac{d\theta}{d\varphi}\right| \propto\sqrt{I(\theta) \left(\frac{d\theta}{d\varphi}\right)^2} \\
&= \sqrt{E\left[\left(\frac{d\,\log(L)}{d\theta}\right)^2\right]\left(\frac{d\theta}{d\varphi}\right)^2} \\
&= \sqrt{E\left[\left(\frac{d\,\log(L)}{d\theta}\frac{d\theta}{d\varphi}\right)^2\right]}.
}$$
Is it because the expectation is over $\theta$ and not $\varphi$?
Any help would be appreciated
Answer: The Fisher information $I(\theta)$ is an expectation over the data $X$ so $\frac{d\theta}{d\phi}$ is constant with respect to it (since $\theta$ and $\phi$ are data-less parameterizations). To be more precise:
$$
I(\theta) = \int_{\mathcal X} \left( \frac{\partial}{\partial \theta} \log f(x; \theta) \right)^2 f(x; \theta) dx
$$
so something that is only a function of $\theta$ and $\phi$ is constant with respect to this integral and can be freely moved about. See the Wikipedia page of the Fisher information for more details.
Comment: +1. Apparently your "$f$" is the same as "$L$" in the referenced Web page.


What are the list of Drupal 7 image cropping modules out there?

Question: Currently I use EPSA crop for cropping images as it uses the same image field without making a new one. What are the list of image cropping modules out there that provide a similar functionality? Epsa crop gives me the ability to crop different sized images for different image styles.
Comment: Sorry but questions asking for 'lists' of anything are automatically off-topic on any Stack Exchange site. [Q+A is Hard, Let's Go Shopping!](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/)...
Answer: You can use the Image Javascript Crop Module.

This module makes an Imagecache 2 (D6) or Styles (D7) 'javascript crop' toolbox action available for use with several modules.
Answer: There is more powerful Imagefield Crop module.

imagefield_crop provides a widget for cropping an image after upload.

It saves a cropped image rather than using some Imagecache 2 (D6) or Styles (D7) things on image.


Broken Pickup Compartment in New Electric Guitar

Question: My new Sterling Albert Lee AL40 strat arrived yesterday and I found that the compartment where the bridge pickup sits is broken. The wood in this area is pretty flimsy as well and is cracked as the attached picture shows.
The guitar is made in Indonesia and is a cheaper version of the signature Music Man Albert Lee HH strat.
I'm new to electric guitars and I'm wondering what effect this will have on the sound. I like this guitar besides these defects and would rather keep it if this isn't a problem.
Should I return the guitar or is it a non issue? It looks like this now after I set it up myself: https://i.stack.imgur.com/2NTav.jpg
Thanks in advance for your input!
Comment: You may be stuck between a rock & a hard place. I'd immediately return it as 'damaged on arrival', however, unless you can see that damage from the outside, you may have invalidated your claim by taking it apart.
Comment: Thanks Tim and Tetsujin. Yes I don't have a reference to compare it with so I can't know how the sound might have been affected. Also generally the guitar doesn't feel solid and the broken internals suggest either poor manufacturing quality or little oversight neither of which is good. So I have made my decision to return the guitar.
Comment: Simple question - what made you strip the guitar after one day?
Comment: The guitar came in without being setup, which surprised me, so I stretched the strings, tuned them, removed tension on the truss rod to raise the action, and also the humbucker pickups were wobbly so I had to get inside the hull(?) to understand how they were seated and use the screws to tighten them in place. It's good now to my ears at least.
Comment: Thanks Tetsujin for your suggestion. Is it based on how it would affect the sound or is it concerning the longevity of the body of the guitar itself?
Comment: Doubtful the sound will be affected at all. And, how would you ever know anyway?
Comment: I think for the price, you'd be entitled to one that doesn't look like it's been smacked with a hammer. You have no idea what other damage there may be, or how it may manifest over time.
Answer: Personally, I would contact the shipping company responsible for transporting the guitar, they should have insurance to cover such damage and you certainly deserve an undamaged instrument for yourself. If you should ever choose to sell your instrument, that damage will make it difficult to get a fair price. From what I can see, I wouldn't expect the damage to affect the sound or playability of the guitar, but you'll have to decide for yourself.


Which quantile type (quantile calculation method) is best for small samples?

Question: The R help page of the quantile function lists 9 types of quantiles, i.e. 9 methods to calculate sample quantiles. Which method suits small sample sizes best? Which method will give the most similar quantile estimates if I take samples of sizes 6, 7, 8 of the same population? The distribution looks similar to log-normal; I'm most interested in percentiles 5, 50 and 95.
Comment: I don't know the answer to this question, but simulation might give you at least an idea of which method is the "best" (whatever you mean by _best_).
Answer: It sounds as if you want to estimate a particular quantile rather than report a quantile as a descriptive statistic. For that purpose, consider a tailored estimation method such as that proposed by Harrell and Davis. As Frank Harrell is an enthusiastic R user, there's an implementation in R.
All that said, trying to get at the 5% and 95% percentiles from samples of sizes 6 to 8 is a really big stretch: more ESP than statistics, some might say. Essentially, you are extrapolating wildly, whatever you do.
Note that being "similar" to lognormal does not get you very far, as being slightly wrong about the distribution could get you very wrong answers about quantiles in the tails. But it does suggest to me that you should take logarithms first, and more broadly try at least two different methods, perhaps one assuming (log)normal parent and one not.
Why are you obliged to treat these samples separately? Can you pool them?


More help with vertical asymptotes

Question: Of the six questions regarding finding vertical asymptotes of graphs, I've had problems with two.  The second is using the graph of $$g(x)= \frac{3+x}{x^{2}(3-x)}$$
Now, looking at the function, it seems that both 0 and 3 will be the vertical asymptotes, since $$g(0)= \frac{3+0}{0^{2}(3-0)}= \frac{3}{0(3)}= \frac{3}{0}= undefined$$ and
$$g(3)= \frac{3+3}{3^{2}(3-3)}= \frac{6}{9(0)}= \frac{6}{0}= undefined$$
However, those answers were not accepted, why?
Comment: Probably a more detailed analysis was asked: Observe that $\lim_{x \searrow 3} g(x) = - \infty$ and $\lim_{x \nearrow 3} g(x) = + \infty$. The picture at $0$ is different. Have a look at http://www.wolframalpha.com/input/?i=%28x%2B3%29%2F%28x%5E2+%283-x%29%29
Comment: Accepted by whom? What is the definition of *vertical asymptote* you are working with?
Comment: @mariano, this calculus class homework is submitted and processed by webassign.net.  The definition I'm working with is if f(x) approaches positive or negative infinity,  as x approaches c from the right or left, then the line x=c is a vertical asymptote of the graph of f
Answer: The usual definition for a vertical asymptote at $x=a$ is that at least one of the following conditions must be satisfied.

$\displaystyle \lim_{x \rightarrow a^+} f(x) = \pm \infty$
$\displaystyle \lim_{x \rightarrow a^-} f(x) = \pm \infty$

It is clear from the equations and from the graph of the function that at least one of these conditions is satisfied at $x=0$ and $x=3$.
Hence, $x=0$ and $x=3$ are both vertical asymptotes to the function.
However, I have seen some people defining vertical asymptote as
$$\displaystyle \lim_{x \rightarrow a^-} f(x) = \displaystyle \lim_{x \rightarrow a^+} f(x) = \pm \infty$$
i.e. the left limit and the right limit must both tend to $+\infty$ or the left limit and the right limit must both tend to $-\infty$. In that case, $x=3$ won't be consider a vertical asymptote.
In general, I prefer to work with the first definition.
Comment: and that's the same definition as provided in the book.

More help with vertical asymptotes


Boot BroadcastReceiver does not work on Xiaomi devices

Question: I have a following BroadcastReceiver which should run after boot completion. I have tested it on my Xiaomi device (Redmi 1s), it's not running, while on other devices like Samsung it's running as expected.
public class DeviceBootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
            Toast.makeText(context, "I am Running", Toast.LENGTH_SHORT).show();
        }
    }
}

I have set permission in Manifest.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

And following is my broadcast receiver:
<receiver android:name=".receiver.DeviceBootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

Comment: I have problem with android 8 xamoi phones with RECEIVE_SMS when app is in background and Receiver is triggred but message is empty. Do have any idea about this?
Answer: I searched around the web and found a solution, I've decided to answer my own question. Follow the same code given in the question.
In Xiaomi devices, you just have to add your app to Autostart list, to do so, follow these simple steps given below:

Open Security app on your phone.
Tap on Permissions, it'll show you two options: Autostart and
Permissions
Tap on Autostart, it'll show you list of apps with on or off toggle
    buttons.
Turn on toggle of your app, you're done!

Now, reboot your phone, you'll see a Toast message I am Running
Comment: You have helped me a lot! I did not know about this :)
Comment: @Dimitar : oh! I'm glad that it helped you.
Comment: Man you saved my life... I guess I would have never found this solution...
Comment: I cant see Autostart option in Xiaomi hm note1 LTE
Comment: @Salivan I am glad :)
Comment: But how to do this automatically ? User isn't going to do this.
Comment: @bdevloper I also don't know, it's Xiaomi's policy, permission or we can say a security feature for apps.
Comment: I have problem with android 8 xamoi phones with RECEIVE_SMS when app is in background and Receiver is triggred but message is empty. Do have any idea about this?


Optimized way to write a series strings to a text file without quotations

Question: I am new to Julia so sorry if this question is obvious.
I am trying to use Julia to help me run a series of finite element models, which use a text input file to give instructions to the finite element solver. Basically, I would like to use Julia to read in the base input file, edit some parameters on some lines of the file and then write it as a new file. I am getting hung up on a couple things though.
Currently, I am reading in the file like this
mdl = "fullmodelSVTV"; #name of input file
A = readlines(mdl*".inp")

This read each line from the file in as a separate string in a vector which I like because it makes it easier to edit the sections I want but it also makes things more difficult when I try to write to a new file.
I am writing the file like this.
io = open("name.inp","w")
print(io,A)
close(io)

When I try to write to a new file the output ends up look like this
Output from code
which is ["string at index 1","string at index 2","string at index 3"...].
What I would like to do is output this the exact same way is it is read in with string at each index of the vector on its own line. I would also like to remove the brackets and quotation marks from the file, as they might interfere with the finite element solver.
I think I have found a way to concatenate all of the strings at each index and separated them with a new line like shown below.
for i in 1:length(A)
    conc = conc*"\n"*lines[i]
end

The issue with this is that it takes a long time to do given the size of the input files I am working with and I feel like there has to achieve my goal.
I also cannot find a way to remove the brackets or quotation marks when writing the file.
So, I'm wondering if anyone has any advice for a better way to write these text files in terms of both concatenating all of the strings from the vector when outputting as well as outputting without the brackets and quotation marks.
Thanks, any advice is appreciated.
Answer: The issue with print(io,A) is that it is printing a representation of the vector, but in fact you want to print each element of the vector. To do so, you can simply print each line in a loop:
open("name.inp", "w") do io
    for line in A
        println(io, line)
    end
end

This avoids the overhead of string concatenation.
Comment: Wow thank you so much. I spent hours googling around looking for the solution to this and I can't believe how simple it is.


How to split input of numbers into a list

Question: How do I turn these numbers into a list using python?
16 3 2 13 -> ["16","3","2","13"]
Comment: Please [edit](https://stackoverflow.com/posts/66166103/edit) your question to show what research you've done and any attempts you've made based on that research. Take the [tour](https://stackoverflow.com/tour) and read [How to Ask](https://stackoverflow.com/questions/how-to-ask) for more tips about this site and asking questions.
Comment: Does this answer your question? [String to list in Python](https://stackoverflow.com/questions/5453026/string-to-list-in-python)
Comment: What format does `16 3 2 13` represent?  Did you mean to type `"16 3 2 13"` to indicate a single string?
Answer: You can divide it by using split:
"16 3 2 13".split()

Output:
["16","3","2","13"]

Answer: If you just want to split by whitespaces.
data = '16 3 2 13'
print(data.split())

Answer: a = '16 3 2 13'

b = ['']
print(type(b))
print(len(b))

j = 0
for i in range(len(a)):
    if a[i] != ' ':
        b[j] = b[j] + a[i]
    else:
        j = j+1
        b.append('')

print(b)


LINQ to XML using as a simple data abstraction layer?

Question: Background for understanding the question
I'm currently designing a simple, light-weight (application-specific) message-based API in C# 4.0. The majority of the messages will leave the .NET/Silverlight stack, thus they get serialized as a XML stream. Some messages are also send/received to local components, hence there is no reason for serialization.
Currently, there is a simple data abstraction layer designed for that API, which contains the content of the message. This data abstraction layer is supposed to be soley used for that purpose.
Now, there is the challenge that, especially during initialization of the application, there are some very big messages, which are received by other systems, thus the xml stream is pretty heavy-weight (several thousand of xml elements). That would mean there several thousand instance of that data abstract layer objects are generated, the message is processed and then the whole data instances are removed.
Question
My question would be: Is linq-to-xml quite good concerning memory consumption/performance so there is no need for a separate data abstraction layer?
My understanding is that linq-to-xml renders only the content if the content is written to a stream.
Thanks for giving feedback.
Answer: LINQ to XML does parse your document in a lazy way, but it does build a complete graph of objects into memory, and it creates a lot of object in memory. It has a great API but is certainly not light-weight. Please do measure performance to see if the performance of LINQ to XML suites your application performance requirements.
Comment: That's not true. The queries are evaluated lazily, but the document is fully loaded in memory when you do `XDocument.Load` or `XDocument.Parse`
Comment: @Thomas: Thanks. You are absolute right about that. Fixed my answer.


Proving the inequality problem

Question: Proving the inequality:
$\frac{a^3+b^3+c^3}{a^2+b^2+c^2}>\frac{a+b+c}{3}$
$a, b$ and $c$ are positive real numbers
I know that it is the same as proving:
$a^3+b^3+c^3+abc>\frac{(a+b)(b+c)(c+a)}{2}$
However, I'm stuck in this step, I don't know how to prove it. Can someone help me with this problem?
Is it a problem where I need to apply the Chebyshev's inequality?
Comment: If $a = b = c = 1$ it fails. Maybe you mean $\geq$.
Comment: Is there any constraint on a,b,c?
Comment: For $a, b, c  \geq 0,  a^3 + b^3 \geq a^2b+ab^2 $
Comment: Also, please change the title to make it less generic and more specific to your problem. Best is just to state the question in the title...
Answer: This is equivalent to showing that for $a,b,c > 0$,
$$\begin{aligned} 3(a^3 + b^3 + c^3) &\geq (a + b + c)(a^2 + b^2 + c^2) \\
&= a^3 + b^3 + c^3 + ab^2 + ba^2 + bc^2 + cb^2 + ac^2 + ca^2\\ ab^2 + ba^2 + bc^2 + cb^2 + ac^2 + ca^2 &\leq 2a^3 + 2b^3 + 2c^3. \end{aligned}$$
Since $a^3 + b^3 - a^2b - ab^2 = (a-b)^2(a+b) \geq 0$ since $a,b > 0$, then we have (by using a similar argument for $b,c$ and $c,a$) $$\begin{aligned} ab^2 + ba^2 &\leq a^3 + b^3 \\ bc^2  + cb^2 &\leq b^2 + c^2 \\  ac^2 + ca^2 &\leq a^2 + c^2.\end{aligned}$$
The required inequality follows.

Alternatively, define the discrete random variable $X$ that takes value $a,b,$ and $c$ with probability $\frac{1}{3}$ each respectively. Let $E(X) = \mu > 0$ (since $a,b,$ and $c$ are $> 0$). By Jensen's inequality, we have
$$E(X^3) \geq E(X^2)^{1.5} = E(X^2)(E(X^2))^{0.5} = E(X^2)(E(X)^2 + Var(X))^{0.5} \geq E(X^2)E(X)$$
since $E(X^2) = E(X)^2 + Var(X)$, $Var(X) \geq 0$, and $t \mapsto t^{1.5}$ for $t > 0$ is a convex function.
Thus,
$$E(X^3) = \frac{a^3 + b^3 + c^3}{3} \geq \frac{a + b + c}{3}\frac{a^2 + b^2 + c^2}{3} = E(X)E(X^2). $$
The required inequality follows.
Answer: Equivalently, required to prove $$0\le 3(a^3+b^3+c^3)-(a+b+c)(a^2+b^2+c^2)=$$ $$=2(a^3+b^3+c^3)-(\,a^2(b+c)+a(b^2+c^2)+(bc^2+b^2c)\,)= ^{def}F(a,b,c).$$
WLOG $a=\max (a,b,c).$
Differentiating $F$ with respect to $a,$ keeping $b,c$ constant, we have $$\frac {\partial F}{\partial a}=6a^2-2ab-2ac-b^2-c^2=$$ $$=(a^2-b^2)+(a^2-c^2)+2a((a-b)+(a-c))\ge 0.$$ Therefore $F(a,b,c)\ge F(b,b,c).$ So we have $$F(a,b,c)\ge F(b,b,c)=2b^3+2c^3-2b^2c-2bc^2=$$ $$=2(b+c)(b^2+c^2-bc)-2(b+c)(bc)=$$ $$=2(b+c)(b^2+c^2-2bc)=$$ $$2(b+c)(b-c)^2\ge 0.$$

Proving the inequality problem


Sound loading working in ubuntu but not working in windows

Question: I have written a method in java to play a sound. It works fine on my ubuntu laptop but doesnt work on windows. There is no error but i think it might be bypassing the drain method on windows for some reason.
public static void runOnce(final String location) {
    new Thread(new Runnable() {
        public void run() {
            try {
                File audioFile = new File(Game.gameFolder + "/sounds/" + location);
                final AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);

                AudioFormat format = audioStream.getFormat();

                DataLine.Info info = new DataLine.Info(Clip.class, format);

                final Clip audioClip = (Clip) AudioSystem.getLine(info);

                audioClip.open(audioStream);
                audioClip.start();
                audioClip.drain();
                try {
                    audioClip.close();
                    audioStream.close();
                } catch (Exception e) {
                    System.out.println("heyeyeyeyye");
                }
                System.out.println("sound method ran");
            } catch(Exception e) {}
        }
    }).start();
}

thanks -Tyler
EDIT:
i remember actually it worked on windows before i used drain but after a certain amount of time it wouldnt load anymore so i switched to drain
Comment: Not just a problem with the forward slashes in the path?
Comment: it actually plays the sound once every few minutes so it reads it for sure. also it prints "sound method ran" the amount of times it should/ the same amount of times as on ubuntu
Comment: @sje397 forward slashes will be translated by the JVM on windows.
Comment: Shouldn't you wait for the whole clip to be played before closing? What if you play an hour long clip
Comment: the whole clip does play... the drain waits until done thats why i have it in a separate thread
Answer: I suggest you use try-with-resources and that you join() the Thread you start and never swallow the message from your Exception. Something like,
public static void runOnce(final String location) {
    File audioFile = new File(Game.gameFolder + "/sounds/" + location);
    Thread t = new Thread(new Runnable() {
        public void run() {
            try (AudioInputStream audioStream = AudioSystem
                    .getAudioInputStream(audioFile);) {
                AudioFormat format = audioStream.getFormat();
                DataLine.Info info = new DataLine.Info(Clip.class, format);
                try (Clip audioClip = (Clip) AudioSystem.getLine(info);) {
                    audioClip.open(audioStream);
                    audioClip.start();
                    audioClip.drain();
                }
                System.out.println("heyeyeyeyye");
                System.out.println("sound method ran");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    t.start();
    t.join();
}

Comment: i just found a class that implements thread. it works on my computer (ubuntu) so when i can use my moms again i will test it on there. i got the class from the first answer [here](http://stackoverflow.com/questions/18009542/extreme-lag-after-having-wav-au-sound-in-my-game?rq=1) if you want to see it.
Comment: yep theres worked. yours probably would have too but theres seems like i can do more with it too anyways


Elastic: I want to Write a Query (Peak volume per hour experienced at any time in the specific month)

Question: I got total data for a month.
Now, I want to get peak volume per hour in that specific month with the help of query?
I am working with Kibana-Elastic.
Answer: Use a filter query to filter the result, then use a aggregation on the result to achieve the peak. For the aggregation part u will need to use a date histogram combined with a Max aggregation.
The Date Histogram splits the result into seperate buckets on which u can then use the max metric aggregation.
If u want futher help u will need to provide ur data structure as its rly complicated to help without knowing the data u wanna query.


Load php.ini in each folder

Question: I have a question for the php.ini in root folder, how it can be loaded when reading the page and overwrite the original value.
When I was using the webhosting service, I could simply put the php.ini into root folder, then file will overwrite the existing php.ini value on the original php.ini.
However, I am now trying to use local server for development. I use OSX Server App to setup a server, upgraded php5.4 to 5.5 and check everything is good. The phpinfo function shows nothing wrong. But when I put another php.ini in each folder of developing website, they are not be loaded when page is loading. (Its working if I change the value on original php.ini).
May I ask what I am missing and what should I looking for??
Thank you very much for your help!!
Best regards,
Comment: Apache1 or Apache2?
Comment: @SverriM.Olsen Apache2
Answer: There will be a difference if you are using mod_php or suPHP. It's likely that you'll be running mod_php, whereas your host will be running suPHP (suPHP comes with the advantage that scripts run as the correct user, not as a general user like nobody which is what mod_php does).
The feature you're looking for, custom php.ini files, is something specific to suPHP. So, there are two solutions to your scenario:

Run suPHP on your local machine
Change the relevant settings in either php.ini or in .htaccess via things like php_flag

Personally, I'd recommend running your local setup as close to production as possible; so I'd opt for option one.

Load php.ini in each folder


How do I create an Events page listing all Event nodes?

Question: I have a Theatre website that I'm creating in Drupal 8, and I need to create an Event content type. This content type will be displayed on an Events page listing all Events in ascending order from closest date to latest. (I'm pretty sure I can get Views to do this.)
This is how each node should look like when listed on the Events page.

I know I need to create fields for:

Event Poster
Event Presenter
Name of the Event (This would be the Title Field)
Day(s) of the event
Time(s) of the event
Event price(s)
Link to external Ticketmaster-type website to purchase tickets

The problem I have is that not all events are only set up to be on one day or at one time; some events may be listed like the following (Where there are multiple time listings for the day) or some might be where the event is being held for multiple days and may have different times of when it is being held.

What field type should I use for the datetime field? Is there a special module I should get for this that allows multiple dates to be listed? Do I even need to worry about a special Time field or do I just keep it as a plain text field for the user to just type in the time(s)?
TL;DR: How do I create a date field that allows to list multiple days (maybe times) and then sorting the content type by the days of the event in ascending order?
Comment: do you found a solution?
Comment: Nope, I have yet to find a solution to this. Been scouring everywhere but keep hitting dead ends.
Answer: You can use a Date field with an End Date (I don't have at this moment Drupal 8 installed to show you how)
With Views you can configurate your field to show the Start Date and the End Date. For use the format of Date in one place and Time in another place, you need to create a new Date format.
Maybe this question can be interesting for you: When should I use collect an end date for a field, instead of using 2 separated date fields?. Or have a look at How to Add a Custom Date Format in Drupal 8.
Comment: What do you mean by create a new Date format? Could you give me an example?

Basically, if I use the datetime field for the Date and then have them select multiple dates, is it possible to then have it show up as: (ex. Sept 1-5, 2016 instead of it printing each date on a new line)?

And then say that there are multiple times for the different dates, can I not have it print on its own line, 2:00pm & 7:00pm since those would be the only 2 time slots on those dates?

Let me know if I'm not being as clear as possible. Thanks.
Comment: @ACanadianCoder check this https://www.ostraining.com/blog/drupal/d8-dates/


Shell script loop for printing lines doesn't match

Question: I've to display all lines doesn't match on files "inventory.txt" and "monitored_servers.txt". I was able to print all lines that match, as you can see below:
for i in `cat inventory.txt`; do grep $i monitored_servers.txt >> result.txt; done

How to display all lines doesn't match?
Comment: Aside: [Don't Read Lines With `for`](http://mywiki.wooledge.org/DontReadLinesWithFor)
Comment: Also, the above (running `grep` once per word in the inventory) is *really* slow. Even for the positive case, you'd get much better performance with just one grep invocation processing the whole inventory.
Answer: grep -v -f inventory.txt monitored_servers.txt >non-matching.txt

Comment: `-x` might be important too
Comment: @janos, ...maybe, but since the OP is satisfied with the result in their original usage, I'm not convinced.
Answer: grep -v --file inventory.txt monitored_servers.txt

-v - lines that don't match
--file - using your file as template
Comment: Think I beat you there by 25 seconds. :)
Comment: Damn , you're quick ;)
Comment: \o/  :D

Tks a lot!


Create dropdown list from values DB

Question: I got some values from the database
<code>        $result = db_select('node', 'n')
        ->condition('type', 'staff_members')
        ->fields('n', array('nid', 'title'))
        ->execute();

        $options = array();

        while($row = $result->fetchAssoc()) {
            $options[] = array("nid"=>$row['nid'], "title"=>$row['title']);
        }
</code>
What I try to do is implement this results into my dropdown list, so I can select the node wich I need. But it's important that the title is related with the Nid, as value.
<code>        $form['staff_member_options'] = array(
            '#type' => 'value',
            '#value' => array('Nid from array' => t('Title from array'))
        );
</code>
I don't how this is possible because I can't make a while loop in the array, I guess?
Comment: You should read the form api docmentation for Drupal 7 regarding the select element. Specifically, the #options element property.
Answer: Your $options should be:
<code>while($row = $result->fetchAssoc()) {
  $options[$row['nid']] = $row['title'];
}

$form['staff_member_options'] = array(
 '#type' => 'select',
 '#title' => t('title of the select')
 '#options' => $options
);
</code>

Create dropdown list from values DB


Propensity scores in logistic regression models

Question: I have a query after reading a paper, which is about the effectiveness of a medical device. In summary, what the authors did was
1. Generating a propensity score using a multivariable logistic regression based on x number of covariates to see the probability of receiving the medical device.
2. They subsequently evaluated the association between the device and a pre-specified patient outcome Y using logistic regression models. Their model was as follows:
Y ~ propensity score + presence of device + variable Z
in which variable Z is an ordinal variable

They then assessed for effect measure modification of the medical device on patient outcome depending on the level of variable Z by introducing an interaction term significance of the interaction in the model

My queries are as follows:

What is the advantage of not introducing variable Z when generating the propensity scores? Why did they have to use the propensity score as one variable and variable Z separately? Since they were interested the effect modification, it would signify that variable Z did play a role in influencing the presence of the medical device and the outcome, therefore putting it into the propensity score analysis should be valid?
Are there any limitations in introducing the propensity score into the logistic regression model, as opposed to using the propensity score to do matching (e.g. greedy/ optimal, with/without replacement)? Then finding out the relationship using odds ratios?
Answer: I want to add on to @StatsStudent's answer.
There are a few ways to control for a confounder. One is by including that confounder in a well-formed propensity score and conditioning on the propensity score. Another is conditioning directly on the confounder. If $Z$ is a confounder, then generally it belongs in the propensity score model. However, it might be possible to get a well-formed propensity score model without $Z$, in which case it would be sufficient to control for $Z$ by stratifying on it (i.e., including it in the outcome regression model, possibly interacting it with treatment). Indeed, Eeren & de Rooij (2015) found through simulations that even if treatment assignment depended on an effect modifier $Z$, it was preferable to exclude $Z$ from the propensity score model but include it in the outcome model as a treatment effect modifier, just as the authors of the paper you're referencing did.
In general, this is a risky move, and it's theoretically confusing why Eeren & de Rooij found what they did. It may simply be an artifact of their simulation. That said, if one has confidence that $Z$ is not a confounder but is an effect modifier, then there is no requirement to include it in the propensity score model. It goes in the outcome model to estimate the effect modification relationship, but it isn't necessary to additionally control for it through the propensity score.
A major limitation of using the propensity score in a logistic regression model instead of performing matching or weighting is that the estimand is not the average treatment effect in the population. Odds ratios are not collapsible, which means the conditional odds ratio (i.e., when other variables are in a regression model) differs from a marginal odds ratio (when no other variables are in the regression model). Including the propensity score in a logistic regression model for the outcome means the interpretation of the treatment effect is the odds ratio conditional on the propensity score (i.e., for a population held at a given propensity score, what would be the ratio of the odds of the outcome event were the population to be assigned treatment vs. assigned control). Instead using matching or weighting to adjust for confounding and only including the treatment in the outcome model would yield a marginal odds ratio (i.e., for the entire population, what would be the ratio of the odds of the outcome event were the population to be assigned treatment vs. assigned control). The latter is typically what researchers want, which is what motivates using these methods over including the propensity score in the outcome model.
So, the authors took two risks here: first, by not including the effect modifier $Z$ in the propensity score model, they assumed $Z$ was not a confounder or that the results of Eeren & de Rooij justified its exclusion even if it was a confounder. Second, by using covariate adjustment for the propensity score instead of matching or weighting on the propensity score, they assumed the conditional odds ratio (what they got from the regression) was the same as the marginal odds ratio (what they probably wanted to estimate). Many other assumptions were made as well that could severely invalidate the results: they assumed no effect modification by the propensity score, they assumed the correct functional form for the relationship between the propensity score and the outcome, they assumed they had a well-formed propensity score, the list goes on... (and some of these were mentioned by @StatsStudent). In general I would be very wary of the results of this analysis.

Eeren, H. V., & de Rooij, M. (2015). Estimating Subgroup Effects Using the Propensity Score Method. Medical Care, 53(4), 8.
Comment: Excellent addition, @Noah.  Thanks for supplementing here.  I also added a few comments to my original post that address some of the issues raised.
Answer: Using a propensity score in the manner that the authors used it is an incorrect application of the propensity score (this is a very common mistake that researchers do when applying propensity scores and you'll find it all over the medical literature, unfortunately).  Instead, the generated propensity scores should have been used as either weights or used to create strata consisting of patients with similar propensity scores within which separate analyses could be carried out (or other similar matching strategies).
It's hard to say without knowing more about what variable $Z$ is, but there are a few different reasons why one might not include $Z$ in the propensity score model.  When generating propensity scores, one is trying to determine a probability of being assigned to the treatment condition, given covariates that might be correlated with the decision to assign treatment (confounders).  It's possible that variable $Z$ was not a variable that could have affected the treatment assignment (or possibly it was affected by the treatment and not vice versa), and not a covariate that is correlated with treatment assignment, so it would not make sense to include it in a logistic regression model to determine the probability of treatment assignment.
There are several limitations of using logistic regression models to determine propensity scores (as opposed to other methods of propensity score generation).  Two of them are:

It may not be possible to capture complex relationships between the covariates and how they relate to the propensity of being assigned to the treatment group.  For example, there may be complex interactions (e.g. $X_1^4 \times X_5^2$) that are not captured during the modeling process with a large number of covariates.  In other words, it may be difficult and time consuming (another possible limitation) to determine the appropriate functional form of the propensity score model.  Propensity score generation via logistic regression model can also be quite time consuming compared to automted machine learning methods such as Generalized Boosted Methods (GBM) (Ridgeway, 1999).  This itself could be considered a drawback.
Generating propensity scores from logistic regression often calls for including any covariate that could potentially influence the treatment assignment.  This often includes a very large number of correlated covariates that, when combined with few subjects, could make the logistic regression results, typically generated via reweighted least squares, numerically unstable (Ridgeway, McCaffrey, Morral, et al., 2017).

That all being said, it is generally less important what method you use to generate propensity scores than it is determining which covariates are to be used in the propensity score generation (Steiner and Cook, 2013).  In addition, what one should really be paying attention to are the covariance balance score-cards.  The authors should have provided covariate balance diagnostics.  If the authors were able to achieve good balance, then this is quite a good indication that the the propensity scores were well-modeled and achieved the desired result (essentially making the treatment groups comparable).
Finally, if you are interested in a good review of pros and cons of different of the various techniques for the application of propensity scores (e.g. pros and cons of greedy-matching vs. optimal for example) see the article "Methodological Considerations in Implementing Propensity Score Matching" by Haiyan Bai that appears in Chapter 4 of Propensity Score Analysis:  Fundamentals and Developments edited by Wei Pan and Haiyan Bai.  In addition, the article by Garrido, Kelley, Paris, et al. provides a good overview of the pros and cons of different techniques that make use of propensity scores.
Comment: Your points about the difficulties in determining reliable propensity scores are good, but deeming "incorrect" the use of propensity score as a regression covariate is an overstatement. This issue has been examined for example in [this paper](https://www.ncbi.nlm.nih.gov/pubmed/24825821) and Frank Harrell has found inclusion of the logit of the propensity score as a covariate to be useful, as noted [here](https://stats.stackexchange.com/a/115491/28500). When used properly, this can provide a type of double-robustness--with emphasis on "when used properly."
Comment: (1 of 4) I suppose you're right about my use of the term "incorrect." Saying "incorrect" is probably always a bit of a loaded term.  Perhaps I should have simply deemed the method "usually largely biased."

That being said, I don't think either of the papers you cited seem to really be relevant here.  The first paper states that their findings do not apply to non-linear models such as the OP's logistic regression model.
Comment: (2 of 4) Frank's assessment seems to be on the benefit of including the propensity score (PS) and the original covariates in a regression model (without matching) -- a commonly referred to as "double-robustness" (DR). But his work was not an assessment of PS adjustments in regression models vs. matching or weighting (in other words, it doesn't address the issue at hand but addresses the question: given that you are going to use PS adjustment in regression, is there any benefit of performing DR). There's virtually no doubt that DR is a good idea if you are are going to do regression adjustment.
Comment: (3 of 4) [Research by Hade and Lu][1] has shown that there is a definitive bias using the estimated propensity score as a predictor to replace all covariates in the linear model, and in fact, they calculate this bias.  Their simulations show the extent of this bias compared to matching and weighting techniques associated with PS.
[1]: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4004383/#R9 10.1002/sim.5884
Comment: (4 of 4) In most real-world settings it seems that simply including PS in a regression model will result in fairly large biases. It seems it's very rare (if ever) in real-world observational data settings that covariance adjustment with PS results in no (or very little) bias.  Only when coupled with matching does covariate adjustment seem to to result in small biases.
Comment: Useful clarifications, thanks. If you get a chance you might consider incorporating some of this into your answer, as comments can sometimes be lost. Problems that arise in logistic regression that aren't seen in linear regression are particularly worth noting.


Lembrar usuário com segurança

Question: Essa pergunta não se refere a segurança de senhas, ou a criptografia dos dados em si. A questão é mais lógica. Gostaria de saber qual o modo mais seguro de criar aquele esquema "lembrar-me".
Eu estava pensando no seguinte esquema:

Ao autenticar o usuário criar um cookie com ID da sessão.
Salvar o ID da sessão no cadastro do usuário.
Sessão expira em 48h.
A cada acesso atualizar o ID da sessão.

Ou seja, minha ideia era autenticar o usuário baseado em um ID salvo em um cookie no navegador do usuário e no cadastro do usuário no banco de dados, e confirmar se esse ID existe, pois eu acho que salvar o usuário e senha (nos cookies, foi a forma que mais achei na rede para essa questão), mesmo que criptografados com hash e salt e etc, não confio muito.
Gostaria de saber se esse meu método é seguro, quais seriam as possíveis falhas e quais outros métodos eu poderia utilizar, ou como eu poderia melhorar esse meu método.
Comment: P.S. Pergunta relacionada: ["Qual o melhor jeito de fazer um sistema de login em senha com PHP"](http://pt.stackoverflow.com/q/3571/215)
Comment: Isso, é exatamente o "lembrar-me" ou seja, manter a sessão após o fechamento do navegador. Sobre esse salvar a senha, desculpe me expressar mal, mas é que eu pesquisei bastante antes de perguntar aqui, e em todos os locais o pessoal salvava o usuário e senha nos cookies...
Comment: Eu estou confuso em dois pontos na sua pergunta: 1) você está perguntando sobre o "lembrar-me", mas seu protocolo me parece mais um simples meio de manter a sessão (que é igual ao que 99% dos sites usam, aliás). Qual é seu objetivo com esse lembrar-me? É simplesmente que o usuário não deslogue após fechar o navegador? 2) "salvar o usuário e senha (...) não confio muito" A que você se refere? Certamente você tem que salvar isso no BD, de outra forma como você poderia autenticar o usuário? Há meios de se autenticar sem precisar de uma senha salva (certificados, SRP) mas a segurança é +- a mesma.
Comment: De fato, muito embora a senha seja um *segredo compartilhado* entre o usuário e o servidor - de modo que **teoricamente** não teria problema em passá-la de lá pra cá - existem boas razões para não se fazer isso. Dentre elas o fato que os dados do cookie ficam permanentemente salvos no computador do usuário (o ideal é que as senhas só existam em memória, e há muito esforço sendo feito - sem sucesso - para se atingir esse objetivo). Você tem toda razão em não confiar nesse método!
Answer: Alguns itens que devemos tomar cuidado:

Cookies são fáceis de roubar informações
Ataques via falsificação de solicitação entre site ou Cross-site request forgery
Reiniciar a sessão e excluir todos os cookies após alteração de senha, para que tudo possa ser recriado.
Mesmo que o usuário permaneça ativo, solicitar sempre a senha quando envolver transações financeiras.
Nunca armazenar dados de usuários em cookies, como email, senha, cpf, número de cartões, etc.
Não basear a segurança apenas no ID de sessão, pois esse ID tambem pode ser clonado.
Não utilize dados voláteis ou transferíveis como IP para validar um usuário.
Nunca deixar a validade da autenticação eterna.
Forneça uma maneira de o usuário desconectar todos os lugares estiverem com a sessão prolongada.

Pensando nos critérios acima citados, podemos chegar no modelo a seguir e minimizar os riscos.
Gerando o token de autenticação
Precisaremos armazenar tokens da autenticação em nosso servidor, para isso uma tabela semelhante deve ser criada em nosso banco de dados.
 - id           // Um identificador para o token, não utilize auto_increment,
                // pois pode trazer problemas,
 - user_id      // Relacionamento com as informações do usuário
 - token        // Armazena o token de autenticação
 - browser      // Identifica qual browser foi utilizado para autenticar
 - last_access  // Último acesso (timestamp)
 - created_at   // Data de criação (timestamp)

Para gerar o id desta tabela, podemos utilizar algo simples do tipo
md5( uniqid( mt_rand(), true ) );

Nesta solução iremos armazenar tambem o browser utilizado, para dificultar ainda mais as tentativas de ataques, seja por clonagem de sessão, CSRF, ataques automatizados, etc.
No PHP existem funções que facilitam identificar o browser do usuário, mas caso prefira alguma forma alternativa, existem várias na internet. Não importaremos com a versão do browser para evitar erros devido a atualizações automáticas.
Para armazenar o último acesso do usuário, sempre atualize o campo last_access usando a função time().
Para o campo created_at use tambem a função time().
O Token pode ser gerado de forma aleatória, como por exemplo:
sha1( uniqid( mt_rand() + time(), true ) );

Toda vez que o usuário autenticar, iremos gerar um novo e armazenar nesta tabela.
No cookie guardaremos apenas o id do token e o token em si.
$id = md5( uniqid( mt_rand(), true ) );
$token = sha1( uniqid( mt_rand() + time(), true ) );

// Armazenar o token na tabela do banco de dados

$expire = ( time() + ( 30 * 24 * 3600 ) ); // O cookie não deve ser eterno.
$cookieToken = array(
    'i' => $id,
    't' => $token
);
setcookie( 'auth', json_encode( $cookieToken ), $expire, '/', 'www.dominio.com', isset( $_SERVER["HTTPS"] ), true );

Validando o token
No código anterior informamos que o cookie só é válido para determinado domínio, porem isso pode ser alterado. Sendo assim devemos validar de onde está vindo a requisição, e a maneira mais simples de fazer isso é usando a variável $_SERVER['REMOTE_HOST'], o domínio deve ser conhecido.
Após validar a requisição, recupere o cookie, deserialize os dados e valide com o banco de dados.
$tokenData = isset( $_COOKIE['auth'] ) ? json_decode( $_COOKIE['auth'] ) : false;
if( $tokenData !== false ) {
    $id = $tokenData['i'];
    $token = $tokenData['t'];

    // Busque no banco de dados o id e valide o token;
    // Veja tambem a validade do token usando como base o campo 'created_at'
    // e o browser.
    // Se tudo estiver correto, apague este token, gere um novo
    // e inicie a sessão.
}

Incrementando
Para tornar ainda mais seguro, você pode registrar todos os IPs e SESSION_IDs que usaram um determinado token.
Como toda vez que uma nova sessão é iniciada um novo token é gerado, basta gravar em uma segunda tabela o IP que gerou o token e a SESSION_ID, junto destes dados você irá gravar a ultima interação com o seu sistema e o tempo de conexão.
A tabela ficará assim:
 - ip            // Ip do usuário $_SERVER['REMOTE_ADDRE']
 - token_id      // Id do token que foi gerado quando o usuário iniciou a sessão.
 - session_id    // Id da sessão session_id()
 - user_agent    // Informação completa do browser $_SERVER['HTTP_USER_AGENT']
 - time          // Tempo de conexão
 - created_at    // Quando a conexão foi iniciada
 - updated_at    // Última atualização (função time() para toda atualização)

Toda vez que o usuário fizer alguma requisição para nosso servidor com a sessão ativa, iremos atualizar o registro da atual conexão dele, recuperando-a pelo session_id. Se nada for recuperado, a sessão dele é inválida e bloquearemos o acesso.
Para atualizar devemos sempre verificar se o IP e o user_agent são os mesmos, assim como podemos verificar se ele possui o token que foi gerado quando a autenticação foi iniciada.
Para atualizar o tempo de conexão, calcule utilizando o campo created_at
time() - $created_at

Sempre verifique se existe mais de um IP utilizando um token ao mesmo tempo. Isso pode ocorrer quando o provedor do usuário troca o IP e a sessão se mantém ativa.
Se um token possuir requisições de IPs diferentes com um tempo muito curto entre elas, devemos invalidar o token, e redirecionar qualquer requisição ligada a ele para a tela de login.
Observações
Esta maneira possui algumas falhas, mas já dificulta bastante as tentativas de roubo de sessão devido ao fato de o token ser constantemente atualizado.
As requisições de inserção e atualização ao banco de dados vai aumentar bastante para esse modelo. Para evitar problemas, este modelo deve ser baseado em bancos não relacionais ou utilizar uma camada de cache como o memcached, que irá receber todas as requisições e de tempos em tempos, atualizar o banco de dados.
Devemos alertar sempre o usuário quando mais de uma sessão com estiver ativa, e fornecer a possibilidade de invalidar todos os tokens, e realizar o login novamente.
Nunca devemos possibilitar a troca de senha sem ter uma maneira de validar a autenticidade de quem está alterando.
É muito importante alertar ao usuário sobre o uso de cookies e ter uma política bem escrita sobre isso.
Comment: Ops e esqueci, valeu @PapaCharlie. Como no celular não irá possuir sessão ativa, um token novo será gerado só para ele. A implementação não impede que haja mais de um token para um mesmo usuário.
Comment: @mgibsonbr realmente o cookie utilizando HttpOnly fica mais difícil de roubar utilizando javascript, porem em uma requisição que não seja por ajax existem ataques conhecidos como [cookie hijacking](https://en.wikipedia.org/wiki/Session_hijacking), aqui fica difícil explicar. Se for com `Secure` aí é excelente, porem nem todos tem grana pra bancar um certificado digital, etc e tal.
Comment: Ótima resposta, mas gostaria de um esclarecimento sobre os pontos "Cookies são fáceis de roubar informações" e "Não basear a segurança apenas no ID de sessão, pois esse ID tambem pode ser clonado" (pode ser na forma de referências, se uma explicação completa for muito longa pra postar aqui). Que eu saiba, um Cookie `HttpOnly` e `Secure` é muito difícil de ser roubado, talvez exceto por plugins vulneráveis no browser, mas posso estar bastante enganado é claro (por isso gostaria de mais informações). E quanto ao `REMOTE_HOST`, se um atacante roubou o cookie ele não pode forjar isso também?
Comment: Muito bom, mas gerou uma dúvida. Guardar o browser do usuário para validar, pode gerar erro no acesso mobile, não?
Comment: @mgibsonbr O REMOTE_HOST não sei te responder como poderia ser alterado, mas existem algumas outras implementações para validar isso. Em uma pesquisa rápida vi que é possível identificar direto pelo firewall do servidor.
Comment: @PapaCharlie Realmente, aqui só expliquei o funcionamento, mas em minhas implementações eu gravo se é mobile, desktop, tablet, plataforma usada, etc. Para identificar se é mobile, o `user_agent` terá escrito "iPad", "iPod", "iPhone", "Android", e por ai vai, e a função do php nativa, possui formas de te fornecer essa informação. Existem implementações bem completas tambem que extraem tudo isso como essa feita por [Chris Schuld](http://apptools.com/phptools/browser/) ou essa [Jonathan Stoppani](https://github.com/GaretJax/phpbrowscap/blob/master/src/phpbrowscap/Browscap.php)
Comment: Entendi, a ideia é por ai mesmo. O acesso via mobile "geralmente" vai ser o mesmo, então pode-se validar o desktop e jogar o mobile em lista de exceções, sem correr risco de apagar a sessão antiga.
Comment: @marcusagm Valeu pelas referências, vou ler mais sobre o assunto! Perguntei porque - em certas circunstâncias - é desejável se manter **tudo** no cookie (ID e variáveis da sessão, assinados é claro, e talvez cifrados) para evitar que cada requisição gere um hit no BD. Não é um solução aplicável a todos os casos, mas quando o é, pode dar uma melhora significativa na performance. Isso se chama "cookie-based sessions", aqui tem uns exemplos (não em PHP): https://docs.djangoproject.com/en/1.7/topics/http/sessions/#using-cookie-based-sessions http://security.stackexchange.com/q/14193/6939
Comment: E, embora não se trate exatamente do mesmo conceito, [essa resposta do Tom Leek no security.SE](http://security.stackexchange.com/a/10586/6939) descreve bem as implicações que isso tem na segurança (o primeiro link que passei acima também dá alguns alertas). Reiterando: não é uma solução pra todos os casos, tem hora que é aplicável e tem hora que não é. E obviamente, pra isso funcionar o `HttpOnly` e o `Secure` são obrigatórios... (P.S. hoje em dia obter um certificado não é tão caro, e quem não tiver um está vulnerável a MitM durante o login de qualquer forma)

Lembrar usuário com segurança


Complex integral

Question: Let $C$ denote the unit circle  centered at the origin in Complex Plane
What is the value of
$$ \frac{1}{2\pi i}\int_C |1+z+z^2 |dz,$$ where the integral is taken anti-clockwise along $C$?

0
1
2
3

What I have answered is 0 because it seems like $f(z)$ is analytic at 0 hence by Cauchy's Theorem.
Comment: Be careful! $z\mapsto |1+z+z^2|$ is real-valued and not constant and therefore not holomorphic!
Comment: $|z|$ is not analytic at 0
Comment: Numerically integrating seems to give $\approx 0.6$
Comment: Possible duplicate of [To compute $\frac{1}{2\pi i}\int_\mathcal{C} |1+z+z^2|^2 dz$ where $\mathcal{C}$ is the unit circle in $\mathbb{C}$](https://math.stackexchange.com/questions/2329248/to-compute-frac12-pi-i-int-mathcalc-1zz22-dz-where-mathcalc)
Comment: @LutzL Actually, it's not a duplicate; the results are different, although the methods are similar. I have provided solutions to both of them. Also, none of the choices in the OP are correct, as also noted by user399601. See my solution below.
Comment: Yes, I see, the square is missing. It should be obvious from the provided results and the topic, complex analysis, that this is a typo, the only interesting question is if this was already wrong in the original task or only here in the question.
Answer: HINT
Note that if $z = x+yi$ then
$$
\left|1+z+z^2\right|
  = \left|\left(x^2-y^2+x+1\right) +y(2x+1)i\right|
$$
Now parameterize $C$ as $x = \cos t, y = \sin t$ and $t \in [0,2\pi]$, then
$$
\int_C |1+z+z^2 |dz
  = \int_{t=0}^{t=2\pi} \left|\left(x^2-y^2+x+1\right) +y(2x+1)i\right|
$$
where $x,y$ are functions of $t$ as in the parameterization. Can you finish this?
Answer: Put $z=e^{it}, 0\le t\le 2π$ and $dz=i.e^{it}dt$.
So $I_1=\int_0^{2π}|1+e^{it}+e^{i2t}|^2ie^{it}dt=i\int_0^{2π}(1+e^{it}+e^{i2t})(1+e^{-it}+e^{-i2t})e^{it}dt$
$=i\int_0^{2π}g(t)dt$, where $g(t)$ is the integrand and $g(2π+t)=g(t)$. So $I_1=...$
Comment: Why do you put a square on the absolute value? It wasn't there to begin with.
Comment: Cye Waldman..I misread it..
Answer: We want the integral
$$\frac{1}{2\pi i}\int_C |1+z+z^2|dz=\frac{1}{2\pi}\int_0^{2\pi}|1+z+z^2|z~d\theta$$
since $z=e^{i\theta}$.
Now consider the absolute value portion,
$$
\begin{align}
|1+z+z^2|
&=\sqrt{(1+z+z^2)(1+z+z^2)^*}\\
&=\sqrt{(1+z+z^2)(1+z^{-1}+z^{-2})}\\
&=\sqrt{(1+z+z^2)(1+z^{-1}+z^{-2})\frac{z^2}{z^2}}\\
&=\sqrt{\left(\frac{1+z+z^2}{z} \right)^2}\\
&=\sqrt{\left(\frac{1}{z}+1+z \right)^2}\\
&=\sqrt{(1+2\cos\theta)^2}\\
&=|1+2\cos\theta|
\end{align}
$$
We can return to solve the integral
$$
\begin{align}\frac{1}{2\pi i}\int_C |1+z+z^2|dz
&=\frac{1}{2\pi}\int_0^{2\pi}|1+2\cos\theta|(\cos\theta+i\sin\theta)~d\theta\\
&=\frac{1}{2\pi}\int_0^{2\pi}|1+2\cos\theta|\cos\theta~d\theta\\
&=\frac{1}{3}+\frac{\sqrt{3}}{2\pi}\approx0.60900
\end{align}$$
This is in agreement with our own numerical solution as well as that of others noted previously.

Complex integral


Manipulação de Txt - Separar blocos com base em um padrão

Question: Eu possuo um txt com algumas informações. O txt segue o seguinte padrão:
1 - Inicio do bloco
2 - Informação
3 - Descrição da linha 2
Então, por exemplo
190845 3890580235203895 0329045832854880328 58908349058340534859 hjdfhgjdfhg dgfdgdf
22343 34234234 324234 324234234 234234 342324989856475959596
3SHDSHFUHDSFUHSDUFHSHDFUDSFDSTTJKKHGHJMNMNBN
22343 34234234 324234 324234234 234234 342324989856475959596
3SHDSHFUHDSFUHSDUFHSHDFUDSFDSTTJKKHGHJMNMNBN
22343 34234234 324234 324234234 234234 342324989856475959596
3SHDSHFUHDSFUHSDUFHSHDFUDSFDSTTJKKHGHJMNMNBN
120845 3890580235203895 0329045832854880328 58908349058340534859 hjdfhgjdfhg dgfdgdf
22343 34234234 324234 324234234 234234 342324989856475959596
3SHDSHFUHDSFUHSDUFHSHDFUDSFDSTTJKKHGHJMNMNBN

O que eu preciso é separar em varáveis diferentes os blocos sabendo que eles iniciam em 1 e terminam na próxima incidência de 1. O exemplo acima ficaria:
a = '190845 3890580235203895 0329045832854880328 58908349058340534859 hjdfhgjdfhg dgfdgdf
22343 34234234 324234 324234234 234234 342324989856475959596
3SHDSHFUHDSFUHSDUFHSHDFUDSFDSTTJKKHGHJMNMNBN
22343 34234234 324234 324234234 234234 342324989856475959596
3SHDSHFUHDSFUHSDUFHSHDFUDSFDSTTJKKHGHJMNMNBN
22343 34234234 324234 324234234 234234 342324989856475959596
3SHDSHFUHDSFUHSDUFHSHDFUDSFDSTTJKKHGHJMNMNBN'

b = '120845 3890580235203895 0329045832854880328 58908349058340534859 hjdfhgjdfhg dgfdgdf
22343 34234234 324234 324234234 234234 342324989856475959596
3SHDSHFUHDSFUHSDUFHSHDFUDSFDSTTJKKHGHJMNMNBN'

Tentei fazer combinando while + readline + startswith, mas não consegui
Comment: @AndersonCarlosWoss tua dica ajudou muito !!
Comment: Pode aparecer o valor 1 em qualquer lugar da linha, dentro da informação, ou sempre o 1 representará início do bloco?
Comment: Olá Anderson! Quanto tempo ! Então, o 1 pode aparecer em qualquer lugar do arquivo, mas o 1 que representa o inicio do bloco sempre será na posição 1 da linha
Comment: eu havia tentado o line.startswith("1"), mas para manipular o bloco inteiro ficou inviável
Comment: [Assim](https://repl.it/HmUX) que você fez? Acho que com expressão regular consegue fazer uma solução melhor, mas não consigo pensar em nada neste momento.
Answer: Você consegue utilizar a seguinte expressão regular:
^1 - Onde o ^ indica o inicio de uma linha seguido do caracter que você esta buscando no caso o 1. Fiz um exemplo que faço o split do texto utilizando expressao regular e após isto volto concatenando cada item com o 1.
Para montar a expressão regular gosto de utilizar o Rubular
Codigo: repl
import sys
import re

FINDER = "1"
# [(^1)]
# http://rubular.com/r/Sx8PL2qdR8
REGEX = '[(^' + FINDER + ')]'

if __name__ == '__main__':
    content = """190845 3890580235203895 0329045832854880328 58908349058340534859 hjdfhgjdfhg dgfdgdf
    22343 34234234 324234 324234234 234234 342324989856475959596
    3SHDSHFUHDSFUHSDUFHSHDFUDSFDSTTJKKHGHJMNMNBN
    22343 34234234 324234 324234234 234234 342324989856475959596
    3SHDSHFUHDSFUHSDUFHSHDFUDSFDSTTJKKHGHJMNMNBN
    22343 34234234 324234 324234234 234234 342324989856475959596
    3SHDSHFUHDSFUHSDUFHSHDFUDSFDSTTJKKHGHJMNMNBN
    120845 3890580235203895 0329045832854880328 58908349058340534859 hjdfhgjdfhg dgfdgdf
    22343 34234234 324234 324234234 234234 342324989856475959596
    3SHDSHFUHDSFUHSDUFHSHDFUDSFDSTTJKKHGHJMNMNBN"""

    splitted = re.split(REGEX, content)

    #Verifica e faz a remoção do primeiro item se for vazio
    if splitted[0] == '':
        splitted = splitted[1:]

    #Recupera todos os item juntando com o caracter inicial
    result = []
    for split in splitted:
        result.append(FINDER + split)

    #Exibe o resultado
    print(len(result))
    for r in result:
        print("----> " + r)


How convergence relates to equivalence of norms

Question: Let $X$ be a normed linear space with two norms $||\cdot||_1$ and $||\cdot||_2$.
Prove or disprove that this statements are equivalent:

$||\cdot||_1$ and $||\cdot||_2$ are equivalent,
$\{x_n\}$ converges in $||\cdot||_1$ iff $\{x_n\}$ converges in $||\cdot||_2\;\; $   $\forall \{x_n\}\in X$

The first implies the second trivially because of equivalence of topologies. But it implies something more: sequence converges to the same element in both norms. But I don't have such condition.
Is this a necessary condition to converge to the same in both norms, or this is just a consequent of "if and only if" in the statement of convergence, or there is a example disproving the equivalence?
Answer: Suppose $\|\cdot\|_1$ and $\|\cdot\|_2$ are inequivalent, so one is unbounded with respect to the other; WLOG $\|\cdot\|_2$ is unbounded with respect to $\|\cdot\|_1$.  That means you can find a sequence $x_n$ with $\|x_n\|_1 \leq 1$ for all $n$ but $\|x_n\|_2 \geq n$.  Let $y_n = \frac{x_n}{\sqrt{n}}$.  Then $y_n \to 0$ in $\|\cdot\|_1$, but $\|y_n\|_2 \to \infty$.  So, for inequivalent norms you can always find a sequence which converges to 0 in one norm, but goes to infinity (hence doesn't converge to anything) in the other.
Answer: So, in addition to Dave's answer, here is a more geometric perspective.
Norms are uniquely defined by their convex unit balls, and they are equivalent if you can fit the unit ball of one norm inside that of the other norm, and vice versa. Also since you can freely translate things in a vector space, there is no loss of generality in assuming that $x_n \rightarrow 0$.
So, with this understanding you can imagine starting with a ball in norm A centered at 0, putting a smaller scaled unit ball of norm B inside it, then a smaller one of norm A inside that, then B inside that, etc, ending out with a nested series of convex shapes, ABABAB... getting smaller and smaller, with scaling factors going to 0.
The sequence $x_n$ converges to zero for norm A if every one of these A-balls contains a tail of the sequence (and likewise for norm B). Since the balls are nested A inside B inside A, .., if it converges in one norm it has converge in the other.


Is there a way to output a (symbolic) matrix equation in matlab similar to one in LaTex?

Question: I was wondering if there was a way to use defined Matrices to print them in an expression either using live editor or the normal editor. I was hoping to get my output to look similar to the image I have attached. I am hoping to get that as an output, but can only get individual matrices per line with the 'ans =' in between
Answer: My solution is also a workaround but I think it works in a better way:
clear
syms x y z

% create symbolic variables (could be calculated also)
A = sym([-2  1 -3; -3  2 -2; -1 -3 -1])
b = [x; y; z]
v = sym([-3; -4; 3])

% convert to latex strings
A_str = latex(A)
b_str = latex(b)
v_str = latex(v)

my_Eqn = append(A_str, b_str, " = ", v_str)  % create desired line

% replace [ and ] since "MATLAB Latex" does not seem to support them
% and add $-signs to mark it as a Latex string
my_Eqn = "$" + replace(my_Eqn,["[";"]"], ["(";")"]) + "$"

figure(1); clf; hold on  % create figure
text(0, 0.5, my_Eqn, 'interpreter', 'latex', 'FontSize', 20)  % write text
set(gca,'visible','off')  % remove axis

Output:

The downside is the size of the figure and the space that is wasted in this way.
It is also to mention that precalculated fomulas can be inserted in the LIVE EDITOR. Just convert one line  to "Text" and under INSERT > Equation an equation can be pasted (even latex)
Answer: *In Progress: Inviting anyone to build upon this and edit as they please.
Code so far:
This example uses a .mlx live script. Casting the matrices as sym, symbolic matrices will force the output to display brackets. To configure the output to display square brackets the sympref(), symbolic preferences function can be called to set the 'MatrixWithSquareBrackets' to true.

sympref('MatrixWithSquareBrackets',true);
syms x y z
Matrix_1 = sym([-2  1 -3; -3  2 -2; -1 -3 -1]);
Matrix_2 = [x; y; z];
Matrix_3 = sym([-3; -4; 3]);

disp(Matrix_1); disp(Matrix_2); disp("="); disp(Matrix_3);


How to find an object by id?

Question: I have this collection of objects:
const objects = [
  { id: '11', name: 'ron', surname: 'lesner', group: 'A' },
  { id: '12', name: 'don', surname: 'lesner', group: 'B' },
  { id: '13', name: 'ton', surname: 'lesner', group: 'A' },
]

I need to return the object with matching id using Lodash.
The following code returns undefined:
_.find(object, id, 11);

I'm expecting this result:
{ id: '11', name: 'ron' , surname: 'lesner' , group: 'A' }

Answer: You need to pass '11' - string representation of the 11 number, because your id is of type string. With Lodash#find

const object = [
     {id: '11', name: 'ron' , surname: 'lesner' , group: 'A'},
     {id: '12', name: 'don' , surname: 'lesner' , group: 'B'},
     {id: '13', name: 'ton' , surname: 'lesner' , group: 'A'}
];

const found = _.find(object , ['id', '13']);

console.log(found);

Also you can use pure Javascript instead of lodash?

const object = [
     {id: '11', name: 'ron' , surname: 'lesner' , group: 'A'},
     {id: '12', name: 'don' , surname: 'lesner' , group: 'B'},
     {id: '13', name: 'ton' , surname: 'lesner' , group: 'A'}
];

const found = object.find(item => item.id === '11');

console.log(found);
Comment: actually I am coding in Typescript so wondering if any new design pattern will be seen.it is okay with javascript also.
Comment: Is this a lodash? ._find is not used.
Comment: I need to use lodash function only
Comment: @Aditya See updated. I have provided lodash version
Comment: okay..will try and update.
Comment: found = undefined I am getting
Comment: See my examples
Comment: I tried const `found = _.find(object , 'id', '13');` it returns me the first object always..and not actual 13th one
Comment: and using with`found = _.find(object , ['id', '13']);` return as undefined
Comment: Work with my examples. Something wrong is in your local
Answer: You are not using the lodash find function in accordance with hiw its intended to be used. Please check source code and coments at https://github.com/lodash/lodash/blob/master/find.js
Also for something so trivial it can be argued that you should better use the native array functions if you cannot motivate library use with the need for extreeme performance or other reasons; and also dont call an array Object. It will make your code confusing.

How to find an object by id?


Can we make witnesses for membership of $\Sigma_2$ sets unique?

Question: A $\Sigma_2$ set $A$ is one for which there is a computable relation $R(x, s, t)$ s.t. $x \in A \iff \exists s \forall t \colon R(x, s, t)$.
Can we use $R$ to produce another computable relation $Q$ determining membership of $A$ in the same fashion, but where $S_Q(x) = \{ s \ | \ \forall t \colon Q(x, s, t) \}$ (the set of witnesses for $x$ wrt $Q$) has a unique element?
The best I have so far is that if there is some computable $f$ s.t. $f(x) \in S_R(x)$ whenever $S_R(x)$ is non-empty, we can get the result by sabotaging the cases where $s \neq f(x)$. But I don't see how I can construct such $f$ or otherwise argue one exists.
Comment: You will not be able to build such an $f$ in the general case. (A would only be $\Pi_1$ if you can)
Answer: You can compute such a "unique witness" $Q$ from $R$, using that pseudo-python code :
<code>def Q(x,s,t) :
    r,u,a=0,0,False
    for i in range(s) : # repeat s times
        a=R(x,r,u)
        if a : u+=1
        else : r+=1
    if a : return False
    else : return R(x,r,t)
</code>
Comment: While trying to understand the strategy of your answer, I arrived at a similar solution myself (I'm writing up my own answer), so thanks—but I don't think this is quite right. The for-statement looks through values of $s$ (I.e. $r$) for a current best guess at the first witness, and if its guess is wrong then no harm is done. If one exists then it eventually finds the first witness $s$, and $r$ never exceeds this value, so from then on the for-loop exits with $a$ true. Then it always returns False from this point on, so there can be no witness at all.
Comment: @G.H.Faust I'm not sure what's wrong with my answer. Once you find a potential witness 's', yes, all subsequent witnesses are False, to make 's' unique. It doesn't prevent Q to have that witness. So I don't understand your comment. For example if $R(x,0,n)$ only fails for $n=10$ but $R(x,1,n)$ is always true for all $n$, then $Q(0,x,y)=R(0,x,y)$ $Q(x,n,z)$ fails for all $0<n<11$ (and for all $z$) and $Q(11,x,y)=R(1,x,y)$ and then $Q$ has a unique witness $11$.
Comment: Ah, I see now—the value of $a$ is always assigned _before_ $r$ is incremented, so it lags one behind, and consequently the for-loop does not exit with $a$ true the very first time it finds a new witness.
Answer: A strategy to compute such a $Q(x, s, t)$ is as follows.
First check $R(x, 0, 0)$. If it holds, bump up the last entry by $1$, and check again. If it doesn't hold, set the last entry to $0$, and bump up the second entry by $1$. Repeat this $s$ times. The process we are undertaking is making a "best guess" at a witness (sitting in the second entry of our last $R(x, \cdot, \cdot)$ call). In short, we are guessing the least $s$ for which $R(x, s, t)$ has held for all $t$ checked so far. If there is a witness, we will eventually find the first one, and never change our guess.
So, we have our guess at the witness $s_0$. If when computing $Q(x, s-1, t)$ we arrive at the same guess, then $Q(x, s, t)$ does not hold. Otherwise, $Q(x, s, t) = R(x, s_0, t)$.
So if a witness does not exist for $x$ wrt $R$, then $Q$ does not find one either. If one does, then eventually at some $s_1$ we guess the right witness for the first time, and $s_1$ is then a witness for $x$ wrt $Q$. But our guess at the first witness never changes after this, so for $s>s_1$, computing $Q(x, s, t)$ finds that we used the same guess $s_0$ as when computing $Q(s, s-1, t)$, and as such, does not hold. Hence $s_1$ is a unique witness.


For a model like this what performance measures can I calculate and how?

Question: Methods:
From the machine learning literature, I understand different parameters can show performance of model in machine learning. I would briefly expand my understanding with confusion matrix:

(1) Accuracy: measures the proportion of correct predictions considering the positive and negative inputs.
(2) Specificity: measures the proportion of the true negatives, that is, the ability of the system on predicting the correct values for the cases that are the opposite to the desired one.
ROC curve: Considering many thresholds, it is possible to calculate a set of pairs (sensitivity, 1-specificity) which can be plotted in a curve.  This curve will be the ROC curve for the system where the y-axis (ordenades) represents the sensitivity and the x-axis (abscissas) represents the complement of specificity (1 - specificity).
area under the ROC Curve (AUC) - higher the ROC curve's area, better the system.
(3) Sensitivity: measures the proportion of the true positives, that is, the ability of the system on predicting the correct values in the cases presented.
(4) Efficiency: mean of Sensibility and Specificity
(5) Positive Predictive Value: the estimation of how good the system is when making a positive affirmation - POSITIVE HITS / TOTAL POSITIVE PREDICTIONS
(6) Negative Predictive Value: measure indicates the estimation of how good the system is when making a negative affirmation - NEGATIVE HITS / TOTAL NEGATIVE PREDICTIONS
(7) Phi (φ) Coefficient
My data
I have quantitative y variable with many x quantitative variables and fit a lear regression equation. Objective here is how closely x values predict y - means that deviation from expectation in both negative and positive direction is not good.
#random population of 200 subjects with 1000 variables

M <- matrix(rep(0,200*100),200,1000)
for (i in 1:200) {
set.seed(i)
  M[i,] <- ifelse(runif(1000)<0.5,-1,1)
}
rownames(M) <- 1:200

#random yvars
set.seed(1234)
u <- rnorm(1000)
g <- as.vector(crossprod(t(M),u))
h2 <- 0.5
set.seed(234)
y <- g + rnorm(200,mean=0,sd=sqrt((1-h2)/h2*var(g)))

myd <- data.frame(y=y, M)

Let's say I want to fit ridge and lasso to this:
 require(glmnet)

   # LASSO
   fit1=glmnet(M,y, family="gaussian", alpha=1)

   # Ridge
   fit1=glmnet(M,y, family="gaussian", alpha=0)

Question:
What performance measure listed above (or not listed) are relevant here and how can I calculate them?
Answer: Being that you're facing a regression task, the metrics above are not appropriate: They're for assessing classifier performance. The scikit learn metrics documentation provides a handy, quick reference that nests metrics under their appropriate problem types.
In regression, mean squared error (MSE) is the classic measure. You may calculate this by taking the difference of each prediction and actual value, squaring them, and taking the mean of all values. Another measure is the mean absolute error (MAE), which is less prone to outliers. It is calculated by taking the absolute value of the errors, rather than squaring them. Lower is better in both cases, and here's a basic example:
# Suppose that:
#  yTest is your hold-out set for cross-validation
#  Your model was trained using xTrain and yTrain
#  fit1.predictions holds the predictions from using your fitted model on xTest
fit1.meanSquaredError = mean((yTest - fit1.predictions) ^ 2)
fit1.meanAbsoluteError = mean(abs(yTest - fit1.predictions))

Many ML packages calculate this for you, and let you select which to use for cross-validation. From the documentation, for glmnet uses MSE for cross-validation by default, with the option of MAE. (See type.measure on p. 4.)