$X^n$ where $X$ is normally distributed?

Question: Suppose $X \sim N(\mu, \sigma^2)$, is there a general way to describe the distribution (i.e. mean, variance, ...) of $Y=X^n$ for some constant $n$?
(assume $\mu \in (0,1)$ and somehow $X \in (0,1)$ most of the times if this makes it any easier)
Furthermore, how does $n$ affect the probability that $Y$ falls within a fixed interval, say $\pm\delta$, around its mean?
My intuition is that as $n$ increases, the distribution should become more condensed and thus has smaller variance, and overall the probablity should increase since the interval spans larger portion of the PDF?
Comment: If $\mu=0$ then for even $n$ this can be described by a [generalized gamma distribution](https://en.m.wikipedia.org/wiki/Generalized_gamma_distribution). You could use rules for transforming variables to get the PDF and compare it with formulas for the mean and variance of that distribution to get to know the behaviour at larger $n$.
Comment: @GrumpyCivet, thanks. It depends on whether the interval contains zero or not. This is an interesting problem. Intuitively, and informally, in the limit, the distribution will be a mixture of a point mass at infinity (all the mass outside [-1,1] get mapped there) and a point mass at zero (all the mass in (-1,1) gets mapped there). I don't know how to formally describe it and it seems that formally the distribution does not converge.
Comment: Welcome to CV, Grumpy Civet. I like this question.
Comment: Not sure what this means "overall the probablity should increase ... ".
Comment: @passerby51p sorry for the confusion! here the probability is just the probablity that $Y$ falls within a fixed interval
Comment: You could describe the moments of $X^n$ in terms of the moments of $X$. The mean of $X^n$ will be the $n$-th moment of $X$, the 2nd moment of $X$ will be the $2n$-th moment of $X$, and the variance will be the 2nd moment minus the square of the mean.
Comment: @passerby51 thanks so much I'm still digesting your answer. Would it help if we only look at the part within (0,1) open? and the fixed interval should always be round mean of $Y$.
Comment: @GrumpyCivet, not sure if I understand what you mean. You can decompose $Y$ into two pieces. I will edit my response to add more details. The mean of $Y$ doesn't seem to be that central to the question. If you look at a fixed interval around the mean that does not include zero, then the probability of falling in that interval decreases. (The probability of falling within any interval not containing zero decreases.)
Comment: @passerby51p thanks! I meant to restrict with the assumption that $\mu$ is within (0,1) and restrict $X$ to (0,1) as well. then wouldnt the probability of falling within such an interval increase in $n$?
Comment: @GrumpyCivet, please see my updated response for how restricting $X$ can be used. Restricting $\mu$ doesn't seem to matter much. The same happens more or less even if $|\mu| > 1$.
Answer: Let $Z_n := Z := g(X) := n X^n$. The relation between $Z$ and $Y$ is quite simple (one is a scaled version of the other). Let's figure out the distribution of $Z$. Assume for simplicity that $n$ is odd. Then, $g^{-1}(z) = (z/n)^{1/n}$. Hence, $|{g^{-1}}'(z)| = \frac1n (|z|/n)^{1/n-1}$.
It follows that the density of $Z$ is
$$
 f_{Z_n}(z) = f_X(g^{-1}(z)) |{g^{-1}}'(z)| = \frac{n^{1/n}}{\sqrt{2\pi}} |z|^{\frac1n-1} e^{-(z^{1/n} n^{-1/n} - \mu)^2/(2\sigma^2)}
$$
Since $n^{1/n} \to 1$ and $|z|^{1/n} \to 1$ for all $z \neq 0$, the density pointwise converges to
$$
f_{Z_n}(z) \to \frac{1}{2\pi} e^{-(1-\mu)^2/2(\sigma)^2} |z|^{-1}, \quad z \neq 0
$$
which might be a good approximation for large $n$ (EDIT: it turns out it is not in general! See the edit.). Note, however, that this limit is not a density since it does not integrate to something finite. (Formally, one might be able to show that the distribution of $Z_n$ converges to a point mass at zero, in "some" sense. However, there is some mass that escapes to infinity, anything above 1 basically. So needs some care and the result might not be true. Informally, the limiting distribution is a mixture of a point mass at 0 and two point masses at $\pm \infty$ for $n$ odd.)

EDIT: Assume $n$ is odd. To clarify the situation, Let  $X_1 := X\cdot 1_{\{|X| \le 1\}}$ and $X_2 := X\cdot 1_{\{|X| > 1\}}$ where $1_{\{|X| \le 1\}}$ is 1 if $|X| \le 1$ and zero otherwise and similarly for the other indicator function. We have $X = X_1 + X_2$ with $|X_1| \le 1$ almost surely and $|X_2| > 1$ almost surely. It is not hard to see that
$$
Y_n := X^n = (X_1 + X_2)^n = X_1^n + X_2^n.
$$
with $|X_1^n| \le 1$ and $|X_2^n| > 1$ a.s.
Assuming that $X$ has a continuous distribution (so that $\mathbb P(X=1) = 0$), it is not hard to see that $X_1^n$ converges in distribution to a point mass at 0. However, $X_2^n$ does not converge in distribution. In fact, it should be straightforward to show that
$$ P(X_2^n \in (0,t)) \to 0, \quad \text{as}\; n\to \infty$$ for any finite $t > 0$. This is what  can be informally described as "the mass in the distribution of $X_2^n$ is escaping to infinity".
Since we also have $\mathbb P( X_1^n \in (s,\infty)) \to 0$ for any $s > 0$, it follows that $\mathbb P(Y_n \in (s,t)) \to 0$ for any $t > s > 0$. The only intervals that will have positive mass in the limit are those that contain 0. That is, if $I$ is an interval with $0 \in I$, then
$$
P(Y_n \in I) \to P(|X| \le 1), \quad \text{as}\; n \to \infty.
$$
Otherwise (that is, if $0 \notin I$), we have $\mathbb P(Y_n \in I) \to 0$.
Comment: The pointwise limit of the densities is a truly terrible approximation.  To see why, consider that the chance $|X|$ exceeds $1$ is positive (it's equal to $2\Phi(-1)$) and this is the limiting chance that $|X|^n$ exceeds $T$ for *any* positive threshold $T.$  That should make it obvious that much of the support of $X^n$ travels out towards infinity and that the sequence of variances diverges.
Comment: I think that the problem with a formal statement is that you describe the convergence of $f_{Z_n}$. But the cumulative distribution function $F_{Z_n}$ does not converge (not uniformly), so there is no convergence in distribution.
Comment: @whuber, I should add that in some cases it could be a reasonable approx., e.g., if much of the mass of X is concentrated in [-1,1], for example when $X \sim N(0.5, 0.01)$. This seems to be what OP has in mind in their problem statement. Although, there is going to be always a constant approx. error in the limit.
Comment: So everything of $\vert X \vert$ below 1 will approach 0 and everything of $\vert X \vert$ above 1 will approach infinity (but because this part that approaches infinity spreads out the density goes to zero).
Comment: @SextusEmpiricus, that should be what happens. The mass between [0,1] gets pulled towards zero and the mass above it gets pulled towards infinity.
Comment: @SextusEmpiricus, yes, that is the case. Convergence in distribution seems to fails. Still it would be interesting to somehow describe an approximation for large "n" (if at all possible). The mass that escapes to infinity causes the tail of the distribution of $Z_n$ to get heavier  and heavier as $n$ increases.
Comment: @whuber, thanks. I agree. I edited the answer to point that the approximation by the limiting density is problematic.
Answer: Far from an answer in general, but there is a formula for $\text{E}[X^n]$ if $\mu=0$. Then we have
$$
  \text{E}[\text{X}^n] = \begin{cases}0\,, & n \text{ odd }\\ \sigma^n(n-1)(n-3)\cdot\ldots\cdot 1\,, & n \text{ even }\end{cases}
$$


Personal Virtual Desktop Collection: User Assignment

Question: Using Windows Server 2012 Remote Desktop Services, I have a 'Personal Virtual Desktop Collection' with automatic user assignment enabled.
According to Microsoft "Personal virtual desktops are permanently assigned to a user account and the user logs on to the same virtual desktop each time."
Is there a way either through the Server Manager UI or PowerShell to determine which user has been assigned to which VM?
The only way I have found so far is to query the 'Remote Desktop Users' group on each VM in the collection, however that requires each VM to be powered on. There must be a better way.
Answer: Two ways.
PowerShell Module:
From a Windows 8/Windows Server 2012 machine in PowerShell you should be able to use the Get-RDPersonalVirtualDesktopAssignment command. You can specify a connection broker to connect to with -ConnectionBroker <String>, or query by collection and user.
Active Directory:
You may be able to find the information in Active Directory if Windows Server 2012 maintains the same schema as in 2008 R2, you may be able to find it by querying users for the msTSPrimaryDesktop attribute. To search by attribute in PowerShell, on Windows 7/2008 R2 and previous versions you may need to first run Import-Module ActiveDirectory, and then execute the command:
Get-ADUser -Properties msTSPrimaryDesktop -Filter  { msTSPrimaryDesktop -like "*" }
The msTSPrimaryDesktop property is used in VDI in Windows Server 2008 R2 at least, and is also accessible on certain machines via Active Directory Users and Computers (dsa.msc). I am not sure if Windows Server 2012 uses this property as a user's primary desktop may be relative to a particular collection, not global as per 2008 R2.


Scanning QR code from screen

Question: I'm trying to read a QR code that appears on the device screen but I cannot find any library that does it without taking a screenshot first.
I know that using zxing it is possible to scan the QR code from an image, but is there any way to do the scan on runtime when the QR code appears in the device screen?
Comment: Can you generate the image programmatically then send it to zxing? https://stackoverflow.com/questions/2661536/how-to-programmatically-take-a-screenshot-in-android
Answer: You might try Google's Mobile Vision API.
The detect method only requires a Frame, which you can build from a Bitmap.
Answer: Consider generating the screenshot programmatically (https://stackoverflow.com/a/5651242/1240523), loading the image as a bitmap and using that in conjunction with zxing.
Answer: There's a project which allows this called Zxing Android Embedded. Take a look at the Embedding documentation.
There's also an Activity which they provide as a sample using their DecoratedBarcodeView.
It's embedded, and can be added in the XML as shown here, namely:
    <com.journeyapps.barcodescanner.DecoratedBarcodeView
        android:id="@+id/barcode_scanner"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_above="@+id/buttonsLayout"
        android:layout_alignParentTop="true">

Scanning QR code from screen


Fixed effects vs random effects when assumption of strict exogeneity holds

Question: I have trouble understanding the following exercise:
Assume a setting in which the assumption of strict exogeneity holds, but
random effects estimation and fixed effects estimation give very different parameter
estimates. Which estimates do you trust most? Briefly explain why.
My answer to this question was that we should trust the random effects model, because $\sigma_{RE}$ is smaller than $\sigma_{FE}$ in the case of strict exogeneity right?
The correct answer to the question however is:
Trust the fixed estimation because the covariates are correlated to the fixed effects
Q: Why would we trust fixed effects instead of random effects in this case? (I don't understand the explanation given).
Comment: what is assumption of strict exogeneity ?
Comment: Possible duplicate of http://stats.stackexchange.com/questions/188349/use-of-fixed-effects-and-random-effects/188430#188430
Answer: You would trust the Fixed Effects because it is consistent under weaker assumptions. This is not about the efficiency so the fact that variance is smaller is secondary. If the estimates are different, chances are strict exogeneity is violated and RE becomes biased, while FE remains consistent even without strict exogeneity.


Inequalities and rearrangements

Question: Some children are arranged in two rows, so that each child in the front row is taller than the child behind him in the back row. The children are now rearranged in increasing order in each row. Show that in the new arrangement  each child in the front row is taller than the child behind him.
Reformulation: consider two $n$-uples of (positive) numbers $(a_1, \ldots, a_n)$ and $(b_1, \ldots, b_n)$ such that $a_i \ge b_i$ for all $1\le i \le n$. If $(a'_1, \ldots, a'_n)$ and $(b'_1, \ldots, b'_n)$ are the increasing rearrangements of $(a_1, \ldots, a_n)$ respectively $(b_1, \ldots, b_n)$ then  $a'_i \ge b'_i$ for all $1\le i\le n$.
I was told that the statement is obvious. Is it? It is fairly easy to see that $a'_1 \ge b'_1$, and also that $a'_n \ge b'_n$, but it does not seem obvious for other values of $i$.
Answer: Take the smallest child of the front row and the smallest child of the back  row (which clearly is the smallest of all childs) both "out of competition". Is it possible to rearrange the rest of the children in such a way that each child stays in the same row and again each child in the (new) front row is taller than the child behind him in the (new) back row? If so then you are done with induction. If the two children mentioned were allready originally in the same column then the answer is clearly "yes": all children (except the two that were taken out) take their original positions. If not then the situation is even more favourable. The child in the front and originally in the same column as the smallest child in the back will be taller than the smallest child in the front hence will be taller than the child behind the smallest child in the front. So these two children are placed in a column. The other children just take their original places.
Answer: Look at it inductively.  The shortest kid in the front ($a'_1$) is clearly taller than the shortest kid in back ($b'_1$) . Why?  Well, $a'_1$ was taller than some kid in back and that kid had to be at least as tall as $b'_1$.
Now, suppose (inductively) that we are done for the first $i-1$ kids.  Look at the original configuration.  If $a'_1, ...a'_{i-1}$ originally were in front of the list $b'_1, ...b'_{i-1}$ (in any order) then clearly the kid $a'_i$ was originally in front of someone no shorter than $b'_i$.  Alternatively, suppose that at least one of $a'_1, ...a'_{i-1}$ was in front of some b other than one of $b'_1, ...b'_{i-1}$.  But that would mean that there were more than $i-1$ kids in the back row shorter than $a'_{i-1}$ which means that $b'_i < a'_{i-1} < a'_i$ as desired.
Answer: If ${\max\,}_l\> a_l=a_j$ and ${\max\,}_l\> b_l=b_j$ for the same $j$ then just make the pair $\left[\matrix{ a_j\cr b_j\cr}\right]$ the last pair of the line. If ${\max\,}_l\> a_l=a_j$ and ${\max\,}_l\> b_l=b_k$ with $j\ne k$ then we have the chain of inequalities
$$a_j\geq a_k\geq b_k\geq b_j\ .$$
We then make $\left[\matrix{ a_j\cr b_k\cr}\right]$ the last pair and $\left[\matrix{ a_k\cr b_j\cr}\right]$ the (temporary) first pair of the line. In both cases the first $n-1$ resulting pairs form an admissible instance of the problem with $n$ replaced by $n-1$.

Inequalities and rearrangements


How to resolve a subdomain to another subdomain of a different host

Question: How do I resolve a subdomain to another subdomain of a different host? What I need is
sub.firstdomain.com

to be resolved as
sub2.seconddomain.com

I do not have control on secondomain.com(it is a cloud hosting) but I own firstdomain.com
I cannot make  CNAME to point to IP as I cannot resolve the IP of the subdomain.
I used CNAME record BUT it gives me 404 error so I think the forwarding is correct but something is wrong.
So, what can I do? Is there a CNAME tweek? or tip? Is there another way other than CNAME?
Answer:
You can't point a CNAME to an IP-Address only to another A record
You are confusing HTTP Host headers and DNS entries

To explain the second part:
If i set up a VirtualHost that reacts to firstdomain.invalid on 192.0.2.1 but don't create a DNS entry I am still able to browse the site by adding the Host headers manually and requestfing from http://192.0.2.1.
If I now crate a DNS entry firstdomain.invalid A 192.0.2.1 I can browse the site by simply using the name (since the HTTP client will take care of the situation that a Host header is needed)
If someone crates a DNS entry seconddomain.invalid A 192.0.2.1 nothing will happen with a browser since the server doesn't know abut the corresponding host entry (setting aside default hosts for now)
If someone creates a DNS entry seconddomain.invalid CNAME firstdomain.invalid the same is true as the above. PLUS the owner of seconddomain.invalid will run into Mail problems since any sane client will see a CNAME entry and start resolvoing the MX entries under the domain where seconddomain.invalid points to. In other words: the programs will do this:

Hey there's a CNAME from
  seconddomain.invalid. It's pointing to
  firstdomain.invalid. Great I'll just
  take the MX of firstdomain.invalid
  since it's a CNAME and try mailing to
  whatever host is defined there as an
  MX, if there's no MX defined I'll
  simply try to mail to the A record of
  firstdomain.invalid

PS (and totally OT): The .invalid Domain and 192.0.2.0/24 are reserved for documentation and example purposes. Please use those as they are guranteed (by RFC) not to be reachable
Comment: Hi and thanks for the reply, but there is no real solution there? what can i do?thanks
Comment: _The people who own the content HTTP server_ have decided that it does not carry the domain `second.example.com.` and have configured it accordingly for the case where anyone goes there asking for WWW pages whose URLs use that domain.  You tell us that you don't own the content HTTP server.  There is nothing that you can do to affect a content HTTP server that isn't yours to reconfigure.
Comment: That is not totally true, you could always use an application layer proxz (read squid) to provide the simple case. Of course you could always hack something up to rewrite the content so it looks like your own -- but that would be...unethical


Ideal in ring product

Question: Let $R$ and $S$ be two rings, then $K$ is an ideal in $R\times S$ if and only if there are $K_1$ and $K_2$ such that $K_1$ is an ideal of $R$ and $K_2$ is an ideal of $S$ such that $K = K_1 \times K_2$.
How do you show that $K_1 = \{a \in R \mid (a,0) \in K\}$ is an ideal of $R$ and $K_2 = \{b \in S \mid (0,b) \in K\}$ is an ideal of S, and the converse too.
Thank you very much.
Comment: Take $K_1$ and $K_2$ as the projections of $K$ and check that they are ideals and $K=K_1\times K_2$. You can easily check that $K\subset K_1\times K_2$. Showing the reverse inclusion requires some properties of ideals.
Comment: how to check K1 and also K2 are ideals in form as (a,0) ∈ K, (0,b) ∈ K ?
Answer: For the inclusion $K_1 \times K_2 \subset K$, let $(a,b) \in K_1 \times K_2$, then $(a,0) \in K$ and $(0,b) \in K$.
For the reverse inclusion, let $(a,b) \in K$, then $(1,0) \cdot (a,b)=(a,0) \in K$ and $(0,1) \cdot (a,b)=(0,b) \in K$. Note that I assume $1 \in R,S$.
Comment: how to check K1 and also K2 are ideals in form as (a,0) ∈ K, (0,b) ∈ K ?
Comment: Take two elements in $a,b \in K_1$ What is their sum and product in K_1? What about their sum and product in $K$ as $(a,0),(b,0)$. Take $r \in R$. Is $(ra,0) \in K$? Notice $(r,0) \cdot (a,0)=(ra,0)$.
Comment: Ok, thank very much. I've got it

Ideal in ring product


Why is my R density plot a bell curve when all datapoints are 0?

Question: When I graph a density plot in R, and all the numbers are slightly greater than 0, I get essentially a vertical line at x = 0.  But when all the numbers are exactly equal to 0, I get some sort of bell curve.  Why is that?  It seems counterintuitive.
The command I used to plot the curves was
for (i in 0:60) {
    cur_data = subset(data, time == i)
    p <- ggplot(cur_data, aes(x=error)) +
                geom_density() +
                theme_bw() +
                xlab(paste("Error distribution (minute ", i, ")", sep="")) +
                xlim(0, 1)
    ggsave(...)
}

At i = 60, cur_data should be entirely populated by the values 0.0.

(Originally posted on Stack Overflow; was told to post here.)
Comment: Hint: how is the density curve computed? What math is R doing to create that plot?
Comment: I have no idea.  If I were to guess, R first finds the cdf, and then takes the (approximate) derivative at each point to find the pdf.  Except in this case the derivative is infinity, so you'd think it would be a vertical line.
Comment: Actually since there is a finite number of points, the cdf is discrete and the derivative would actually be infinity at every point.  So to approximate the derivative at any given point I'd take the interval (x, x + dt) for every point x and compute the change in y over that interval.  But in this case it would be a spike at 0 because this approximate derivative would always be 0 at any point other than x = 0.  So I guess that brings me back to where I was before.
Comment: If you're getting all-zero data, then you don't even have a continuous density (whatever the rest of the distribution does that you didn't observe, a lot of the probability is exactly at zero), so it doesn't necessarily make sense to attempt to compute a derivative. Certainly if you have no data anywhere else (even if the population distribution were continuous elsewhere), the exercise on such a sample is utterly futile. You're entirely reliant on assumptions about its behavior where you have no data ... and your estimate should reflect your assumptions, not the specifics of the kernel.
Comment: Wait, if the data is all zero, shouldn't the cdf be a step function?  So if we were to approximate the derivative at 0 by finding $\Delta y/\Delta x$ in some small interval around 0, wouldn't it just be $1 / (\Delta x)$?
Answer: You should explain what the intuition is that you have that the behavior runs counter to - it would make it easier to focus the explanation to address that.
A kernel density estimate is the convolution of the sample probability function ($n$ point masses of size $\frac{1}{n}$) and the kernel function (itself, by default, a normal density).
The result in the default case is a mixture of normal (Gaussian) densities, each with center at the data values, each with standard deviation $h$ (the bandwidth of the kernel), and weight $\frac{1}{n}$.
When all the data are coincident, the resulting mixture density is a sum of $n$ weighted densities, all with the same mean and standard deviation ... which is just the kernel itself, centered at that data value.

The difference in behavior you see might relate to the trim argument in ggplot2::stat_density. When the range of values is exactly zero, my guess is that it's setting trim to FALSE (or at least something other than TRUE), but when it's even a little larger than 0 it's at the default (TRUE). You'd need to look into the source to double check, but that would be my guess. If that's what's happening, you should be able to modify that behavior.
Comment: Ah. Sorry, I see what you're concerned about. That may be related to the `trim` argument in `ggplot2::stat_density`. When the range is exactly zero, my guess is that it's setting `trim` to `FALSE` (or at least something other than `TRUE`), but when it's even a little larger than `0` it's setting it to `TRUE` (the default). You'd need to look into the source to double check, but that would be my guess. You should be able to modify that behavior.
Comment: Thanks, I didn't know that stuff about the kernel density estimate.  I thought it was a weird result because the numbers are only changing very slightly, so you'd think that would produce a very small change in the density function.  (Actually I still think it's kind of a weird result because presumably the weighted sum of Gaussian densities is a continuous function of their means, so if the means change slightly, why should the density change so much?)


find $\sum_{n=0}^{\infty}n^2 x^n$

Question: I'm trying to find $\sum_{n=0}^{\infty}n^2 x^n$
What I tried doing is:
$\sum_{n=0}^{\infty}n^2 x^n$ = $\sum_{n=0}^{\infty}n(n-1) x^n + \sum_{n=0}^{\infty}n x^n$
= $x^2\sum_{n=0}^{\infty}n(n-1) x^{n-2}+x \sum_{n=0}^{\infty}n x^{n-1} =x^2(\frac{1}{1-x})'' + x(\frac{1}{1-x})'$
But anyway I continute gets me a wrong answer so I wonder if there's some mistake here?
The answer should be $ -\frac{x(x+1)}{(x-1)^3} $
Answer: Your solution is mostly correct. Your lower bounds for the summation are wrong. But that is irrelevant when it comes to your argument simplification which you must not have done correctly because you will get the right answer if you continue down the path you are currently going on.
Answer: Let's denote $f(x) = \sum n^2 x^n = x \sum n^2 x^{n-1} = xg(x)$.
$\int g(x)dx = \sum nx^n = x \sum nx^{n-1} = xh(x)$
$\int h(x)dx = \sum x^n$

find $\sum_{n=0}^{\infty}n^2 x^n$


Symfony2 app hangs randomly - tools to debug

Question: I have a VPS with two docker containers running on it. The two containers have different source code written using Symfony2 inside. The problem is that one of them randomly hangs and is not responding to any requests. It happens only with one of them so I think it's a problem with the source of the app. There are no error logs or server overload when I try to debug the problem. Everything seems fine. Can you suggest me some tools so I can debug the problem and find solution because this happens 5-6 times a day and lasts between 2 and 5 minutes. Then the container works fine - it fixes alone without restart or anything.
Comment: Have you tried to run the app you think is faulty in the other container?
Comment: I tried to run the container on different server and the problem still exists. The two images are running in containers with the same configuration in Dockerfile, the only difference is that different source folders are mounted while building the image. So the two containers are with identical versions of the dependencies and the environment, the only difference is the source with the Symfony2 source code.
Answer: Xdebug is the de facto tool for debugging. There are a lot of tutorials on how to use it. If the hang is caused when you access a route then you should debug that route in particular.


How do I use MATLAB to solve an Euler Backward problem for a Differential Equation?

Question: Is there a way to use MATLAB to solve an Euler Backward problem when the function I have is a differential equation?
My original problem was to simulate an electromagnetic and an electrical field for a certain interval in R^2 and in this interval an electron would enter with an initial speed in x, y direction. I then plotted the path the electron would take inside the field, but now I'm trying to approximate the path using Euler Backward.
Our differential equation in MATLAB looks like this:
<code>dy(1)=y(3);
dy(2)=y(4);
dy(3)=y(4)+1;
dy(4)=-y(3)
</code>
Where y=[x ; y ; u ; v] where u is the derivative of x and v is that of y.
Comment: Are you required to write your own code to implement backward Euler, or can you use one of Matlab's prewritten routines?
Comment: EDIT: Yes, we are required to write our own code to implement backward Euler, we can not use one of Matlab's prewritten routines.
Answer: Given the vector-valued differential equation $\mathbf{y}'(t) = \mathbf{f}(\mathbf{y}(t))$, the Euler backward scheme is given by discretizing the time derivative and evaluating $\mathbf{f}$ at the value of $\mathbf{y}$ to be determined:
$$\frac{\mathbf{y}_{n+1} - \mathbf{y}_n}{h} = \mathbf{f}(\mathbf{y}_{n+1})$$
where $h$ is the time step and $t = nh$, so you have
$$\mathbf{y}_{n+1} - \mathbf{y}_n - h\mathbf{f}(\mathbf{y}_{n+1}) = 0$$
which is an implicit equation for $\mathbf{y}_{n+1}$. There are two interesting facts about the case you're trying to solve:
(1) the equation is basically linear, i.e. $\mathbf{f}(\mathbf{y}) = \mathbf{b} + A\mathbf{y}$ where $\mathbf{b}=(0,0,1,0)$ and $A$ is a matrix.
(2) the differential equation for $y_3$ and $y_4$ has no dependence on $y_1$ and $y_2$, implying that you can solve for $y_3$ and $y_4$ separately, and then calculate $y_1$ and $y_2$.
If we consider that $\mathbf{f}$ is linear, then we get the equation
$$\mathbf{y}_{n+1} - \mathbf{y}_n - hA\mathbf{y}_{n+1} - h\mathbf{b} = 0$$
which can be solved explicitly for $\mathbf{y}_{n+1}$, giving
$$\mathbf{y}_{n+1} = (I - hA)^{-1}(\mathbf{y}_n + h\mathbf{b})$$
where $I$ is the identity matrix. This requires finding the inverse of a 4 x 4 matrix which, whilst it is entirely possible using a computer, isn't necessarily desirable for stability reasons. It would be better to just consider the last two components of the equation, the $y_3$ and $y_4$ components. After manually inverting the 2 x 2 matrix you get
$$y_3^{n+1} = \frac{y_3^n + h y_4^n + h}{1+h^2}$$
$$y_4^{n+1} = \frac{y_4^n - hy_3^n}{1+h^2}$$
which you should easily be able to program in Matlab, and then use the values for $y_3$ and $y_4$ to calculate $y_2$ and $y_1$.
Note that I've given you a very specific implementation of backward Euler which is tailored for the problem at hand. A more general backward Euler solver would have to use a root-finding technique such as Newton-Raphson iteration to calculate $\mathbf{y}_{n+1}$ at each step.


Simple proof that the Airy function decays faster than any polynomial

Question: My question concerns the Airy function $\mbox{Ai} (\cdot)$, which is the solution of the Airy equation
$$y'' = x y$$
that decays exponentially as $x \to \infty$. I have read about how the asymptotic expression for $\mbox{Ai} (\cdot)$is obtained.
Comparing the Airy equation above with the much simpler $y'' = Ay$ (for constant $A>0$), and its decreasing solution - namely $y(x) = e^{-\sqrt{A}x}$, I have an intuition for why Ai$(\cdot)$ should decay exponentially as $x \rightarrow \infty$. So my question is: Without getting into the asymptotic analysis, is there a more direct way to say that Ai$(\cdot) \rightarrow 0$ as $x \rightarrow \infty$ faster than any polynomial?
I am expecting that the role of $f(x) = x$ in the Airy equation is just that of a function which increases to $\infty$ as $x \rightarrow \infty$. So a related question is: Can we make a similar conclusion for a decreasing solution of
\begin{align*}
y''(x) = f(x) y(x)\text{ and }y(0)=1,
\end{align*}
where $f>0$ is an increasing function such that $\lim_{x \to \infty} f(x) = \infty$?
Thanks!
Comment: I'm wondering if you need to specify another initial condition?
Comment: [Hint](https://en.wikipedia.org/wiki/Stokes_phenomenon#Example:_the_Airy_function): change variables to $t:=\tfrac23x^{3/2},\,z:=x^{1/4}y$ so $dt=x^{1/2}dx,\,x^{1/4}=(3t/2)^{1/6}$.
Comment: my friend Dmitry, who is in the biz, recommends Olver, Asymptotics and special functions (following Copson's 1963 paper).   and Wasow, Asymptotic expansions for ordinary differential equations
Comment: As for Ai, it is the solution which is decreasing in $(0,\infty)$ and in the more general case, I expect that like for the Airy equation there are going to be two solutions - one increasing and the other decreasing on $(0,\infty)$ and I am interested in the one which decreases.
Comment: It turns out that the value at $0$ is not $1,$ see wikipedia. Just about everything on this is in Abramowitz and Stegun; I have a paperback reprint
Comment: @Will Jagy: You are right, I have edited the question.
Comment: @J.G.: Thanks, but your hint looks similar to the *stationary phase* which is used to establish the asymptotic formula.
Comment: @J.G.: Chapter 8 of [this](http://pordlabs.ucsd.edu/wryoung/SIO203C2016/PartB_Asymptotics&Integrals.pdf)
Answer: I will assume that what we know about $y = \operatorname{Ai}(x)$ is that $y'' = xy$ and $ y \to 0$ through positive values as $x \to +\infty$.
Assume $y > 0$ for $x > M$. Let $k$ be fixed and large enough so that $k^2 > M$. Let $y_1 = Ce^{-kx}$, where $C$ is chosen so that $y_1(k^2) = y(k^2)$. We will prove that $y \leq y_1$ for $x \geq k^2$. This shows that $y$ is negligible compared to any exponential function.
The function $y - y_1$ takes the value $0$ at $k^2$ and tends to $0$ as $x \to +\infty$.
Assume for a contradiction that $y > y_1$ for some $x > k^2$. Then $y - y_1$ attains a positive maximum, say at $x_0 > k^2$. Therefore the second derivative of $y - y_1$ must be $\leq 0$ at $x_0$. Hence we obtain the absurd consequence that
$$0 \geq y''(x_0) - y_1''(x_0) = x_0 y(x_0) - k^2 y_1(x_0) \geq k^2 [y(x_0) - y_1(x_0)] > 0.$$
Comment: The "though positive values" part of the hypothesis can be omitted. A similar proof, but taking $y_1 = 0$, shows that if $y$ is any solution of $y'' = xy$ such that $y \to 0$ as $x \to +\infty$, then $y$ has constant sign for $x \geq 0$.
Comment: Very nice solution!
Answer: I haven't thought through a fully rigorous argument, but I think we can get the estimate
$$\textrm{Ai}(x) \le \exp\left( - \tfrac23 x^{3/2} +C\sqrt{x}\right) \qquad (x>0)$$
(which holds for all positive $x$, with $C$ being some positive constant) using some fairly low-tech and intuitive bounds. This comes pretty close to the more precise asymptotic formula
$$ \textrm{Ai}(x) \sim \frac{1}{2\sqrt{\pi} x^{1/4}} \exp\left( - \tfrac23 x^{3/2} \right) \qquad (x\to\infty) $$
and explains where the exponential decay in $x^{3/2}$ comes from (which is a bit more than what you asked for -- it's certainly faster than any negative power of $x$, and even a bit faster than a simple exponential decay in $x$ because of the $3/2$ exponent), and even gives the correct coefficient $2/3$ preceding $x^{3/2}$.
The idea is to compare $\textrm{Ai}(x)$ to the function $G(x)$ that solves a discretized version of the Airy differential equation, where we replace
$$ y''(x) = x y(x) $$
by
$$ y''(x) = (n-1) y(x) \qquad \textrm{on any interval }n-1<x<n $$
for integer $n\ge 1$. Specifically I construct this $G(x)$ by gluing together a bunch of exponentials of the form $G(x)=c_n e^{-\sqrt{n-1}x}$ on each interval $[n-1,n]$. The constants $c_n$ are computed inductively from the requirement that $G(x)$ should be continuous, and that we have $G(0)=\textrm{Ai}(0)$. This leads to the piecewise formula
$$ G(x) = \begin{cases}
\textrm{Ai}(0) & \textrm{if }0\le x<1, \\
\textrm{Ai}(0)\exp\big(-\sqrt{1}(x-1)\big) & \textrm{if }1\le x<2, \\
\textrm{Ai}(0)\exp\big(-\sqrt{1}-\sqrt{2}(x-2)\big) & \textrm{if }2\le x<3, \\
\textrm{Ai}(0)\exp\big(-\sqrt{1}-\sqrt{2}-\sqrt{3}(x-3)\big) & \textrm{if }3\le x<4, \\
\textrm{Ai}(0)\exp\big(-\sqrt{1}-\sqrt{2}-\sqrt{3}-\sqrt{4}(x-4)\big) & \textrm{if }4\le x<5, \\
\cdots \\
\textrm{Ai}(0) \exp\left(-\sum_{k=1}^{n-1} \sqrt{k} - \sqrt{n}(x-n)\right) & \textrm{if }n\le x<n+1,
\\
\cdots
\end{cases}
$$
Here is a plot showing the two functions $\textrm{Ai}(x)$ and $G(x)$:

Now the trick is to observe that $0<\textrm{Ai}(x)\le G(x)$ for any $x>0$. This shouldn't be too hard to prove rigorously; the intuition behind it is that the change from the original Airy equation to the discretized version makes it harder for the function to decay by speeding up the second derivative of $y(x)$ just a bit. (Edit: on second thought, this version of the equation slows down the second derivative, so the comparison is a bit more subtle than I thought at first. Nonetheless, the plot suggests the inequality is true, and if it is then I suspect it should not be hard to justify rigorously.)
Assuming this, we see that, for $x$ in the interval $[n,n+1]$ with $n\ge1$ integer,
$$ \textrm{Ai}(x) \le \textrm{Ai}(0)\exp\left( - \sum_{k=1}^{n-1} \sqrt{k} \right),$$
and this is easily seen to behave like $\exp\left( - \tfrac32 x^{3/2} +C\sqrt{x}\right)$, e.g., by a comparison of the sum inside the exponential with the integral $\int_0^n \sqrt{x}\,dx = \tfrac23 n^{3/2}$.
Comment: Wonderful! I also had a similar intuition, but didn't really expect it would give $\exp(-\frac{3}{2}x^{3/2})$. Using similar arguments and considering an analogous function $H(x) = a_n e^{-\sqrt{n}x}$ on $[n-1,n)$, we can get a matching lower bound too!
Answer: This is somewhat weaker than what you want, but may be useful.
To study what happens as $x \to +\infty$, it's convenient to use the change of variables $t = 1/x$ so that $t \to 0+$.  The Airy equation becomes
$$ (t^2 u')' = u/t^3 $$
Now suppose a solution $u$ has $u \sim c t^m$ as $t \to 0+$ for some $m, c > 0$.  Then
$(t^2 u')' \sim c t^{m-3}$.
Note that $t^2 u'$ is increasing.  If  $u'(t_0) = 0$ for some $t_0 > 0$,
we'd have $u'(t_1) < 0$ for  $t_1$ with $0 < t_1 < t_0$, and then there would be $\epsilon > 0$ with
$u' < - \epsilon/t^2 $ for $0 < t < t_1$.  But since $1/t^2$ is not integrable on that
interval, this is impossible.  Similarly we can't have all $t^2 u' > \epsilon > 0$. So we must have $u' > 0$, and $t^2 u' \to 0$ as $t \to 0+$, and
$$ t^2 u'(t) = \int_0^t (s^2 u'(s))' ds \sim c \int_0^t s^{m-3}\; ds$$
In particular $s^{m-3}$ must be integrable on $(0,t]$ so $m > 2$, and
$$t^2 u'(t) \sim \dfrac{c}{m-2} t^{m-2} $$
That makes $u'(t) \sim \dfrac{c}{m-2} t^{m-4} $.
Again, $t^{m-4}$ must be integrable, so $m > 3$, and
$$ u(t) \sim \dfrac{c}{(m-2)(m-3)} t^{m-3} $$
But that contradicts the assumption $u \sim c t^m$.
Comment: Thanks! I think your answer is quite general and will be useful for many other examples too.
Comment: The book by Olver follows Copson (1963) which I don't have... https://www.cambridge.org/core/journals/glasgow-mathematical-journal/article/on-the-asymptotic-expansion-of-airys-integral/3DF1D7888D7060967D78DC91E651E6BD


Crawler para fazer paginação

Question: Preciso de um crawler que faça paginação em um site.
Estou lendo o código fonte e gerando um txt dessa maneira
public class CodFonte {

public static void crawler(String str) throws IOException {

    URL url = new URL(str);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setReadTimeout(15 * 1000);
    connection.connect();

    // read the output from the server
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            connection.getInputStream()));
    StringBuilder stringBuilder = new StringBuilder();

    String linha = "";

    String path = System.getProperty("user.home") + "\\Desktop\\";
    String fileName = "Fonte Code.txt"; // Nome do arquivo

    FileWriter file = new FileWriter(path + fileName);
    PrintWriter gravarArq = new PrintWriter(file);
    gravarArq.println("SITE -------- " + url);

    while ((linha = reader.readLine()) != null) {
        gravarArq.println(linha);
    }
     file.close();
    reader.close();
}

}

Mas preciso ir para próxima pagina, a url é amigável não muda de acordo com a requisição do form que é via POST.
Comment: Como é a estrutura da URL (paginação)? É um número?
Comment: é numero o input esta dentro de uma tabela ----
Comment: E você já consegue ler este input pelo seu `java` acima?
Comment: Sim eu consigo chegar ate ele usando  Document doc = Jsoup.parse(html);
Comment: Bem, certa vez eu criei um crawler como este em PHP. A ideia era a mesma. A diferença é que eu colocava um link já com a próxma página no final da página, assim, eu clicava e ai a pagina atual era a próxima página. Você terá que usar um método de `sleep` (para aguardar entre uma página e outra) e usar um `loop` para seguir para a próxima página, além de uma condição de stop (ex.: `maxPaginasToCraw`). Antes, terá que ver quantas páginas existe, acessando todas elas e verificando  header do http (código 200) para salvar numa variável o total de páginas para usar no loop.
Comment: Essa parte de pegar o total de paginas eu consegui, tem uma div em que a pagina mesmo ja fala o total, entao eu soh faço umas condições e recupero o total, agora como submeter o post com os parametros?
Comment: Seu problema é só ir para a próxima página então? Você já consegue obter o código da página atual?
Comment: Sim, ja consigo ate gerar um txt da pagina atual, eh isso mesmo soh preciso saber  como submeter o formulario via post com esse crawler assim que eu tiver a proxima pagina eu consigo fazer o scan dela
Answer: Fazendo uma requisição post e obtendo o retorno, ajuda?
HttpURLConnectionExample.java
package com.meupacote.app;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HttpURLConnectionExample {

    private final String USER_AGENT = "Mozilla/5.0";

    public static void main(String[] args) throws Exception {

        HttpURLConnectionExample http = new HttpURLConnectionExample();

        System.out.println("\nTesting 1 - Enviar request via POST");
        http.sendPost();

    }

    // HTTP POST request
    private void sendPost() throws Exception {

        String url = "http://www.url.com/";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "param1=valor1&param2=valor2";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\Enviando 'POST' request para a URL : " + url);
        System.out.println("Parâmetros parameters : " + urlParameters);
        System.out.println("Response Code: " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());

    }

}

Comment: Então, mas a url é amigavel, não muda, entao para que eu consiga ir para proxima pagina eu preciso mandar a requisição via post e assim recuperar a nova pagina
Comment: Atualizei a resposta. Talvez eu não tenha entendido errado
Comment: Boa resposta! Mas, há algum motivo especial para usar `StringBuffer` ao invés de `StringBuilder`? Acho também que daria para usar a sintaxe *try-with-resources* para simplificar o código e deixá-lo mais robusto.
Comment: tranquilo, entao esse codigo eu creio que ja vai ajudar muito, como vc pegou os parametros que devem ser passados na requisição. Porque acho que estou passando os parametros errados
Comment: Acha então que os parâmetros estão errado, por isso o retorno não te ajuda?
Comment: porque, quando eu executo meu codigo ele retorna sempre a mesma pagina, fiz um laço para chamar a requisicao post com o total de paginas, o site que preciso fazer o crawler eh esse http://www.apinfo.com/apinfo/inc/list4.cfm. Preciso armazenar as vagas nesse site, mas nao consigo passar da primeira pagina
Comment: Entendi! Então, a URL para post é http://www.apinfo.com/apinfo/inc/list4.cfm e os parâmetros são `

`
Comment: Basta setar em `String urlParameters = "param1=valor1&param2=valor2";` os parâmetros e ver o que retorna...o que retornará provavelmente será o HTML todo da página, prontos pra parsear usando parte do código do seu seu `crawler`
Comment: agora ficou claro, vou implementar aqui, vlw cara
Comment: Imagina! Acho que também vou fazer um da Apinfo em C#! Abraço
Comment: Cara testei aqui e funcionou certinho, eu estava fazendo uma coisa muito complicada utilizando Jsoup, do jeito que vc fez foi simples e direto vlw
Comment: Opa! Haha perfeito! Que ótimo!
Comment: cara sera que pode me dar uma ajuda em outro crawler ? http://pt.stackoverflow.com/questions/72459/crawler-para-fazer-login-no-site-da-nota-fiscal-paulista

Crawler para fazer paginação


Ir para uma nova view com JSon

Question: Estou fazendo um exclusão com Ajax e retornando um JSon. Como eu faço para abrir uma view diferente?
Segue o código, coloquei o url mais não funciona:
View
$.ajax({
    url: '@Url.Action("ExcluirPedidoCompra")', // to get the right path to controller from TableRoutes of Asp.Net MVC
    dataType: "json", //to work with json format
    type: "POST", //to do a post request
    contentType: 'application/json; charset=utf-8', //define a contentType of your request
    cache: false, //avoid caching results
    data: "{\"id\" : " + id + "}", // here you can pass arguments to your request if you need
    success: function (data) {

        if (data > 0) {
           url: '/PedidoCompraConsultar/Index'
        }

    },
    error: function (xhr) {
        alert("Erro! Ocorreu um erro ao excluir, Favor Entrar em Contato com O Suporte.");
    }
});

código do controller
public ActionResult ExcluirPedidoCompra(int id)
{
    var resultado = 1;
    return Json(resultado);
}

Já testei de todas as forma. Se alguém puder me ajudar quero ir para "PedidoCompraConsultarController - Index".
Comment: testou,  url: '@Url.Action("PedidoCompraConsultar")'  ?
Answer: Coloca dessa forma :
window.location.href= 'rota'

Comment: muito obrigado deu certo

Ir para uma nova view com JSon


Assinar projeto em flutter com a mesma keystore de um projeto já publicado

Question: Me surgiu uma duvida tenho uma aplicação feita em kotlin no android studio já publicada na loja porem descobri o flutter e gosto mais de usar ele como linguagem, eu estava pensando em refazer esse projeto em flutter, eu consigo assinar ele com a mesma keystore do projeto já publicado na loja e enviar como uma atualização?
Comment: Mudar a tecnologia utilizada para criar o app não tem problema. O app deve ter o mesmo nome de pacote e ser assinado com a mesma chave. Já fiz app com java que mudou para ionic e mudou para kotlin, sempre atualizando sem problemas.
Comment: nunca passei por isso, mas desde que seu app mantenha o mesmo applicationID creio que não haverá problemas na hora de publicar
Answer: Resposta curta: Sim!
Eu já fiz isso, na verdade era um projeto legado feito com Ionic e o meu trabalho era refazer utilizando Flutter. A única coisa que você precisa se atentar é que o app Flutter precisa ter o mesmo package name do app feito em nativo. Então, sugiro que você rode o seguinte comando na hora de criação:
flutter create --org=com.suaorganizacao nome_do_projeto

Assim ele vai gerar um pacote: com.suaorganizacao.nome_do_projeto, ainda existem opções mais complexas no comando flutter create vale a pena você executar flutter create --help para ver todas as possibilidades.
Também, quando for efetivamente subir o app, vai ter que compilar com um version code superior ao que está publicado.
Dentro do seu pubspec.yaml vai ter uma chave escrito version:
Seguindo o exemplo abaixo, o "1.0.0" é o versionName e o número 1 após o símbolo de mais é o versionCode.

Dessa forma se você já tiver compilado 30 versões do seu app e você está na versão 1.0.6, o nome da sua próxima versão seria algo como:
version: 1.0.7+31


Prove that $\ln(x^2+1) \arctan x$ is uniformly continuous in $\mathbb R$.

Question: Prove that $\ln(x^2+1) \arctan x$ is uniformly continuous in $\mathbb R$.
My attempts at proving this have not yielded anything worth sharing. I'd appreciate any help or a push in the right direction.
Comment: Hint: Your function has a bounded derivative.
Comment: @DavidMitra Thank you very much!! You should convert your comment to an answer.

Also, when proving that the derivative is bounded, is it enough to say that the function is continuous in $\mathbb R$ (meaning that there can't be a vertical asymptote) and that $\lim_{x\to\infty}f(x)=\lim_{x\to-\infty}f(x)=0$?
Comment: Yes, that would work.
Answer: Hint: Since $f(x)=\ln(x^2+1)\arctan x$ is an odd function, it is enough to show that it is uniformly continuous on $[0,\infty)$.
Towards this end, note that, for $x\ge 0$
$$
f'(x)
={2x\arctan x\over 1+x^2}+{\ln(1+x^2)\over 1+x^2}
\le {\pi x\over 1+x^2}+{\ln(1+x^2)\over 1+x^2}\ \
\buildrel{x\rightarrow\infty}\over\longrightarrow\ \ 0.
$$
Use this and the fact that $f' $ is continuous to deduce that $f'(x)$ is bounded on $[0,\infty)$.  The uniform continuity of $f$ over $[0,\infty)$ follows from this.


How to delete a dynamic array with my function class?

Question: Again with templates. Now I'm trying to write a Deleter function class so that it works similar to the language one delete. Here is my attempt:
class Deleter
{
public:
    template <typename T>
    void operator()(T*) const;
};

template <typename T>
void Deleter::operator()(T* ptr) const
{
    std::cout << "freeing memory...\n";
    delete ptr;
}

int main()
{

    int* pi = new int(7);
    char* cp = new char[100];
    strcpy(cp, "hi there!");

    Deleter del;
    del(pi); // 1- argument deduced is int*
    del(cp); // 2- argument deduced is char*

    std::cout << "\ndone\n";
}

I've overloaded the call operator as a template thus at compile time it knows the static type of argument. (I could made it non-template replacing T with void*).
It works fine but I think surely that statement 2 will cause a Memory leak because I am passing a pointer to a dynamic array into delete which works on pointers to dynamic object not array and as I've already learned it is undefined behavior to call delete on an object that had not been allocated with the corresponding new operator.
So Is there a workaround in my code so that I can call del[]cp;? Thank you!
Comment: Practicing what exactly? You cannot deduce from a pointer in what way it has been allocated, that information is not available there
Comment: I don't see an easy solution. The information on whether it was allocated via new or new[] is not available.
Comment: You could create a second class called ArrayDeleter and have the delete in operator() use [] like `delete [] ptr;`
Comment: Why do you need to do any of this instead of using standard library containers which manage the memory on their own?
Comment: @UnholySheep: Just for practice. After all I prefer using smart pointers as much as possible.
Comment: @RemyLebeau: feels so genius! could you elaborate an example please?
Comment: @drescherjm that won't work, since the `operator()` won't know if the pointer needs to be freed via `delete` or `delete[]`.  You need separate `operator()` specializations for each type of deletion.
Comment: @Maestro see the answer I just posted.
Comment: I meant a completely different class with a different operator() where you use the Deleter() class for objects created with new and the ArrayDeleter class for objects created with new[].
Comment: @drescherjm yes, you would need two separate classes, one for each type of deletion
Comment: I do like your answer better anyways..
Answer: You cannot use delete with memory allocated with new[], and vice versa using delete[] with memory allocated with new. This is exactly why std::unique_ptr and std::shared_ptr have specializations to decide when to use delete[] vs delete for array and non-array memory, respectively (via the std::default_delete template).
You are just going to have to specialize your Deleter in a similar manner, too.  Only the user of your Deleter, not the Deleter itself, can decide which specialization to use, since only the user has information about how the memory was allocated to begin with, and thus how it needs to be freed.
For example:
template <typename T>
class Deleter
{
public:
    void operator()(T* ptr) const {
        std::cout << "freeing memory using 'delete'...\n";
        delete ptr;
    }
};

template <typename T>
class Deleter<T[]>
{
public:
    template <typename U>
    void operator()(U* ptr) const {
        std::cout << "freeing memory using 'delete[]'...\n";
        delete[] ptr;
    }
};

int main()
{
    int* pi = new int(7);
    char* cp = new char[100];
    strcpy(cp, "hi there!");

    Deleter<int> del1;
    del1(pi); // uses 'delete'...

    Deleter<char[]> del2;
    del2(cp); // uses 'delete[]'...

    std::cout << "\ndone\n";
}

Live Demo
Comment: @Maestro Yes.  Though consider using `{}` instead of `()` when constructing the `Deleter` object, eg: `Deleter{}(cp);` But both ways will work.
Comment: so can I call it with an r-value this way: `Deleter()(cp);?`
Comment: Ah yes to avoid the vexing parser?


Rationality of $a^2+b^2$

Question: I have looked into this topic lately and have not found an answer to the following question.  Is the following true:
If $a,b\in\mathbb{R}$ and $a + b$ is rational, then $a^2 + b^2$ is rational
Comment: Try $a=\sqrt e$, $b=-\sqrt e$
Comment: it is easy to make both positive as well.  Try $a=\sqrt 2$, $b=2-\sqrt 2$ for example.
Comment: Thank you.  I appreciate your answer.
Comment: Thank you again.  If permitted, I would like to make one more condition.  Both a and b are irrational while (a+b) > 0.
Comment: My (recent)  example satisfies that.
Comment: You are right.  Thank you very much.
Answer: No.
Proof by counter-example
Take any irrational number $c$ and let $a = \sqrt c$ and $b = -\sqrt c$.
Then $a+b$ will be rational, but $a^2 + b^2$ will be irrational.
Comment: Thank you.  That is what I was looking for.  What about if (a +b) > 0?

Rationality of $a^2+b^2$


MVC o método que usei para chamar uma função de outro model está correto?

Question: Estou estudando MVC e me deparei com a seguinte situação:
Tenho uma View que precisa receber dados de dois Models diferentes, então no controller desta View eu tenho a função abaixo:
<code>public function teste($id) {

        $this->view->a = $this->getOneA($id);

        $this->loadModel('b');
        $this->view->b = $this->model->getOneB($id);

        $this->view->render('app/teste');
}
</code>
O cenário acima me retorna o esperado, pega os dados de A e de B e os deixa disponiveis para a View.
Está correto utilizar esse método ?
Se sim, eu deveria carregar o Model "b" no __construct do controller "a"  ou diretamente na função do controller "a" como neste exemplo?
Se não, qual a melhor maneira de obter dados de diferentes Models?
OBS: todos os controllers são filhos do controller principal e todos os models são filhos do model principal.
Answer:
Está correto utilizar esse método ?
Se sim, eu deveria carregar o Model "b" no __construct do controller "a" ou diretamente na função do controller "a" como neste exemplo?

Para quem passar pela mesma dúvida, a resposta é Sim para as perguntas acima.
Posso declarar o model tanto no construct (possibilitando a utilização em qualquer lugar da classe) quanto em uma única função como no exemplo.
A estrutura é bem parecida (inclusive os nomes dos métodos) com a do CakePHP.
Encontrei aqui a resposta https://riptutorial.com/cakephp/example/11485/load-another-model-into-controller


Loading view file into a variable in Zend Framework

Question: I am trying to send mail using mail templates. To do this I want to load a .tpl into a variable. Instead of loading an HTML file and substituting placeholders, I wonder if it is possible to set values of the view in the controller, and then load this view into a variable. This way I would have a variable containing the HTML mail filled out with the information set in the controller prior to loading the view.
Any alternatives are also welcome, I mean, if there are already ways of doing mail templating in a more standardized way.
Answer: A great idea Erik, and I've done this many times.
Zend_View is really just a templating system, and can be used to generate anything, not just HTML.
Sample code - create a view, assign some data, render the view and send the mail!
<code>$view = $this->getHelper('ViewRenderer')->view;

$view->email = $data['email'];
$view->password = $data['password'];

$text = $view->render('mail/new-user.php');
$mail = new Zend_Mail();

$mail->addTo($data['email'], $data['forename'] . ' ' . $data['lastname']);
$mail->setSubject('Account Details');
$mail->setBodyText($text, 'utf-8');

$mail->send();
</code>
In the first line I retrieve the ViewRenderer's view so I have access to the normal script paths. You can create a new Zend_View object, but you'll need to add the path to your view scripts manually.
In my example text based content is generated, but you could generate HTML all the same.
Answer: Sorry guys (and girls). My google skills must have noticed it was early in the morning. I found what I was looking for here:
http://myzendframeworkexperience.blogspot.com/2008/09/sending-mails-with-templates.html
Comment: Dead link.. check the link


Determine the angles of the form $k (\pi)$

Question: Determine the angles of the form $k (\pi)$ with rational $k$ such that the results of its sines are rational
This is an application of Niven's theorem.?
Answer: Yes, it is an application of Niven's theorem. That theorem gives the list of those $k\in\mathbb Q\cap\left[0,\frac12\right]$ for which $\sin(k\pi)\in\mathbb Q$. It happens that that list consists of $\left\{0,\frac16,\frac12\right\}$. It is now easy to determine those $k\in[-1,1]\cap\mathbb Q$ for which $\sin(k\pi)\in\mathbb Q$. And then we use the fact that the sine function is periodic with period $2\pi$.
Comment: I don't think it changes much, since $ sin (kx) = cos (\pi / (2-kx))$
Comment: I misunderstood your question. What do you think now?
Comment: Yess ! Thanks! oo


Slow Magento Homepage

Question: Hello is there any direct or simple reason to Mage_Core_Model_Session_Abstract_Varien::start take 15 seconds to load?
I have in the same server other project and other PHP framework and this is only happening to one site.
This is what I am having, what does blocking mean?
Comment: It depends on you used cache backend. Are you using 'files'?
Comment: I know I am using files....
Comment: I notice that another site of mine just did the same: a Joomla with JSession::_start
Comment: Does deleting /var/session make a temporary improvement?
Answer: It was a bad server vhost configuration. It was not allowing the server to use Fast CGI. Nothing to do with Magento.

Slow Magento Homepage


How to get a backtrace in Drupal, without problems like out-of-memory when huge objects are in the trace?

Question: I often have problems with the standard backtracing functions when working with Drupal:

debug_print_backtrace(); often seems to get lost between pages and never prints,
Drupal's objects and classes are often so big that debug( debug_backtrace(), "Backtrace", true ); can kill my server with out of memory errors, and debug( debug_backtrace() ); almost always fails with a "Nested dependency" recursion error.

Is there any alternative to the above approaches that can be used reliably, ideally as a drop-in function without needing to set up any framework?
Answer: I find this useful as a less memory intensive Drupal-friendly way to backtrace PHP as a one-off code snippet to temporarily drop into a troublesome location without installing modules or server-side tools:
  $trace = debug_backtrace();
  $backtrace_lite = array();
  foreach( $trace as $call ) {
    $backtrace_lite[] = $call['function']."    ".$call['file']."    line ".$call['line'];
  }
  debug( $backtrace_lite, "TRACE", true );

It gets the backtrace into Drupal's debugging system, but strips it down to the essentials to avoid failures when massive objects are involved.
For handy reference, the other keys within each row of the debug_backtrace() object are:

class
object
type
args

Note - this answer was first posted in the now-deleted too-broad question How do I debug Drupal?
Answer: More compact variant:
  $backtrace_lite = array_map(function($call_item) {
    return "{$call_item['function']} -> {$call_item['file']} -> line {$call_item['line']}";
  }, debug_backtrace());


zfs regular read pauses

Question: We have a zfs file system running on openindiana with an almost purely read-only workload. Recently we have found that the io is blocked or pauses every 1 minute for around 2-3 seconds. Does anyone know why this happens and how to stop it occurring?
pool: data

state: ONLINE

status: The pool is formatted using a legacy on-disk format.  The pool can
        still be used, but some features are unavailable.

action: Upgrade the pool using 'zpool upgrade'.  Once this is done, the
        pool will no longer be accessible on software that does not support feature
        flags.

scan: none requested

config:

        NAME                       STATE     READ WRITE CKSUM
        data01                     ONLINE       0     0     0
          raidz1-0                 ONLINE       0     0     0
            c6t5E83A97A6BAB722Fd0  ONLINE       0     0     0
            c6t5E83A97BBE7FE8F1d0  ONLINE       0     0     0
            c6t5E83A97CB2D1609Fd0  ONLINE       0     0     0
            c6t5E83A97E0D2BC6ACd0  ONLINE       0     0     0
            c6t5E83A97E1E2A6F66d0  ONLINE       0     0     0
            c6t5E83A97E4C627FC0d0  ONLINE       0     0     0
            c6t5E83A97E44EB7FC0d0  ONLINE       0     0     0
            c6t5E83A97E124F8168d0  ONLINE       0     0     0
            c6t5E83A97E86762E4Dd0  ONLINE       0     0     0
            c6t5E83A97E25716311d0  ONLINE       0     0     0
            c6t5E83A97EBEEB8B60d0  ONLINE       0     0     0
            c6t5E83A97FCF5551F5d0  ONLINE       0     0     0

errors: No known data errors

As requested by @jlliagre, here are the results from calling hotkernel during good and bad times.
good times

zfs`vdev_is_dead                                            1   0.0%
ip`conn_ip_output                                           1   0.0%
sd`sdintr                                                   1   0.0%
mpt_sas`mptsas_start_cmd0                                   1   0.0%
genunix`new_mstate                                          1   0.0%
genunix`segvn_faulta                                        1   0.0%
unix`swtch                                                  1   0.0%
unix`tsc_scalehrtime                                        1   0.0%
zfs`ddt_stat_add                                            1   0.0%
unix`lwp_segregs_save                                       1   0.0%
rootnex`rootnex_get_sgl                                     1   0.0%
genunix`ldi_strategy                                        1   0.0%
mpt_sas`mptsas_scsi_init_pkt                                1   0.0%
genunix`ddi_fm_dma_err_get                                  1   0.0%
zfs`zio_create                                              1   0.0%
zfs`zio_destroy                                             1   0.0%
unix`strcmp                                                 1   0.0%
unix`cpu_acpi_idle                                          1   0.0%
ip`ip_xmit_attach_llhdr                                     1   0.0%
genunix`mdi_pi_get_vhci_private                             1   0.0%
genunix`lbolt_event_driven                                  1   0.0%
unix`disp                                                   1   0.0%
genunix`cpu_update_pct                                      1   0.0%
unix`tsc_gethrtime                                          1   0.0%
ip`tcp_build_hdrs                                           1   0.0%
genunix`dnlc_lookup                                         1   0.0%
unix`page_create_va                                         1   0.0%
genunix`kmem_zalloc                                         1   0.0%
unix`mmapobj_map_elf                                        1   0.0%
bnx`bnx_intr_1lvl                                           1   0.0%
genunix`btopr                                               1   0.0%
genunix`fsflush                                             1   0.0%
genunix`gexec                                               1   0.0%
unix`mmu_tlbflush_entry                                     1   0.0%
unix`hment_alloc                                            1   0.0%
specfs`spec_lockcsp                                         1   0.0%
zfs`vdev_stat_update                                        1   0.0%
genunix`stk_getptr                                          1   0.0%
unix`resume                                                 1   0.0%
unix`do_splx                                                1   0.0%
unix`page_clr_all_props                                     1   0.0%
bnx`bnx_xmit_ring_xmit_mblk                                 1   0.0%
genunix`list_create                                         1   0.0%
scsi`scsi_uscsi_handle_cmd                                  1   0.0%
unix`page_lookup_nowait                                     1   0.0%
genunix`syscall_mstate                                      1   0.0%
genunix`kmem_free                                           1   0.0%
genunix`as_map_locked                                       1   0.0%
unix`cpu_idle_adaptive                                      1   0.0%
unix`page_lookup_create                                     1   0.0%
sd`sd_start_cmds                                            1   0.0%
unix`0xfffffffffb85                                         1   0.0%
unix`atomic_cas_64                                          1   0.0%
genunix`restorectx                                          1   0.0%
genunix`vmem_is_populator                                   1   0.0%
unix`disp_anywork                                           1   0.0%
unix`prefetch_page_r                                        1   0.0%
sd`xbuf_iostart                                             1   0.0%
zfs`zfs_read                                                1   0.0%
unix`hwblkclr                                               1   0.0%
specfs`sfind                                                1   0.0%
genunix`swapfs_getvp                                        1   0.0%
zfs`vdev_cache_allocate                                     1   0.0%
zfs`buf_hash_find                                           1   0.0%
genunix`taskq_thread                                        2   0.0%
unix`tsc_read                                               2   0.0%
unix`tsc_gethrtimeunscaled                                  2   0.0%
genunix`fop_getpage                                         2   0.0%
unix`inflate_table                                          2   0.0%
unix`ddi_get32                                              2   0.0%
unix`mutex_exit                                             2   0.0%
unix`idle                                                   3   0.0%
zfs`lzjb_compress                                           3   0.0%
unix`mutex_enter                                            6   0.1%
unix`page_nextn                                             9   0.1%
genunix`fsflush_do_pages                                    9   0.1%
unix`disp_getwork                                          12   0.2%
unix`acpi_cpu_cstate                                      441   5.7%
unix`i86_mwait                                           7118  92.7%

bad times

genunix`cpu_update_pct                                      1   0.0%
unix`splr                                                   1   0.0%
bnx`bnx_timer                                               1   0.0%
unix`av_check_softint_pending                               1   0.0%
genunix`devid_str_decode_id                                 1   0.0%
pcplusmp`apic_send_ipi                                      1   0.0%
genunix`callout_downheap                                    1   0.0%
unix`prefetch_page_r                                        1   0.0%
dtrace`dtrace_state_clean                                   1   0.0%
genunix`fsflush                                             1   0.0%
unix`link_ptp                                               1   0.0%
ip`ip_input_cksum_v4                                        1   0.0%
ip`tcp_timer_callback                                       1   0.0%
unix`page_pptonum                                           1   0.0%
unix`do_splx                                                1   0.0%
unix`page_nextn                                             5   0.1%
genunix`fsflush_do_pages                                    6   0.1%
unix`acpi_cpu_cstate                                      782  17.7%
unix`i86_mwait
Comment: More details about the hardware and pool layout, please...
Comment: Have you run a scrub on your system since this problem started?
Comment: Status of C-states? And to pre-empt an answer of 'on', turn off C-states. They are a huge killer of performance (for instance, you'll never get full 10Gbe if C-states is on, fun huh?). You can't really (AFAIK) disable them fully in OS. Go into your BIOS, find anything about C-States and disable it. Then find where it talks about power, and set it to 'Performance' or the equivalent. If your CPU is capable of dropping below C1 (or maybe C1E), you're going to feel performance penalties, and at times you wouldn't even expect it.
Comment: The zpool contains 12 ssd's in raidz-1 configuration. The load is made up of a large number of small random reads.
Comment: And how much RAM do you have? Is there any L2ARC? Can you provide the output of `zpool status -v`?
Comment: The server has 64 gb ram. The cache hit ratio is fairly poor so we have decided not to use an L2ARC.
Comment: You might want to use dtrace to identify what the OS is doing during the pauses. I would suggest starting with the hotkernel script.
Comment: hotkernel script is not showing anything obvious (to me)
Comment: @PhilHoy Have you looked at disk-busy figures?
Comment: @PhilHoy Please use the @ + name prefix when replying for notifications to occur. You should run hotkernel twice, the first one during a normal period, the second one when the problem occurs then post the results.
Answer: Well, there are a few things wrong here...

Your zpool version is old. zpool upgrade will fix that.
The pool design does not lend itself to high performance. You have the effective IOPS potential of one disk. (this is likely the biggest issue here)
You have too many drives in your RAIDZ1. You shouldn't go over 7...
There are likely other tunables that may help here. Can you show zfs list?

Take a read of: http://nex7.blogspot.com/2013/03/readme1st.html for more general guidelines.
Comment: I would like to stress the performance WAS very good until recently when it started pausing every minute. Inbetween the pauses the performance is great.

zfs list

NAME                          USED  AVAIL  REFER  MOUNTPOINT

data01                       2.98T  1.71T  42.0K  /data01
Answer: Perhaps is there an issue with power management on your machine.
Try disabling it by adding the following line to the /etc/power.conf file
cpupm disable

next run
pmconfig

and see if the I/O behavior changes.

Update:
As disabling power management doesn't change anything, the fact is the kernel is essentially idle during the "Bad times" with zero ZFS activity,.
I would then infer the application is not I/O bound and is simply doing something else during these periods of time.
Comment: Tried that and it did not help. Nice ideas though.
Comment: Thanks for the feed back ! Don't forget to revert power management back to default by removing the cpupm line and running pmconfig again.
Comment: Answer updated.
Comment: I had already ruled out the application as a possible cause of the pauses however @jlliagre's wise words forced my to take another look. Embarrassingly i was barking up the wrong tree and the app was to blame. Thanks everyone one and sorry to take up your time.

zfs regular read pauses


SIMD Vectors - Complex numbers?

Question: I am wanting to use the System.Numerics.Vector namespace in .NET Core, but I have run into the issue of there being no support for vectors of complex numbers. As it stands, the Vector type will work with any primitive type, from byte to double. I am not a programmer by trade, so I can be ignorant of some low-level/conceptual stuff, but is there a reason why there isn't support for complex numbers? As far as I can see, perhaps the only issue would be that the Complex type is a managed struct. Could I not just extend the Register type to include [FieldOffset(0)] internal Complex complex_0 and build new functions around that?
I am willing to work on the type extension myself, but wanted to ask if there is some reason why this wasn't included in the first place, since it seems like a lot of signal processing work would benefit greatly from complex vectors and SIMD.
Comment: A possible reason is that there is no direct hardware support for complex numbers. It's much more efficient to use two vectors, one for the real and one for the imaginary parts. (the relevant concept here is SoA vs. AoS)
Comment: They *help* make it more efficient in cases where you're "stuck" with the AOS memory layout where real/imaginary pairs must be next to each other. But it is still far more efficient to separate real/imaginary pairs into different SIMD vectors.
Comment: I thought that might be the case, but https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf on 184.108.40.206 shows possible CPU instructions for complex arithmetic. Of course, I am not sure how much this applies...
Comment: Ok, I really appreciate the advice. Thanks for clearing that up for me!
Comment: `System.Numerics.Vectors` contains SIMD accelerated types like `Vector<>`. I checked Complex and while part of this assembly it is not SIMD accelerated. As @Mysticial points to use SOA and can allow you to executed say 8 floating point mulitplications in parallel and with better cache utilization.
Comment: @Justanothermetaprogrammer Yes, I am using the SIMD Vectors.
Comment: Worth noting that drastically expanded SIMD support is being worked on for .NET Core. The GitHub issue is worth a read: https://github.com/dotnet/corefx/issues/22940
Comment: @battlebottle thanks for sharing this! It definitely gave me a lot more hope for vectors. They hardly perform better than arrays at the moment.
Answer: The System.Numerics.Vector is useless for your goal. You could rely on the Vector256 class from the System.Runtime.Intrinsics namespace. The necessary instructions are exposed in the System.Runtime.Intrinsics.X86.Avx class.
(Vector128 would be of little help here, as it represents a single Complex number. I failed to locate any magic that would help me re-interpreting the Complex as Vector128 without copying, otherwise we would be able to boost up the built-in operators provided for the Complex class)
So, the idea is to

Have your Complex data expressed in terms of Span
Have the arithmetic operators implemented on those Spans
Internally, cast those Spans to Vector256
And use the Avx operations

See the sample code below:
public static class ComplexAvx
    {
        public static Span<Complex> Add(ReadOnlySpan<Complex> left, ReadOnlySpan<Complex> right)
        {
            var result = new Complex[Math.Min(left.Length, right.Length)].AsSpan();
            var vectorRes = MemoryMarshal.Cast<Complex, Vector256<double>>(result);
            var vectorLeft = MemoryMarshal.Cast<Complex, Vector256<double>>(left);
            var vectorRight = MemoryMarshal.Cast<Complex, Vector256<double>>(right);
            for (int i = 0; i < vectorRes.Length; i++)
                vectorRes[i] = Avx.Add(vectorLeft[i], vectorRight[i]);

            for (int i = 2 * vectorRes.Length; i < result.Length; i++)
                result[i] = left[i] + right[i];
            return result;
        }

        public static Span<Complex> Subtract(ReadOnlySpan<Complex> left, ReadOnlySpan<Complex> right)
        {
            var result = new Complex[Math.Min(left.Length, right.Length)].AsSpan();
            var vectorRes = MemoryMarshal.Cast<Complex, Vector256<double>>(result);
            var vectorLeft = MemoryMarshal.Cast<Complex, Vector256<double>>(left);
            var vectorRight = MemoryMarshal.Cast<Complex, Vector256<double>>(right);
            for (int i = 0; i < vectorRes.Length; i++)
                vectorRes[i] = Avx.Subtract(vectorLeft[i], vectorRight[i]);

            for (int i = 2 * vectorRes.Length; i < result.Length; i++)
                result[i] = left[i] - right[i];
            return result;
        }

        public static Span<Complex> Multiply(ReadOnlySpan<Complex> left, ReadOnlySpan<Complex> right)
        {
            var result = new Complex[Math.Min(left.Length, right.Length)].AsSpan();
            var vectorRes = MemoryMarshal.Cast<Complex, Vector256<double>>(result);
            var vectorLeft = MemoryMarshal.Cast<Complex, Vector256<double>>(left);
            var vectorRight = MemoryMarshal.Cast<Complex, Vector256<double>>(right);
            for (int i = 0; i < vectorRes.Length; i++)
            {
                var l = vectorLeft[i];
                var r = vectorRight[i];
                vectorRes[i] = Avx.HorizontalAdd(
                    Avx.Multiply(
                        Avx.Multiply(l, r),
                        Vector256.Create(1.0, -1.0, 1.0, -1.0)),
                    Avx.Multiply(
                        l,
                        Avx.Permute(r, 0b0101)
                        ));
            }
            for (int i = 2 * vectorRes.Length; i < result.Length; i++)
                result[i] = left[i] * right[i];
            return result;
        }

    }

This code performs 5 AVX operations for multiplying two complex numbers, whereas using the System.Numerics.Complex.Multiply would consume 8 multiplications and 4 additions.
(Of course, the code should check for Avx.IsEnabled - skipped that for brevity)
I haven't bothered with the benchmarks, so not sure how much (if at all) gain would it produce on the modern CPUs.
Avx512 would allow using same 5 instructions for handling 4 complex at once; but that's pending the CLR support yet.

SIMD Vectors - Complex numbers?


dotnet System.Web.Caching.Cache vs System.Runtime.Caching.MemoryCache

Question: I've got a class that needs to store data in a cache.
Originally I used it in an asp.net application so I used System.Web.Caching.Cache.
Now I need to use it in a Windows Service.
Now, as I understand it, I should not use the asp.net cache in a not asp.net application, so I was looking into MemoryCache.
The problem is that they are not compatible, so either I change to use MemoryCache in the asp.net application, or I will need to create an adapter so ensure that the two cache implementations have the same interface (maybe derive from ObjectCache and use the asp.net cache internally?)
What are the implications of using MemoryCache in an asp.net?
Nadav
Comment: +1 interesting question.  The most obvious thing I'd see would be that MemoryCache and the ASP.NET Cache would be competing for memory resources.  This might translate into different behavior when there is memory pressure, as each have independently defined cache item priority.
Answer: I would go with your second option and refactor things a little bit. I would create an Interface and two Providers (which are your adapters):
<code>public interface ICachingProvider
{
    void AddItem(string key, object value);
    object GetItem(string key);
}

public AspNetCacheProvider : ICachingProvider
{
    // Adapt System.web.Caching.Cache to match Interface
}

public MemoryCacheProvider : ICachingProvider
{
    // Adapt System.Runtime.Caching.MemoryCache to match Interface
}
</code>
Comment: Where do you think that Common Interface would live? I suspect Microsoft didn't want to make it that you had to include some System.Runtime.*.dll as a requirement of using System.Web.Caching and likewise they made System.Runtime.Caching because they didn't want people to have to reference System.Web.* from their applications.
Comment: It just Irritating that there are two cache implementations in the BCL and they don't have a common interface :(
Comment: Well, an interface is not such a big thing that you can't put it in one of the base dlls.
Right now, If you want to cache data in a client you don't have anything( System.Runtime.Cache is in the Server profile).
Comment: Hi Justin,
This will probably be what I will do.
Answer: This morning I came across a library that could help with this situation. It's a CacheAdapter that allows you to code against a common interface and swap out the caching mechanism (System.Web.Caching, System.Runtime.Cache, or AppFabric) via configuration.
https://bitbucket.org/glav/cacheadapter
Comment: Yes, I just saw it yesterday :)


Android slidable listview with googlemaps

Question: I was wondering if there is any library for android that helps displaying listview and google map in the same screen, similar to the Transit app.
So, when u drag the blue listview header up, as in the picture, the list moves on top of the map, whereas the map shrinks but maintains the focus of the location dot in the center.
Answer: You may want to check this Android Sliding Up Panel library which provides a simple way to add a draggable sliding up panel (popularized by Google Music and Google Maps) to your Android application.
Simply add the following dependency to your build.gradle file to use the latest version:
dependencies {
    repositories {
        mavenCentral()
    }
    compile 'com.sothree.slidinguppanel:library:3.3.1'
}

Here's a sample  map animation (sliding panel) with ListView.


Geometry problem boils down to finding a closed form for $\sum_{n=1}^{k}{\arctan{\left(\frac{1}{n}\right)}}$

Question: I was solving the following problem:
"Find $\angle A + \angle B + \angle C$ in the figure below, assuming the three shapes are squares."

And I found a beautiful one-liner using complex numbers:
$(1+i)(2+i)(3+i)=10i$, so $\angle A + \angle B + \angle C = \frac{\pi}{2}$
Now, I thought, what if I want to generalize? What if, instead of three squares, there were $2018$ squares? What would the sum of the angles be then? Could I make a formula for $k$ squares?
Essentially, the question boiled down to finding a closed form for the argument of the complex number
$$\prod_{n=1}^{k}{(n+i)}=\prod_{n=1}^{k}{\left(\sqrt{n^2+1}\right)e^{i\cot^{-1}{n}}}$$
This we can break into two parts, finding a closed form for
$$\prod_{n=1}^{k}{(n^2+1)}$$
and
$$\sum_{n=1}^{k}{\cot^{-1}{n}}$$
This I don't know how to solve.
Comment: It seems you summed under the square root -- that would work if the square root were a logarithm, but it doesn't work for square roots. You can check that your result doesn't give the right values for the first few values of $k$. (Speaking of which, the products and summations run to $k$, whereas $n$ is just the summation index, so the free variable in the results should be $k$, not $n$.)
Comment: Oops, it seems that I mixed up my products and summations.
Answer: With CAS help:
$$\sum _{n=1}^k \tan ^{-1}\left(\frac{1}{n}\right)=\\\int \left(\sum _{n=1}^k \frac{\partial }{\partial a}\tan ^{-1}\left(\frac{a}{n}\right)\right) \, da=\\\int \left(\sum _{n=1}^k \frac{n}{a^2+n^2}\right) \,
   da=\\\int \frac{1}{2} \left(-H_{-i a}-H_{i a}+H_{-i a+k}+H_{i a+k}\right) \,
   da=\\-\frac{1}{2} i (\text{log$\Gamma $}(1-i a)-\text{log$\Gamma $}(1+i a)-\text{log$\Gamma
   $}(1-i a+k)+\text{log$\Gamma $}(1+i a+k))+C$$
where $a=1$ and $C=0$ then:
$$\color{blue}{\sum _{n=1}^k \tan ^{-1}\left(\frac{1}{n}\right)=-\frac{1}{2} i (\text{log$\Gamma
   $}(1-i)-\text{log$\Gamma $}(1+i)-\text{log$\Gamma $}((1-i)+k)+\text{log$\Gamma
   $}((1+i)+k))}$$
Where: $H_{i a}$ is harmonic number and $\text{log$\Gamma $}(1-i)$ is  logarithm of the gamma function
MMA code:
<code>HoldForm[Sum[ArcTan[1/n], {n, 1, k}] == -(1/2)
I (LogGamma[1 - I] - LogGamma[1 + I] - LogGamma[(1 - I) + k] + LogGamma[(1 + I) + k])] // TeXForm
</code>
Comment: cute starting point ! (+1).  Now use the fact that $\Gamma (\tilde z) = \tilde \Gamma (z)$ to simplify a further step and reach to the same conclusion as in my answer : $Im(ln(\Gamma(1+i+k) / \Gamma(1+i)))$
Comment: An integral sign is missing on the second line. By the way, great answer!
Comment: Moreover, I don't think that $C=0$. Consider the case $a=0$.
Comment: @Szeto. Case is only $a=1$,there are No others cases. `:)`
Answer: Playing around with Wolfy suggests that
$s(n)
=\sum_{k=1}^n \arctan(1/k)
=\frac{3\pi}{4}-\frac12\arctan(g(n))
$
where
$g(n)$ is an increasingly complicated fraction.
Some values are
$g(4) = 15/8,
g(5) = 140/71,
g(6) = 2848/7665,
g(7) = 14697/203896
$.
To get a recurrence for
$g(n)$,
$\begin{array}\\
s(n+1)-s(n)
&=\arctan(1/(n+1))\\
&=(\frac{3\pi}{4}-\frac12\arctan(g(n+1)))-(\frac{3\pi}{4}-\frac12\arctan(g(n)))\\
&=\frac12(\arctan(g(n))-\arctan(g(n+1))\\
\end{array}
$
so,
using
$\arctan(x)\pm\arctan(y)
=\arctan(\frac{x\pm y}{1\mp xy})
$,
$\begin{array}\\
\arctan(g(n+1))
&=\arctan(g(n))-2\arctan(1/(n+1))\\
&=\arctan(g(n))-\arctan(\frac{2/(n+1)}{1-1/(n+1)^2})\\
&=\arctan(g(n))-\arctan(\frac{2(n+1)}{(n+1)^2-1})\\
&=\arctan(g(n))-\arctan(\frac{2(n+1)}{n^2+2n})\\
&=\arctan(\frac{g(n)-\frac{2(n+1)}{n^2+2n}}{1+g(n)\frac{2(n+1)}{n^2+2n}})\\
&<\arctan(g(n)-\frac{2}{n+1})\\
\end{array}
$
so,
assuming that
the proper branch of
arctan is taken,
$g(n+1)
=\frac{g(n)-\frac{2(n+1)}{n^2+2n}}{1+g(n)\frac{2(n+1)}{n^2+2n}}
\lt g(n)-\frac{2}{n+1}
$.
Since $\sum 1/n$ diverges,
this shows that
exentually
$g(n) < 0$.
At this point the
next branch of
arctan has to be taken.
For example,
Wolfy calculates that
$s(20)
=\frac{5 π}{4} - \frac12 \arctan(\frac{47183650393321137025}{17864397263976449928})
$
and
$s(40)
=\frac{5π}{4} + \frac12 \arctan(\frac{41279370979134545450499387615832498927444174194743607}{269197868658553203529942799672226208517623565372926024})
$.
I'll leave it at this.
Comment: Sadly no matches for fraction on OEIS.
Answer: We have that
$$
\prod\limits_{1\, \le \,n\, \le \,k} {\left( {i + n} \right)}  = {1 \over i}\prod\limits_{0\, \le \,n\, \le \,k} {\left( {i + n} \right)}
  = {1 \over i}i^{\,\overline {\,k + 1\,} }  = \left( {1 + i} \right)^{\,\overline {\,k\,} }
 = {{\Gamma \left( {1 + i + k} \right)} \over {\Gamma \left( {1 + i} \right)}} = k!\left( \matrix{
  i + k \cr
  k \cr}  \right)
$$
where $x^{\,\overline {\,k\,} }  = {{\Gamma (x + k)} \over {\Gamma (x)}}$ denotes the Rising Factorial
and $x^{\,\underline {\,k\,} }  = \left( {x - k + 1} \right)^{\,\overline {\,k\,} } $ the Falling Factorial.
By means of the expression through The Gamma Function, they are defined as meromorphic
functions even for complex $x$ and $k$.
Then
$$
\ln \left( {z^{\,\overline {\,k\,} } } \right) = \ln \left( {\left| {z^{\,\overline {\,k\,} } } \right|} \right) + i\arg \left( {z^{\,\overline {\,k\,} } } \right)
 = \ln {{\Gamma (z + k)} \over {\Gamma (z)}}
$$
The above tells us that your question is related to the absolute value and argument of the Gamma Function,
which unfortunately do not have a closed expression, better than the above.
Comment: The Gamma function ($\Gamma (x)$) is the same as an offset factorial ($(x - 1)!$), but defined in such a way that it is usable for non-integer values of $x$. $i^{\,\overline {\,k + 1\,}}$ in this context is the rising factorial: $i(i + 1)(i + 2) \cdots (i + k - 1)(i + k)$.
Comment: I get the first and second steps but I don't understand what $\overline{k+1}$ and $\Gamma$ are. Could you please explain?
Comment: @ShreyJoshi From context I assume it's a strange factorial variant: $a^{\overline{b}} = (a+b)!/a!$?
Comment: Actually the third, fourth and fifth steps are not necessary. This can be derived directly from the definition of generalized binomial coefficients.
Comment: @above, thank you for clearing it all up, I see how it fits together much better now. One thing I find funny is how we can define factorials and choose functions for imaginary numbers. It would also be interesting to see what would happen for fractional $k$.
Comment: But it still feels like cheating, expanding the choose function yields the same as the product of $(n+i)$. What I'm looking for is a closed form solution which reduces computation.
Comment: @ShreyJoshi: added some more details, wishing they are enough. Concerning the ".. solution which reduces computation" , since the Gamma Function computation algorithm is quite available in many platforms, please be more specific on what you are looking for.
Comment: @user7530: it is a common way to designate the Rising Factorial (also called Pochhammer symbol. See the added details
Comment: @ShreyJoshi: the Gamma Function allows for such an extension, where both the upper and lower terms of the binomial coefficient can be not only fractional, but real and even complex! (except for negative integers). For your curiosity $\binom{1}{1/2}=4/ \pi$.
Answer: Note that the addition formula for the arctangent gives $\arctan(x)+\arctan(y)=\arctan(\dfrac{x+y}{1-xy})$; thus, if we define $\alpha_n$ by $\arctan(\alpha_n)=\sum_{i=1}^n\arctan(\frac1i)$, then we have $\alpha_n=\dfrac{\alpha_{n-1}+\frac1n}{1-\frac{\alpha_{n-1}}{n}}$ $=\dfrac{n\alpha_{n-1}+1}{n-\alpha_{n-1}}$; alternately, setting $\alpha_n=\frac{a_n}{b_n}$, we can write this as $a_n=na_{n-1}+b_{n-1}, b_n = -a_{n-1}+nb_{n-1}$ - or $\begin{pmatrix}a_n \\ b_n \end{pmatrix} = \begin{pmatrix}n & 1 \\ -1 & n\end{pmatrix}\begin{pmatrix}a_{n-1} \\ b_{n-1} \end{pmatrix}$.  This 'blows up' at $n=3$ (since there's a division by zero), but because the equation in terms of $a_n$ and $b_n$ is homogeneous, we can continue through that point with a rescaling: $(a_n, b_n) (1\leq n\leq 3) =\langle(1, 1), (3, 1), (10, 0)\rangle$, and rescaling to take $a_3=1, b_3=0$ we get $a_4=4, b_4=-1$; $a_5=19, b_5=-9$; $a_6=105, b_6=-73$; $a_7=662, b_7=-616$; etc. Unfortunately, I also can't find any references to this series, and the OEIS doesn't seem to be any help.


project Can not execute Findbugs: java.lang.ArrayIndexOutOfBoundsException

Question: I am using sonarQube4.5.7 version with JDK 1.8 version. currently getting this error on running
mvn sonar:sonar

command. can anyone suggest me how to resolve this error.
Logs are:
Unable to get XClass for java/lang/StringBuilder
java.lang.ArrayIndexOutOfBoundsException: 26721
At org.objectweb.asm.ClassReader.readClass(Unknown Source)
At org.objectweb.asm.ClassReader.accept(Unknown Source)
At edu.umd.cs.findbugs.asm.FBClassReader.accept(FBClassReader.java:44)
At org.objectweb.asm.ClassReader.accept(Unknown Source)
At edu.umd.cs.findbugs.classfile.engine.ClassParserUsingASM.parse(ClassParserUsingASM.java:110)
At edu.umd.cs.findbugs.classfile.engine.ClassParserUsingASM.parse(ClassParserUsingASM.java:587)
At edu.umd.cs.findbugs.classfile.engine.ClassInfoAnalysisEngine.analyze(ClassInfoAnalysisEngine.java:76)
At edu.umd.cs.findbugs.classfile.engine.ClassInfoAnalysisEngine.analyze(ClassInfoAnalysisEngine.java:38)
At edu.umd.cs.findbugs.classfile.impl.AnalysisCache.getClassAnalysis(AnalysisCache.java:268)
At edu.umd.cs.findbugs.ba.XFactory.getXClass(XFactory.java:652)
At edu.umd.cs.findbugs.ba.ch.Subtypes2.addInheritanceEdge(Subtypes2.java:1260)
At edu.umd.cs.findbugs.ba.ch.Subtypes2.addSupertypeEdges(Subtypes2.java:1233)
At edu.umd.cs.findbugs.ba.ch.Subtypes2.addClassAndGetClassVertex(Subtypes2.java:275)
At edu.umd.cs.findbugs.ba.ch.Subtypes2.addClass(Subtypes2.java:244)
At edu.umd.cs.findbugs.ba.AnalysisContext.setAppClassList(AnalysisContext.java:941)
At edu.umd.cs.findbugs.FindBugs2.setAppClassList(FindBugs2.java:997)
At edu.umd.cs.findbugs.FindBugs2.execute(FindBugs2.java:225)
At org.sonar.plugins.findbugs.FindbugsExecutor$FindbugsTask.call(FindbugsExecutor.java:207)
At java.util.concurrent.FutureTask.run(FutureTask.java:266)
At java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
At java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
At java.lang.Thread.run(Thread.java:745)

Answer: You may have hit bug here. Try with jdk 7 or upgrade findbug pluguin.


Função ajax para enviar lista de itens a um método C# em Asp.net

Question: Tenho uma lista de itens em uma página ASP.NET definida como:

Banana

Maçã

Melão

Abacaxi

Uva

Como essa lista é editável na página, gostaria de alguma função ajax/javascript para chamar um método C# no CodeBehind (digamos, um WebMethod chamado EnviarLista()) que enviasse essa lista de itens como parâmetro. Essa função seria chamada através de um botão asp:LinkButton chamado "Salvar".
Como seria essa função em ajax/javascript? Como poderia linkar essa função ao botão "Salvar"?
Comment: Se ta usando BulletedList e com jQuery.sortable ... ?
Comment: Isso mesmo! Não falei antes porque no final, uma BulletedList vira isso aí em cima, mas o exemplo que você mostrou embaixo é exatamente da forma como está no meu programa.
Answer: Se sua dúvida for com BulletedList utilizando jQuery.sortable, tenho esse código:
aspx
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebLista.aspx.cs" Inherits="WebApplication1.WebLista" %>
    <!DOCTYPE html>

        <title></title>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" />

        <form id="form1" runat="server">

            <asp:BulletedList ID="BulletedList1"
                DataTextField="Numero"
                Width="220"
                DataValueField="Index"
                runat="server">
            </asp:BulletedList>

<asp:Label Text="" ID="LblResposta" ViewStateMode="Disabled" ClientIDMode="Static" runat="server" />

            <asp:Button ID="ButSalvar" OnClick="ButSalvar_Click" runat="server" Text="Button" />
            <button type="button" onclick="Gravar();">Gravar</button>
        </form>

cs
using System;
using System.Web.Services;
using System.Web.UI.WebControls;
namespace WebApplication1
{
    public partial class WebLista : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Call_List();
            }
            Call_List_Css();
        }
        private void Call_List()
        {
            BulletedList1.DataSource = new object[]
            {
                new {Index = 1, Numero="Numero 1"},
                new {Index = 2, Numero="Numero 2"}
            };
            BulletedList1.DataBind();
        }
        private void Call_List_Css()
        {
            if (BulletedList1 != null && BulletedList1.Items.Count > 0)
            {
                foreach (ListItem li in BulletedList1.Items)
                {
                    li.Attributes.Add("id", string.Format("{0}", li.Value));
                    li.Attributes.Add("class", "ui-state-default");
                }
            }
        }
        protected void ButSalvar_Click(object sender, EventArgs e)
        {
            if (BulletedList1.Items.Count > 0)
            {
                LblResposta.Text = "";
                foreach (ListItem li in BulletedList1.Items)
                {
                    LblResposta.Text += string.Format("
{0} - {1}
", li.Value, li.Text);
                }
            }
        }
        [WebMethod()]
        public static string Save_Ordem(string[] Texto)
        {
            //aqui você ia trabalhar o código!
            //sendo que ele mandar um lista ordenada igual na tela !!!
            return "";
        }

    }
}

Tela no Navegador

Ao clicar no Botão Gravar ele vai enviar um Ajax no Formato Json e você vai pegar a ordem estabelecida na tela e com essa ordem gravar os dados da maneira que desejar no Web Method Save_Ordem:
[WebMethod()]
public static string Save_Ordem(string[] Texto)
{
      //aqui você ia trabalhar o código!
      //sendo que ele mandar um lista ordenada igual na tela !!!
      return "";
}

Exemplo do que ele envia:

Observações:
private void Call_List()
{
       BulletedList1.DataSource = new object[]
       {
           new {Index = 1, Numero="Numero 1"},
           new {Index = 2, Numero="Numero 2"}
       };
       BulletedList1.DataBind();
}

Perceba que o método Call_List ta carregando dados fixos, faças as devidas alterações e perceba que há relação disso com a tela ...
Outra ponto é mudar para RedirectMode.Off, no RouteConfig da pasta App_Start, senão ta dando erro 401:
public static class RouteConfig
{
     public static void RegisterRoutes(RouteCollection routes)
     {
         var settings = new FriendlyUrlSettings();
         settings.AutoRedirectMode = RedirectMode.Off;
         routes.EnableFriendlyUrls(settings);
     }
}

Comment: Eu desabilitei isso que eu to lembrando agora: no App_Start, no RouteConfig.cs eu deixei assim: settings.AutoRedirectMode = RedirectMode.Off; eu editei no post como obs
Comment: Cara, é EXATAMENTE isso que estou procurando. Só não tenho como testar agora no meu projeto, mas como é a primeira solução que apareceu aqui, já tá valendo! Muito obrigado!
Comment: Se você copiar o fonte já tem um página de exemplo !!!
Comment: Testei aqui e deu certo, só tive que ajustar alguns detalhes aqui. Mas de alguma maneira, o botão Grava não funciona... no browser do navegador, o console diz: "`Failed to load resource: the server responded with a status of 404 (Not Found)`". Sendo que o código está exatamente como acima. Alguma ideia do que seja?
Comment: OK, funcionou agora! Não era nem isso, era outra coisa que eu tinha esquecido de mudar... hehehe Mas muito obrigado mesmo!
Comment: O que era ... kkk ?
Comment: Eu tinha esquecido de mudar a url na function Gravar, pois eu tinha mudado o nome do Webmethod... (shame on me)


Como separar uma string em unity c#

Question: Queria saber como separar uma string em unity C#, acabei olhando algumas perguntas parecidas para C# soque não em unity, achei muitas vezes esse exemplo
string[] linha = reader.ReadLine().Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);

e da erro de que a função StringSplitOptions não existe no contexto, então gostaria de saber um método.
Eis o que quero fazer, eu terei em um arquivo TXT uma linha de texto que eu quero separar por o texo para cada || , Ex:
" Você acorda, o que faz?||Dormir mais||2||Levantar||1||Sentar e esperar||2||Cair da cama||3$2||1<> "

quero separar este texto da seguinte forma;
string lin1 = "Você acorda, o que faz?"
string lin2 = "Dormir mais"
string lin3 = "2"
string lin4 = "Levantar"
string lin5 = "1"
string lin6 = "Sentar e esperar"
string lin7 = "2"
string lin8 = "Cair da cama"
string lin9 = "3$2"
string lin10 = "1"

Obs: o <> em teoria é para servir como quebra de linha;
Comment: Jovem, conseguiu resolver seu problema? A resposta atendeu o que você precisava ou precisa que algo seja melhorado?
Answer: O que acontece é que Unity roda numa versão bem antiga do Mono. E nesta versão, algumas coisas que estamos acostumados não estão implementadas.
O método Split, nesta versão, não tem nenhuma sobrecarga que aceite como parâmetro um array de strings e um StringSplitOptions.
Em contrapartida, existe uma sobrecarga que aceita um array de chars e um StringSplitOptions.
Neste caso, será impossível quebrar o texto a cada par de pipes (|), mas como você estará usando a opção RemoveEmptyEntries, acaba-se tendo o mesmo resultado final.
reader.ReadLine().Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

Veja funcionando no .NET Fiddle.
Comment: Obrigado!!, funcionou perfeitamente agora.

Como separar uma string em unity c#