Is there any geometric intuition for the factorials in Taylor expansions?

Question: Given a smooth real function $f$, we can approximate it as a sum of polynomials as
$$f(x+h)=f(x)+h f'(x) + \frac{h^2}{2!} f''(x)+ \dotsb = \sum_{k=0}^n \frac{h^k}{k!} f^{(k)}(x) + h^n R_n(h),$$
where $\lim_{h\to0} R_n(h)=0$.
There are multiple ways to derive this result. Some are already discussed in the answers to the question "Where do the factorials come from in the taylor series?".
An easy way to see why the $1/k!$ factors must be there is to observe that computing $\partial_h^k f(x+h)\rvert_{h=0}$, we need the $1/k!$ factors to balance the $k!$ factors arising from $\partial_h^k h^k=k!$ in order to get a consistent result on the left- and right-hand sides.
However, even though algebraically it is very clear why we need these factorials, I don't have any intuition as to why they should be there. Is there any geometrical (or similarly intuitive) argument to see where they come from?
Comment: Check out 3Blue1Brown's [video](https://www.youtube.com/watch?v=3d6DsjIBzJ4) on Taylor series.
Comment: Answering this question would take some serious [balls](http://en.wikipedia.org/wiki/Volume_of_an_n-ball).
Comment: @XanderHenderson I think a very nice one can be obtained via the FTC at [17:01 of 3b1b's video](https://youtu.be/3d6DsjIBzJ4?t=1021). I think the same idea can be pushed to 3D to also see the $1/6$ factor arising [with something like this](https://i.stack.imgur.com/X0qzG.png) (green volume is the linear correction, purple the second order correction with factor $\frac12$, red the third order one with factor $\frac16$). These are essentially visual representations of the ideas in [the currently most upvoted answer](https://math.stackexchange.com/a/3753600/173147)
Comment: The question specifically highlights a "geometric" intuition (or other similarly intuitive explanation, but...).  For my money, there should be a really stellar *picture* which gives this intuition.  I don't see it myself, but I imagine that someone else has the idea.  I would very much like to see such a figure.
Comment: @glS Indeed.  The point of my comment was to encourage an answerer to include such a figure or representation here.  Math SE is meant to be relatively self-contained, thus off-site links aren't as good as inline images here.
Comment: Xander brought this question up in [the Pearl Dive](https://chat.stackexchange.com/rooms/102837/pearl-dive).
Comment: Instead of geometric there is a "categorifical" intuition of this where the $n!$ are seen as the action of a symmetric group on $n$ elements. see the first answer of: https://mathoverflow.net/questions/43579/examples-of-categorification
Answer: Yes. There is a geometric explanation.
For simplicity, let me take $x=0$ and $h=1$.
By the Fundamental Theorem of Calculus (FTC),
$$
f(1)=f(0)+\int_{0}^{1}dt_1\ f'(t_1)\ .
$$
Now use the FTC for the $f'(t_1)$ inside the integral, which gives
$$
f'(t_1)=f'(0)+\int_{0}^{t_1}dt_2\ f''(t_2)\ ,
$$
and insert this in the previous equation.
We then get
$$
f(1)=f(0)+f'(0)+\int_{0}^{1}dt_1\int_{0}^{t_1}dt_2 f''(t_2)\ .
$$
Keep iterating this, using the FTC to rewrite the last integrand, each time invoking a new variable $t_k$.
At the end of the day, one obtains
$$
f(1)=\sum_{k=0}^{n}\int_{\Delta_k} dt_1\cdots dt_k\ f^{(k)}(0)\ +\ {\rm remainder}
$$
where $\Delta_k$ is the simplex
$$
\{(t_1,\ldots,t_k)\in\mathbb{R}^k\ |\ 1>t_1>\cdots>t_k>0\}\ .
$$
For example $\Delta_{2}$ is a triangle in the plane, and $\Delta_3$ is a tetrahedron in 3D, etc.
The $\frac{1}{k!}$ is just the volume of $\Delta_k$. Indeed, by a simple change of variables (renaming), the volume is the same for all $k!$ simplices of the form
$$
\{(t_1,\ldots,t_k)\in\mathbb{R}^k\ |\ 1>t_{\sigma(1)}>\cdots>t_{\sigma(k)}>0\}
$$
where $\sigma$ is a permutation of $\{1,2,\ldots,k\}$.
Putting all these simplices together essentially reproduces the cube $[0,1]^k$ which of course has volume $1$.
Exercise: Recover the usual formula for the integral remainder using the above method.
Remark 1: As Sangchul said in the comment, the method is related to the notion of ordered exponential. In a basic course on ODEs, one usually sees the notion of fundamental solution $\Phi(t)$ of a linear system of differential equations $X'(t)=A(t)X(t)$. One can rewrite the equation for $\Phi(t)$ in integral form and do the same iteration as in the above method with the result
$$
\Phi(s)=\sum_{k=0}^{\infty}\int_{s\Delta_k} dt_1\cdots dt_k\ A(t_1)\cdots A(t_k)\ .
$$
It is only when the matrices $A(t)$ for different times commute, that one can use the above permutation and cube reconstruction, in order to write the above series as an exponential. This happens in one dimension and also when $A(t)$ is time independent, i.e., for the two textbook examples where one has explicit formulas.
Remark 2: The method I used for the Taylor expansion is related to how Newton approached the question using divided differences.
The relation between Newton's iterated divided differences and the iterated integrals I used is provide by the Hermite-Genocchi formula.
Remark 3: These iterated integrals are also useful in proving some combinatorial identities, see this MO answer:
https://mathoverflow.net/questions/74102/rational-function-identity/74280#74280
They were also used by K.T. Chen in topology, and they also feature in the theory of rough paths developed by Terry Lyons.

The best I can do, as far as (hopefully) nice figures, is the following.
The simplex $\Delta_1$

has one-dimensional volume, i.e., length $=1=\frac{1}{1!}$.
The simplex $\Delta_2$

has two-dimensional volume, i.e., area $=\frac{1}{2}=\frac{1}{2!}$.
The simplex $\Delta_3$

has three-dimensional volume, i.e., just volume $=\frac{1}{6}=\frac{1}{3!}$.
For obvious reasons, I will stop here.
Comment: Nice rendition using ordered exponential!
Comment: I have put a bounty on this question in hopes of getting some nice *figures*.  I find it hard to believe that a geometrical interpretation is not amenable to nice graphics.  If you have the inclination, I think that some of the ideas you present would make for nice visualizations.
Comment: I was just about to add a picture showing how a cube is split into six identical simplices by the planes $x=y$, $y=z$ and $z=x$. But then you had already added pictures, so I guess that would be pointless. Anyway, thanks for a nice answer as well as doing your best visualizing it :-)
Comment: I think this would be much clearer if you didn't take $h=1$ but left it general
Comment: @XanderHenderson: Not that easy to explain this visually, but I gave it a try.
Comment: @JyrkiLahtonen: Thanks. What would be best would be an animation where the six identical pieces would be moved around and recombined into the unit cube. However, this is way beyond my current skills.
Comment: I think one half of them are mirror images of the other half, so they cannot be shown as rotated copies of the same piece. I am practicing animations with Mathematica (for fun as well as for educational material), so I might give it a try.
Comment: Too late an hour. FWIW the next to last picture [here](https://math.stackexchange.com/a/3665362/11619) shows all eight octants split into six simplices like here.
Comment: @JyrkiLahtonen: You are correct of course. One needs three identical pieces and three mirror images, which reflects the sign of the six permutations.
Answer: Here is a heuristic argument which I believe naturally explains why we expect the factor $\frac{1}{k!}$.
Assume that $f$ is a "nice" function. Then by linear approximation,
$$ f(x+h) \approx f(x) + f'(x)h. \tag{1} $$
Formally, if we write $D = \frac{\mathrm{d}}{\mathrm{d}x}$, then the above may be recast as $f(x+h) \approx (1 + hD)f(x)$. Now applying this twice, we also have
\begin{align*}
f(x+2h)
&\approx f(x+h) + f'(x+h) h \\
&\approx \left( f(x) + f'(x)h \right) + \left( f'(x) + f''(x)h \right)h \\
&= f(x) + 2f'(x)h + f''(x)h^2. \tag{2}
\end{align*}
If we drop the $f''(x)h^2$ term, which amounts to replacing $f'(x+h)$ by $f'(x)$, $\text{(2)}$ reduces to $\text{(1)}$ with $h$ replaced by $2h$. So $\text{(2)}$ may be regarded as a better approximation to $f(x+2h)$, with the extra term $f''(x)h^2$ accounting for the effect of the curvature of the graph. We also note that, using $D$, we may formally express $\text{(2)}$ as $f(x+2h) \approx (1+hD)^2 f(x)$.
Continuing in this way, we would get
$$ f(x+nh) \approx (1+hD)^n f(x) = \sum_{k=0}^{n} \binom{n}{k} f^{(k)}(x) h^k. \tag{3} $$
So by replacing $h$ by $h/n$,
$$ f(x+h) \approx \left(1 + \frac{hD}{n}\right)^n f(x) = \sum_{k=0}^{n} \frac{1}{n^k} \binom{n}{k} f^{(k)}(x) h^k. \tag{4} $$
Now, since $f$ is "nice", we may hope that the error between both sides of $\text{(4)}$ will vanish as $n\to\infty$. In such case, either by using $\lim_{n\to\infty} \frac{1}{n^k}\binom{n}{k} = \frac{1}{k!}$ or $\lim_{n\to\infty} \left(1 + \frac{a}{n}\right)^n = e^a = \sum_{k=0}^{\infty} \frac{a^k}{k!} $,
$$ f(x+h) = e^{hD} f(x) = \sum_{k=0}^{\infty} \frac{1}{k!} f^{(k)}(x) h^k . \tag{5} $$

Although this above heuristic leading to $\text{(5)}$ relies on massive hand-waving, the formal relation in $\text{(5)}$ is justified in the context of functional analysis and tells that $D$ is the infinitesimal generator of the translation semigroup.
Comment: this is a very nice way to see it. A few notes: there is an $h$ missing in the second row of (2) I think. Also, if you rewrite (2) with $h\to h/2$, isn't the last factor off? You would get $f(x+h)=f(x)+f'(x)h + \frac14 f''(x) h^2$
Comment: @glS, Glad it helped! It was also quite appealing to me when I first heard this approach. Also thank you for pointing out the typos. I fixed them now.
Comment: thanks. Isn't the factor still off though? Or am I missing something?
Comment: @glS, That is a valid objection. Answering to that question, another half of the second-order term is buried in the error of that hand-waving relation $\approx$. Thankfully, the missing part is eventually retrieved as $n \to \infty$, although analyzing what exactly happens in that process now requires more than heuristics.
Comment: ah, I see. So to get the correct $1/2$ term we actually need to apply infinitely many times the linear approximation: $\left(1+ \frac{h}{n}D\right)^n=1+hD+ \binom{n}{2}\frac{h^2}{n^2}D^2+(...)$ and thus only for $n\to \infty$ we have $\binom{n}{2}\frac1{n^2}\to\frac12$.
Comment: @glS, That is correct :)
Comment: (+1) This is a very clear heuristic explanation.  Well done.
Answer: The polynomials
$$p_k(h):=\frac{h^k}{k!}$$
have two remarkable properties:

they are derivatives of each other, $p_{k+1}'(h)=p_k(h)$,

their $n^{th}$ derivative at $h=0$ is $\delta_{kn}$ (i.e. $1$ iff $n=k$, $0$ otherwise).

For this reason, they form a natural basis to express a function in terms of the derivatives at a given point: if you form a linear combination with coefficients $c_k$, evaluating the linear combination at $h=0$ as well as the derivatives of this linear combination at $h=0$, you will retrieve exactly the coefficients $c_k$.
The denominators $k!$ ensure sufficient damping of the fast growing functions $h^k$ for the unit condition to hold and act as normalization factors.

$$\begin{pmatrix}f(x)\\f'(x)\\f''(x)\\f'''(x)\\f''''(x)\\\cdots\end{pmatrix}=
\begin{pmatrix}1&h&\frac{h^2}2&\frac{h^3}{3!}&\frac{h^4}{4!}&\cdots
\\0&1&h&\frac{h^2}2&\frac{h^3}{3!}&\cdots
\\0&0&1&h&\frac{h^2}2&\cdots
\\0&0&0&1&h&\cdots
\\0&0&0&0&1&\cdots
\\&&&\cdots
\end{pmatrix}
\begin{pmatrix}f(0)\\f'(0)\\f''(0)\\f'''(0)\\f''''(0)\\\cdots\end{pmatrix}$$
$$\begin{pmatrix}f(0)\\f'(0)\\f''(0)\\f'''(0)\\f''''(0)\\\cdots\end{pmatrix}=
\begin{pmatrix}1&0&0&0&0&\cdots
\\0&1&0&0&0&\cdots
\\0&0&1&0&0&\cdots
\\0&0&0&1&0&\cdots
\\0&0&0&0&1&\cdots
\\&&&\cdots
\end{pmatrix}
\begin{pmatrix}f(0)\\f'(0)\\f''(0)\\f'''(0)\\f''''(0)\\\cdots\end{pmatrix}$$
Comment: @JacobMaibach I think it's quite clear why $c_k = f^{(k)}(x)$ are the coefficients, simply because differentiating $k$ times and evaluating at $h=0$ yields exactly that relation.
Comment: Good answer, but it feels a bit incomplete without explaining why $c_{k} = f^{(k)}(x)$. Something like $c_{k} = k f^{(k)}(x)$ could seem plausible to someone who didn't know better. Although I guess a quick look at the expansion of the exponential function would clear that up.
Comment: @JacobMaibach: it's all in $\delta_{kn}$. Feel free to provide your own answer.
Answer: The simplest way to look it is that the second derivative of $x^2$ is $2x= 2= 2!$, the third derivative of $x^3$ is $6= 3!$, and, in general, the $n$'th derivative of $x^n$ is $n!$.  That's where the factorials in the Taylor series come from.
If
$$f(x)= \frac{a_0}{0!} + \frac{a_1}{1!}(x- q)+ \frac{a_2}{2!}(x- q)^2+  \frac{a_3}{3!}(x- q)^3+ \cdots$$
then
$$f(q)= a_0,$$
$$f'(q)= a_1,$$
$$f''(q)= a_2,$$
$$f'''(q)= a_3,$$
and in general the $n$'th derivative $f^{(n)}(q) = a_n$.
The point of the factorial in the denominator is to make those derivatives come out right.
Answer: I claim that if you understand why $\exp(x)$ has the form it does, the Taylor expansion makes more sense. Usually, when thinking about the Taylor expansion, we imagine that we are representing a function $f(x)$ as a 'mix' of polynomial terms, which is reasonable, but we could also think of it as a mix of exponential terms.
Why is this? Well, recall that $\exp(x)$ satisfies $\frac{d}{dx} \exp(x) = \exp(x)$. In fact, if we try to find functions $g(x)$ such that $\frac{dg}{dx} = g(x)$, we find that $g(x) = A \exp(x)$ for some constant $A$. This is a critial property of the exponential, and in fact if we try to solve $\frac{d^{k}}{dx^{k}}g(x) = g(x)$ for other values of $k$, we find that again $A \exp(x)$ is a solution. For some $k$ (e.g. $k=4$), there are other solutions, but the functions $A \exp(x)$ are the only ones that work for all $k$.
This allows us to 'store' information about the derivatives of $f(x)$ in the exponential.
That is, we want to build a function with the same $k^{th}$ derivative as $f$ at particular value of $x$, we can. In fact, we can do so for all $k$ at the same time. And we do it by patching togther exponential functions in a clever, although kinda opaque, way.
To be precise, it comes out as
$$f(x+h) = f(x) \exp(h) + (f'(x) - f(x)) (\exp(h) - 1) + (f''(x) - f'(x)) (\exp(h) - 1 - h) \ + \ ...$$
which does not seem particularly illuminating (there is a nice explanation in terms of what are called generalized eigenvectors). But regardless, it is possible, which is important.
As for why does the exponential has the form it does, I would point you to other questions on MSE such as this that dig into it. What I will say is that the form $x^{k}/k!$ is deeply linked to the exponential, so anytime you see something like that it makes sense to think of the exponential. It certainly shows up in other places in math, even in something like combinatorics which is far from calculus (see exponential generating functions).
[This answer was partially a response to the answer by @YvesDaoust, but I'm not sure it really succeeds in making things clearer.]
Answer: Sure.

The iterated integral of $x\to 1$ $n$ times :

$$\cases{I_1(t) = \displaystyle \int_0^t 1 d\tau\\ I_n(t) = \displaystyle \int_0^{t} I_{n-1}(\tau) d\tau}$$
gives us $$\left\{1,x,\frac{x^2}{2!},\frac{x^3}{3!},\cdots,\frac{x^k}{k!},\cdots\right\}$$
together with

Linearity of differentiation : $\frac{\partial \{af(x)+bg(x)\}}{\partial x} = \frac{\partial \{af(x)\}}{\partial x} + \frac{\partial \{bg(x)\}}{\partial x}$

Area-under-curve interpretation of integral of non-negative functions.

gives a geometric interpretation for this. It is basically an iterated area-under-curve calculation for each monomial term in the Taylor expansion.
Answer: I think it can't be done using only simple geometric rules of inference. A geometric proof is a proof using only very simple geometric rules of inference. A geometric proof can tell you that $\forall x \in \mathbb{R}\sin'(x) = \cos(x) \text{and} \cos'(x) = -\sin(x)$. I think geometry doesn't define what the graph $y = x^3$ is. We can however decide to informally say it to mean something else.
I suppose given that two points are the points (0, 0) and (1, 0), you could define (0.5, 0) to be the point such that a translation that moves (0, 0) to that point also moves that point to (1, 0) and can define all the ordered pairs of rational numbers in a similar way. This is too hard for me to figure out for sure but I guess we could also add axioms for distance and which points each Cauchy sequence of points approaches or something like that. Then given any real number $x$ in binary notation, we could compute the binary notation of $x^3$ and then find a way to approach the point $(x, x^3)$ using a geometrical argument.
For what the Taylor series of $\sin$ and $\cos$ are, you pretty much have to prove it through the method of checking that one Taylor series is a derivative of the other and the  other is the negative of the derivative of it. Then using geometry, given any real number $x$, you can sum up all the terms to find the point $(\sum_{i = 0}^\infty(-1)^i\frac{x^{2i}}{(2i)!}, \sum_{i = 0}^\infty(-1)^i\frac{x^{2i + 1}}{(2i + 1)!})$. Then using a lot of rigour, you can show that it will always be the same point as the point $(\cos(x), \sin(x))$ which is gotten by very simple means in geometry itself. It be be very simple to just construct the actual point in space $(\cos(x), \sin(x))$ from the binary notation of the real number $x$. However, computing that that point in fact has the coordinates $(\cos(x), \sin(x))$ is a bit more complicated.


Switching many threads using curl easy to single thread using curl multi

Question: I use libcurl easy interface and I create lots of threads in my c++ app to handle these http requests. I would like to convert the code to use libcurl multi instead. Conceptually, the idea is clear: instead of calling blocking curl_easy_perform on each curl easy handle from multiple threads I'll call a blocking curl_multi_perform from a single thread and this call internally will handle all attached curl easy handles.
Things that aren't clear to me:

how do I cancel any of the outstanding http requests that are being handled by the blocking curl_multi_perform call (from another thread). Similarly, would the same work with easy interface, can I end/about an http request from another thread while there is another thread does curl_easy_perform on that handle.
Is it ok to add new easy handles to a multi handle while there is another thread calls curl_multi_perform on the multi handle?
If I use curl_multi_remove_handle to abort one of outgoing http requests while it was loading data (let's say it was doing 1GB file download) then I can reuse the same handle right after that. Does curl close that tcp connection that was aborted in the middle? Otherwise, I don't see how that connection could possibly be reused without completely downloading entire 1GB body.

Is there a simple example that used to do multiple easy requests from different threads and same example converted to multi interface?
Answer: (This is really several questions disguised as one, which is not a good fit for stackoverflow.)
curl_multi_perform() doesn't block. It does as much as it can do for now, then it returns and expects the program to call it again when it's time or when there's activity on one of its sockets.
Ideally you can mark which transfers to stop in the other threads and as soon as curl_multi_perform() returns you can remove said easy handles from the multi handle and they're no longer in the game. Alternatively, you can use the individual transfer's callbacks (write/read/progress) to return error when you want that transfer to end.
It is not OK to use the same libcurl handle in more than one thread at any given moment. If you really need to use the same handle from more than one thread, then you need to do careful mutexing. See the libcurl treading man page. It is usually better to put things into qeueus from the other threads and let the single libcurl-using thread read handles or actions from that queue when it can, which then assures single thread access to the handles.
If you abort a transfer by removing the handle with curl_multi_remove_handle(), that transfer is aborted. Stopped. You can indeed reuse that handle immediately and if you just put it back in, it will be treated as a brand new transfer and unless you change any options in the easy handle it will simply start off from the beginning again with the same URL. Prematurely aborted transfers will of course be treated correctly, which might include closing the TCP connection if necessary.
Comment: after digging code, I came to the same conclusions, and implemented my code as a single thread that processes added/terminated http requests and loops url_multi_perform/wait


The device is not connected exception

Question: I try to open a large number of files but after 5000 files or so I get
<code>Exception in thread "Main" java.io.IOException: The device is not connected
</code>

Is this the expected behavior? Is there a way around it? I want to leave my code as straightforward as possible.
Answer:
Your operating system may limit the number of files one process can have open.
Generally you want to be careful with resources like open files in java. Unless you have a specific reason for keeping all of those open, you'd be better off reading through each file, extracting the data you want, and then closing.

What exactly are you trying to achieve?
Answer: An open file has some cost in resources, so that opening another file fails when many files are already open is expected behavior. At least it is expecte by myself.
see for example this: http://www.msfn.org/board/lofiversion/index.php/t101414.html
Answer: It should not be a problem opening thousands of files if you remember to close() your files when you are done using them?
If not, you force the operating system to maintain state for your open files, which usually is a limited resource.
If you really need lots of simultaneous open files, the solution depends on the circumstances.  What is it you need to do?  Please show code.

The device is not connected exception


How to interpret Turing Machine illustrations on p79 of Stephen Wolfram's "A New Kind of Science" book?

Question: I am reading Stephen Wolfram's "A New Kind of Science".
At present, I cannot understand how the cellular automata illustrations on p79 are created.
In the patterns, the active cell, representing the head, appears to change orientation between up and -45 degrees. However, none of the rules seem to include an active cell with an orientation other than up or down. How does the active cell orientation of -45 degrees come about in the patterns?
Am I missing something obvious (I am a beginner in this area)?
Answer: You have a simple rule. Just a mapping from 3 binary digits to 1 binary digit. For example:
111 - 0
110 - 0
101 - 0
100 - 1
011 - 1
010 - 1
001 - 1
000 - 0

Then you have some sequence of digits during time t0. For example 00111010. To find what will happen at time t1, you need to use this mapping. So 001 will be 1, then 011 will be 1, 111 = 0, then ... and 010 = 1. This way you will receive the sequence of the same length for the second generation (t1). And you move on further and further again till you will see repetition.
So on that pictures your X axis is this sequence (empty square 0, gray square 1). On your Y axis is how this sequence evolve under specific rule. In my example it was a rule 30 (because 00011110 = 30 in binary)
You can read high level overview here. Also these rules are simple, they can give rise to complex behavior.
P.S. paper was published in Nature (high level science journal) and considered revolutionized because it showed that complicated structures and motifs like dots on the leopard's skin or  the image on the shell can arise from really simple rules.
Comment: Thanks, I understand how they generally work as you described. And understand the example on the [previous page](https://www.wolframscience.com/nksonline/page-78). It is the appearance of the active cells pointing down and to the right (-45 degrees) on p79 that I don't get.
Answer: I think that it is an inconsistency between the printing of the rules and the diagrams.
If the downward (-90 degrees) arrows in the rules are replaced with arrows pointing to the bottom right (-45 degrees) then the rules seem to make sense.

How to interpret Turing Machine illustrations on p79 of Stephen Wolfram's “A New Kind of Science” book?


Distribuição log-normal em python

Question: Eu estou a tentar ajustar a distribuição log-normal a estes dados mas não sei como descobrir a média, o desvio-padrão e ajustar a curva da distribuição em Python (estou a usar o Jupyter no Anaconda). Já tinha tentado fazer isso com a distribuição normal, mas olhando melhor para o gráfico, parece que o que se ajusta mais aos dados é uma distribuição log-normal em vez de uma normal. Poderiam dizer-me como posso alterar o código e colocar uma distribuição log-normal em vez de normal, se faz favor, para o mesmo conjunto de dados?
<code>#amostra 22A
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm
import matplotlib.ticker as tkr
import scipy, pylab
import locale
locale.setlocale(locale.LC_NUMERIC, "de_DE")
plt.rcParams['axes.formatter.use_locale'] = True

df=pd.DataFrame({'frequencia_relativa': {'0-1': 0.282, '1-2': 0.316, '2-3': 0.171, '3-4': 0.068, '4-5': 0.085, '5-6': 0.026, '6-7': 0.026, '7-8': 0.009, '8-9': 0.009, '9-10': 0.0, '10-11': 0.0, '11-12': 0.009}})
df=df.reindex(['0-1', '1-2', '2-3', '3-4', '4-5', '5-6', '6-7',
       '7-8', '8-9', '9-10', '10-11', '11-12'])
plt.rcParams["figure.figsize"] = [15,8]
fig, ax =plt.subplots()
ax.bar(x=df.index, height=df.frequencia_relativa, alpha=0.5, width=0.9)
ax.set_xlabel('Tamanho lateral do triângulo ($\mu m$)', fontsize=22)
ax.set_ylabel('Frequência relativa', fontsize=22)
x_axis = np.arange(0, 10, 0.001)
plt.xticks(fontsize=18)
plt.yticks(fontsize=18)
#normal com média 2,232 e variância 1.88, conforme planilha
ax.plot(x_axis, norm.pdf(x_axis,2.232,1.888), linewidth=3)
#plt.show()
plt.savefig('output.png', dpi=500, bbox_inches='tight')
</code>
Comment: substitua `norm` por `lognorm` no código. Veja documentação: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html
Comment: @Lucas não estou a conseguir. Está a dar-me um gráfico estranho. Talvez seja porque não sei calcular a nova média e desvio padrão. Como posso calcular isso para este conjunto de dados e distribuição? Será que poderias colocar a tua hipótese como resposta se faz favor? Muito obrigada pela tua paciência e ajuda, sem ti não estaria a aprender tanto como tenho aprendido
Answer: Sua variável X ocorre no ponto médio das classes, X=[0.5,1.5,2.5, etc...,11.5 ] - a distribuição parece ser log normal com média possivelmente na classe 1.5 nesta escala, porém, se for mesmo log normal, deves procurar a média em Ln(x).
Transforme X em Ln(X); nesta escala a distribuição deve ser normal, mas também estará assimétrica por falta de resolução do histograma (por sub amostragem possivelmente); daí você retira o Ln(média) e o Ln(desvio padrão), gera um outro vetor Ln(X) mais refinado, calcula as frequências relativas usando a distribuição normal padrão em Z (média zero, desvio 1) e leva de volta este vetor para o espaço da sua variável X usando X = exp(Ln(média) + Z * Ln(desvio padrão)).
Seguindo este procedimento encontrei média de 0.67 e desvio de 2.59 em X. Para isso, usei tentativa e erro, uma vez que otimização não levou a bons resultados. Veja que na sua modelagem, a média está na realidade apontando para o desvio padrão.

Distribuição log-normal em python


Node listings on taxonomy term page

Question: How to disable/remove node listings on taxonomy term page in Drupal 8?
Comment: You can alter the view that creates this page to your specific needs. If you don't want the page at all you can use the rabbithole module and link to another page Ex. Frontpage when users visit taxonomy term pages.
Answer:
function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
            if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
              $term = Drupal\taxonomy\Entity\Term::load($tid);
              $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
            }
          }

Create template file "page--taxonomy--VOCABULARYNAME.html.twig" in template folder and you can customize the page with the help of template file.
Comment: Thanks for the suggestion, now I can alter the specific taxonomy term page :) but my issue to disable/remove node listings within the taxonomy-term.html.twig has not been resolved. I wish there were D8 module similar to this https://www.drupal.org/project/disable_term_node_listings

Node listings on taxonomy term page


PACF and ACF for AR and MA

Question: I once heard the following statement:

The PACF (partial autocorrelation function) for MA processes behaves
  much like the ACF for AR processes; the PACF for AR processes behaves
  much like the PACF for AR processes.

How to understand the logic underlying this statement?
In addition to the strict mathematical proof, are there any approaches to understand this statement, the inherent relationship of AR, MA along with their PACF/ACF,  from time series properties, statistics, or any other high-level thoughts?
Answer: The statement is related to the fact that the ACF of a stationary AR process of order p goes to zero at an exponential rate, while the PACF becomes zero after lag p. For an MA process of order q the theoretical ACF and PACF show the reverse behaviour, the ACF truncates after lag q and the PACF goes to zero at an exponential rate.
These properties can be used as a guide to choose the orders of an ARMA model.
See for instance, Chapter 3 in Time Series: Theory and Methods by Peter J. Brockwell and Richard A. Davis and this.
Comment: Wold you please explain why the ACF truncates after lag q and the PACF goes to zero at an exponential rate in case MA process is the true process. What is the concept or intuition behind using ACF for choosing MA order? I am asking for the mechanism, not observation.
Comment: @Mumbo.Jumbo by getting the expression of the autocovariances in an AR process, it can be checked the decaying ACF of an AR(1) model,
see for example [this](https://onlinecourses.science.psu.edu/stat510/node/60). For the MA model, you can get its AR representation (assuming invertibility) and see that it has coefficients of the form $\theta^i$ ($i=1,2,\dots$ and $\theta$ is the MA coefficient), this suggests a decaying FACP of the MA model.

PACF and ACF for AR and MA


Need help looping JSON with JavaScript. Weird behaviours

Question: Although, it ran fine on small data. I need help looping through JSON in this form:
var current_value = 2;
json_data = {"2":"first information","3":"Second informaton","4":"Third information"}

What I want to do is get the value in the json_data that corresponds to current_value of 2
The problem is that I keep getting " anytime I run this loop:
for(x in json_data){
    if(x === current_value){
        extracted = json_data[current_value];
    }
}

Comment: It's not actually Json you have there, it's an object literal.
Comment: http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/
Comment: @Keith unless it is actually a JSON string and they're not parsing it, may be why they are getting `"`
Comment: You loop through all keys, and if the current key equals a predetermined value, you take the predetermined value out of the object… The entire loop is superfluous for doing that.
Comment: @George — If that is the case, then their code example does not represent their real code.
Comment: @George , like Quentin said, I deduced it's not a JSON string, by the second line of his first code snippet..
Comment: I'm not really understanding what your asking for here, but I think it's worth noting that there's no reason to run a loop just to grab a value. Simply writing `extracted = json_data[value]` will give the same result as the entire loop here, and if you do need to loop then `Object.keys(json_data).forEach(/*...*/)` or `map` will give you much nicer, more declarative syntax.
Comment: Thanks @George. I didn't parse it. After parsing it, I then typecasted the  current_value into string. I have been able to solve the problem. Thanks for these tips.
Comment: Thanks @Quentin for that article
Comment: @franc,  what do you mean parse it?, there is nothing to parse in the code you supplied.  Did you have this by any chance -> `json_data = '{"2":"first information","3":"Second informaton","4":"Third information"}'`, you spot the extra `'`..
Comment: @Keith Yes.. the data is coming from a remote database. So I used JSON.encode()..on arriving at the client side, I didn't use JSON.parse(json_data). Without doing JSON.parse(json_data), I will still get the same error. And no, I didn't have that by any chance. It is in fact JSON but I didn't parse it so I kept getting wrong results until I parsed it.
Comment: @franc , in the future could you post your actual code used, the first snippet is totally valid Javascript, and by posting it like this has just caused confusion.  If your getting the result viaAjax then you should have posted that.
Comment: @Keith will bear that in mind
Answer: JavaScript property names are strings. 2 is a number. === does not do type conversion. "2" !== 2.
You should set current_value to "2" instead of 2.

The loop is pointless though.
A more sensible approach would be:
var extracted;
if (current_value in json_data) {
    extracted = json_data[current_value];
}

… or even just skip the if statement. extracted will be undefined either way if the property doesn't exist.


Interior versus Boundary Points Clarification

Question: Let a,b,c be real numbers such that a<c<c and suppose that U = (a,c)u(c,b) is an open interval punctured at c. Does U have interior points? Does U have boundary points?
I understand that all points in U are interior points. However, I am struggling with the boundary points.
Is it logical to state that there U has no boundary points since all points in U are interior points? Can someone please tell me if my logic is accurate?
Answer: Given any set $A$ in a topological space $X$ (which in your example is $\mathbb{R}$), the boundary of $A$ or the frontier of $A$ is defined by:
$\overline{A}\cap \overline{A^{com}}$, where $A^{com}$ denote the complement of $A$.
In your case $A= (a,c)\cup (c,b)$. Thus, $\overline{A}=[a,b]$ and $A^{com}=(-\infty, a]\cup [b, \infty)\cup \{c\}.$ Note that $A^{com}$ is already closed, since $A$ is open. Therefore, $\overline{A^{com}}=(-\infty, a]\cup [b, \infty)\cup \{c\}.$ Now, it is trivial to see that $\overline{A}\cap \overline{A^{com}}=\{a,b,c\}.$ Therefore, the boundary or the frontier of the set $A$ is given by $\{a,b,c\}$.
You can describe the boundary of a set in a metric space in another way too. Given any set $D$ in a metric space $X$, a point $x_0\in X$ is said to be a boundary point of $D$ if each ball containing $x_0$ contains at least one point of $D$ and at least one point of $D^{com}$. Observe that the boundary $\{a,b,c\}$ (of the set $A$) obtained in case of your example, exactly satisfies this property.


Pearson correlation coefficient for lagged time series

Question: I am trying to calculate lagged Pearson correlation coefficient between time series. I am not interested in calculating cross-correlation. I want to calculate Pearson correlation coefficient because I want to use the correlation for prediction.
In general, when two variables are strongly correlated, we get a high correlation coefficient. We can fit a straight line in the scatter plot of the two variables and use it for predicting $y$ (based on $x$). In such a case, the variance explained by the fitted line would be equal to the square of the correlation coefficient.
But when the two variables are arranged in a certain lag and then Pearson correlation coefficient is calculated between them, can we still say that the variance explained will be equal to the square of the correlation coefficient? Can we use the best fit line from the lagged scatter plot for prediction?
Comment: I think it is more precise to say "Pearson correlation between lagged time series" rather than "lagged Pearson correlation between time series" -- because it one of the time series that gets lagged with respect to another, not the correlation coefficient.
Comment: Thanks Richard for a thorough answer. I still want to make sure of one point though. So based on your answer, when we use cross correlation function such as 'xcorr' in matlab (using 'coeff' option), then the function is calculating Pearson correlation coefficient right? The matlab page does not provide the formula so I was not sure.
Comment: I don't know the Matlab implementation, but for example in R cross correlation is Pearson correlation for lagged series.
Comment: Do you know how are the blank cells treated while calculating correlation in R? Are they replaced by zeros as in cross correlation in matlab or they are replaced by NaNs?
Comment: There can be no blank cells in R (regardless of what you are going to do later, such as calculate correlation). You may check how the data was read into an R object (data frame, for example) before calculating the correlation. The `cor` function itself can treat `NA` values differently; type `?cor` in R for details.
Answer:
But when the two variables are arranged in a certain lag and then Pearson correlation coefficient is calculated between them, can we still say that the variance explained will be equal to the square of the correlation coefficient?

Yes, if you consider explaining the variance of $y_t$ by $x_{t-h}$ where $h$ is the lag order. (But not necessarily so if you consider explaining the variance of $y_t$ by $x_t$.)

Can we use the best fit line from the lagged scatter plot for prediction?

Yes. It is actually quite practical because you have the lagged values earlier than you have the contemporaneous values, hence it is natural to use lagged -- rather than contemporaneous -- values for prediction.

I am trying to calculate lagged Pearson correlation coefficient between time series. I am not interested in calculating cross-correlation.

Cross correlation is the Pearson correlation for lagged time series (when one series is lagged with respect to another.)
Also note that correlation is a natural measure for cross-sectional data where the observations can be assumed to be $i.i.d.$, but it is not that natural in the time series setting where there is time dependence between observations. For example, Pearson correlation is not very useful when applied on two series sharing a common deterministic or stochastic trend (see Spurious correlations website for some examples).
Comment: I just checked the matlab implementation and confirmed that in matlab cross correlation is NOT the Pearson correlation as you said. So your answer "Cross correlation is the Pearson correlation for lagged time series (when one series is lagged with respect to another" is not correct.
Comment: I would say that it is Matlab that uses poor terminology rather than that my answer is incorrect. But at least it's good to know how things are actually implemented in the different software packages.
Comment: @SagarParajuli, I had to scroll down all the way in [this site](http://se.mathworks.com/help/signal/ref/xcorr.html?requestedDomain=www.mathworks.com) to find how Matlab defines cross correlation (in section "More about"). Indeed, it seems to be using poor terminology as it is calculating the empirical **non-centered** second cross-moment, which is not correlation but which could be covariance if the first moment of at least one of the series is zero. Please note that in my answer I am using the standard definition of cross correlation rather than the specific one that is used in Matlab.
Comment: That makes sense but even then cross correlation can be calculated using 'Spearman correlation' as well so we should not presume 'Pearson correlation' in any case. May be that R calculate 'Pearson correlation' by default while calculating cross correlation as you said.
Comment: Yes, that could be done. And R indeed does what I indicated. In my experience "correlation" used without a predicate indicates "Pearson correlation", while Spearman and Kendall versions are less frequently used and most of the time referred to explicitly. But better be precise than obscure.


What does interpolating the training set actually mean?

Question: I just read this article: Understanding Deep Learning (Still) Requires Rethinking Generalization
In section 6.1 I stumbled upon the following sentence

Specifically, in the overparameterized regime where the model capacity
greatly exceeds the training set size, fitting all the training
examples (i.e., interpolating the training set), including noisy ones,
is not necessarily at odds with generalization.

I do not fully understand the term "interpolating" in the context of fitting training data. Why do we speak of "interpolation" in this context? What does the term exactly mean here? Is there any other term that can be used instead?
In my understanding interpolation means the prediction within the training domain for some novel input that was not part of the training set.
Comment: Just for reference, there was a relevant discussion here earlier mentioned the paper https://stats.stackexchange.com/questions/531854/modern-machine-learning-and-the-bias-variance-trade-off
Answer: Your question already got two nice answers, but I feel that some more context is needed.
First, we are talking here about overparametrized models and the double descent phenomenon. By overparametrized models we mean such that have way more parameters than datapoints. For example, Neal (2019), and Neal et al (2018) trained a network with hundreds of thousands of parameters for a sample of 100 MNIST images. The discussed models are so large, that they would be unreasonable for any practical applications. Because they are so large, they are able to fully memorize the training data. Before the double descent phenomenon attracted more attention in the machine learning community, memorizing the training data was assumed to lead to overfitting and poor generalization in general.
As already mentioned by @jcken, if a model has a huge number of parameters, it can easily fit a function to the data such that it "connects all the dots" and at prediction time just interpolates between the points. I'll repeat myself, but until recently we would assume that this would lead to overfitting and poor performance. With the insanely huge models, this doesn't have to be the case. The models would still interpolate, but the function would be so flexible that it won't hurt the test set performance.
To understand it better, consider the lottery ticket hypothesis. Loosely speaking, it says that if you randomly initialize and train a big machine learning model (deep network), this network would contain a smaller sub-network, the "lottery ticket", such that you could prune the big network while keeping the performance guarantees. The image below (taken from the linked post), illustrates such pruning. Having a huge number of parameters is like buying piles of lottery tickets, the more you have, the higher your chance of winning. In such a case, you can find a lottery ticket model that interpolates between the datapoints but also generalizes.

Another way to think about it is to consider a neural network as a kind of ensemble model. Every neural network has a pre-ultimate layer (image below, adapted from this), that you can think of as a collection of intermediate representations of your problem. The outputs of this layer are then aggregated (usually using a dense layer) for making the final prediction. This is like ensembling many smaller models. Again, if the smaller models memorized the data, even if each would overfit, by aggregating them, the effects would hopefully cancel out.

All the machine learning algorithms kind of interpolate between the datapoints, but if you more parameters than data, you would literally memorize the data and interpolate between them.
Comment: @Samuel obviously, you need test data to come from the same distribution to achieve this. In such a case, this is just learning by example. One can argue that humans do a similar thing, if I tell you to imagine a dog of a size between a chihuahua and husky, your brain would probably be able to generate an impression of some dog of this size, resembling the dogs you already saw in your lifetime, it'll be a kind of interpolation, if not just recall of an actual dog you memorized.
Comment: @Samuel There is very interesting research on the phenomenon of "benign overfitting". In [this paper](https://arxiv.org/abs/1906.11300) Bartlett et al. prove for a linear model with *lots* of dimensions, that it can obtain near optimal test error (with guarantees) even when noise is injected into the labels. The idea is that because one has so many parameters, it is possible to "hide" the noise / variability into the fitted parameters, so that many of them will handle uninformative directions in feature space. The drawback is that this makes the models very sensitive to adversarial attacks!
Comment: Woah, what a great way to explain it. Thanks!
Comment: Thanks for that useful answer! But how is it possible that a model interpolates / memorizes the training data, but at the same time is so flexible that it won't hurt the test set performance? I don't find this to be very intuitive. Could you help me with that?
Answer: In layman's terms, an interpolator will literally 'join the dots'.
Here's a simple graphical summary of what interpolation can do and why it can be awful. I'd like to stress that interpolation does play a useful role in statistics/ml but should be used carefully. The  black dots are training data and the red crossed are a similar dataset drawn form the same data generating process - they can be though of as a test set.
We can see the in the left hand plot fits okay to both the training and test data. On the left I just used linear regression to fit a line to the data (just $2$ parameters). The curve in the right hand plot perfectly predicts the training set but looks nothing like the test set. I'd used an $11^{th}$ order polynomial (plus intercept) to fit the interpolator. Additionally, on the test set, the linear fit gives $MSE = 23.8$, the interpolator gives $MSE = 10350842349$ -- not good!
Comment: A computer just stores an image as rgb value for each pixel (usually each rgb value is from $\{0, 1, 2, \ldots, 255 \}$). So your model will just predict rgb values for each pixel - 'joining the dots' in this case will just be interpolating these values. Likewise, any other data representation will be converted to a number for a model to deal with it
Comment: Can you give an intuition what "joining the dots" in image space looks like? Is it possible to transfer the right plot to images or other abstract representations of data?
Comment: It's not really the fact that it's "joining the dots" which is the problem in these examples though - it's the way it's doing it. If you linearly interpolated between the black dots the model would be poor but it would somewhat fit the test data. The terminology "interpolating the training data" is a bit loose, I guess what it really means is overfitting the training data in a way that doesn't generalise to the test data? Or at least the inductive bias of the model is such that the interpolation between training data instances doesn't match the structure of the data?
Answer: Apart from literal meaning of interpolation, this is related to  something called deep learning models totally memorize the training data. Hence, both interpolating and memorisation in this paper/context means zero training loss but still not overfitting on the test set. Hence the curious phenomena, that normally we would call an overfitting (overtraining actually), which is not resolved yet.
Comment: I don't understand this part of your answer "but still not overfitting on the test set". Can we ever overfit the test data? Can you please elaborate on that a bit more?
Comment: It meant to imply, deep learning models do not give predictions of overfitted model even though it "memorise/interpolate" the training set, as phenomenon suggests.
Answer: I would add, the quote actually contains the definition, "fitting all the training examples... including noisy ones". So the training loss is zero. The comment "including noisy ones" implies the the data is generated by a process say
$y= f(x) + \epsilon$
Where $\epsilon$ represents noise. By fitting the model such that $y=f(x)$ for every training example even when $\epsilon$ is non-zero you are interpolating.
Comment: The explanation is a little confusing since it says "fitting to every example even if noise is non-zero", in statistics we generally assume non-zero noise for all samples, as they are thought as random variables. Also, no algorithm distinguishes between noisy and non-noisy examples.
Comment: Actually this goes into deep learning models being a regularisers by construction.
Comment: @Tim interpolation algorithms (generally) assume no noise though, i.e. if you use a spline interpolator you're fitting a curve $y=f(x)$ which is different to the assumption in statistics that "we generally assume non-zero noise for all samples".


How to divide a large rectangle into N smaller rectangles

Question: I would like to divide a NxMpx  rectangle(matrix) into X piece different size smaller rectangles. X is a variable so it dosn't have a fix value.The smaller rectangles must fill the 80-90% area  of large one. Small rectangles must to be different area.

Is there any algorithm or formula to solve this kind of problems.
(Ideas, links are welcome. I'v already searched a lot of websites with google, but unfortunately nothing usefull, maybe i am using wrong keywords or i don't know.)
Thank You
Answer: The problem is that there are so many ways that you have not specified what you want well enough. You can just split the rectangle into $N$ horizontal or vertical stripes.  You can cut those stripes as you do.  You can even make four rectangles that leave a little bit of space in the middle.


Team start with an old ball after enforcing follow on within 30 overs in Cricket

Question: Can a fielding side start bowling in an innings with the same/old ball after enforcing the follow on, having bowled out the opponents with in 30 overs previously? FOr example, Pakistan today bowled New Zealand out today in 35.5 overs and enforced follow on, now could they start with an old ball in second innings?
Answer: Generally speaking,

in theory, the bowling team could ask it.

in reality, the batting tea wouldn't let them.

the bowling team wouldn't want it anyway, unless they are only using spin bowlers, which is highly unlikely.

Law 4 The ball provides that

4.3 New ball
Unless an agreement to the contrary has been made before the match, either captain may demand a new ball at the start of each innings.

In particular, for international Test cricket, ICC Playing Conditions provide that

4.3 New ball
A new ball shall be used at the start of each innings.

Pakistan would not have the choice. A new ball must be used, even if the first innings had been 0/10 in 0.1 overs.
Comment: `0/10 in 0.1 overs`. How?
Comment: It's an extreme example - the laws don't quite currently allow for it, but that could change in the future. 1/10 in 0.0 could happen, of course. @hims056
Comment: `1/10 in 0.0` again how? (Except timeout of course)
Comment: No ball and any of the three options for out there, then timed out the rest, is one way.
Answer: No as per law  in cricket it is mandatory that whenever new innings is started whether after followon or in normal circumstances , new ball will be used to start a inning
Comment: It is **not** mandatory in law, which allows continuation with the previous ball if agreed. The playing conditions may vary this in almost any way conceivable.


React Native Project error : ld: framework not found GoogleAdMob

Question: I face this issue when try to build the app for production. But I could build the app in simulator. I face this issue and also solved it
Answer: Need to update cocoa pods to the latest version
run: pod install
Answer: Use this command which will remove existing pods and install pod again. This will also remove node_modules and do a fresh install.
<code>rm -rf node_modules && yarn install && cd ios && rm -rf Pods && pod install && cd ..
</code>


Finding conditional probability of getting a number on a die and Jacks in Hand

Question: Suppose we roll a fair six-sided die and then pick a number of cards from a well-shuffled deck equal to the number showing on the die. (For example, if the die shows 4, then we pick 4 cards.)
(a) What is the probability that the number of jacks in our hand equals 2?
(b) Conditional on knowing that the number of jacks in our hand equals 2, what is the conditional probability that the die showed the number 3?
That's the detailed question from the Midterm Review questions I am solving and here's my attempt(me and friends have conflicting answers):
(a) Let A = Get 2 or above on the die.
$P(A) = 5/6$
Let B = Get 2 Jacks after picking 2 or more (up to 6 cards)
$P(B) = C(52,2)(4/52)^2 + C(52,3)(4/52)^2(48/52) + C(52,4)(4/52)^2(48/52)^2 + C(52,5)(4/52)^2 + C(48/52)^3 + C(52,6)(4/52)^2(48/52)^4$
Now just multiply $P(A)$ and $P(B)$ to get the answer to (a)
But I think I got $P(B)$ wrong which is what I need help with.

(b) Let A = 3 on die
Let B = Get 2 Jacks
$P(A|B) = \frac{P(A\cap B)}{P(B)}$
I know that $P(A\cap B) = P(A) * P(B|A)$
But I still don't know $P(B)$ is and I am not sure if above formula is correct.
Answer: I think I can help you.
Let $N_D$ be the number you got from the die and $N_J$ the number of Jacks in your hand. In this context  we have:
$$P(N_J = j) = \sum_{d = 1}^6\mathbb P(N_J = j\,|\,N_D = d)\mathbb P(N_D = d)$$
Since the die is fair: $\mathbb P(N_D = d) = 1/6$ for every $d$. To find the other probabilities all you need is the number of hands that have $d$ cards and $j$ Jacks, which is $C(4,j)\times C(52-4,d-j)$. As a consequence:
$$P(N_J = j\,|\,N_D = d) = \frac{C(4,j)\times C(52-4,d-j)}{C(52,d)}$$
To compute the probability on item (b) you can do:
$$\mathbb P(N_D = 3\,|\,N_J = 2) = \frac{\mathbb P(N_J = 2\cap N_D=3)}{\mathbb P(N_J = 2)}$$
$$\mathbb P(N_J = 2\cap N_D=3) = \mathbb P(N_J = 2\,|\,N_D = 3)\mathbb P(N_D = 3)$$
Hope this was useful.


How do I get the form field value?

Question: The question is clear from the title itself :
I have tried :
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
          $form_state->getValue('field_p_fqdn');
          $form['field_p_fqdn']['und']['#default_value'];
}

where field_p_fqdn is my field name .But both didnt worked . Any idea ??
Answer: Depending the field type, it could be:
For exemple for plain text:
$form['field_p_cert_fqdn']['widget'][0]['value']['#default_value']

or
$form['field_p_cert_fqdn']['widget'][0]['#default_value'];

or
$form['field_p_cert_fqdn']['widget']['#default_value'][0];

or for entity reference:
$form['field_p_cert_fqdn']['widget'][0]['target_id']['#default_value'];

or some other thing
I would recommend you to use the devel module: https://www.drupal.org/project/devel (with the kint submodule enable). With this, you can add
dpm($form);

in you alter function to get the structure of the $form.
Comment: unfortunately nothing works !!
Comment: Humm, bad luck. What is the field type of field_p_cert_fqdn ?
Comment: Text (plain) (Text field)
Comment: I have updated my answer with plain text
Comment: I would recommend you to use the devel module (with the kint submodule enable). With this, you can add dpm($form); in you alter function to get the structure of the $form.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/51438/discussion-between-icecreamjelly-and-baud).

How do I get the form field value?


Menu links not working in Ubuntu (D7)

Question: I had a site in Windows installed inside xampp.  I copied the same site's folder and database from windows-xampp installation to Ubuntu's www folder (Lamp) . The menu links are not working now. localhost/sitename directs to the homepage . But when I click on any menu items , it says

The requested URL /sitename/latest/11 was not found on this server.

I could not figure out if this is problem of localhost or menu or database?
I can't even login because users/login is also not working.
Any suggestion or any links to the articles that I should read to solve this problem  would be great. Thank you .
Comment: Have you tried `user/login` to login? (note `user` not `users`)
Comment: Yes I did but does not work.Gives the same error.
Comment: Sounds like .htaccess did not copy over with the rest of the files. Check to see if that file is present in the site's root folder.
Comment: I checked for .htaccess file . It is present there .
Comment: Are you using the same database name in ubuntu..all credentials stuff?
Comment: Yes I am using the same database name . Choster's answer helped me . Thank you for the response.
Answer: My suspicion is that Drupal's .htaccess URL rewrite directives have been disallowed in your Ubuntu installation of Apache. If it were a bootstrap or database connection problem, you would not be able to see the front page either.
Ordinarily, Drupal prevents Clean URLs from being activated if not supported by the server. In this scenario, of course, that test was done in the Windows installation. Ensuring rewriting support in the target server is at the top of the migration checklist.
The quickest way to see if Clean URLs is the culprit is to try browsing to localhost/sitename/index.php?q=user/login ; if that page does come up, you will need to enable rewriting in your web server.
See http://drupal.org/node/1186762#comment-5424052 for some instructions on checking your Apache configuration to make sure it allows Drupal to rewrite URLs in its .htaccess file.
If you can confirm that the .htaccess file is being read, rewrite directives have been allowed in Drupal's installation directory, and that mod_rewrite is active, and still see problems, I would check next for a corrupted menu table.
Comment: Yes the problem was Apache's rewrite problem.                      sudo a2enmode rewrite
worked for me . Thanks a lot for the help.

Menu links not working in Ubuntu (D7)


Why negative of a negative number is positive?

Question: I am intrigued in seeking the philosophy underlying it. When I was trying to prove it mathematically, I was failed but later I started to analyze vectors that what they are? As an outgrowth of vector's study I found my answer i.e.
If there is a vector $A$, then its reverse is the vector -$A$ but what is the reverse of $-A$ again? I used the convention of prefixing a minus sign before $-A$ and figured out that it is the vector we were familiar with i.e. $A$ and no vector can just be opposite to $-A$ i.e. no vector can be at $180$ degree to the vector $-A$ rather than $A$ or '$-(-A)$'.
And so i satisfied myself but i am puzzled thus far that whether I am  right to explain Negative number as the additive inverse or not. Can you tell me if other philosophical fact satisfies it.
Comment: Since $A+(-A) = 0$, $A$ is the additive inverse of $-A$, even for real number $A$.
Answer: A negative (integer) number is the "inverse" with respect to the addition :

$x + (-x) = 0$.

Thus, consider the inverse of a negative number :

$(-x) + [- (-x)] = 0$;

by property of $=$ and commutativy of addition we have that :

$x + (-x) = [- (-x)] + (-x)$

and thus :

$x = [- (-x)]$.
Answer: It's useful to train oneself to use the phrase "additive inverse". Using that terminology, we first learn about positive numbers, and then we learn about negative numbers which are the additive inverses of positive numbers. Finally, your question can then be translated into the statement that the additive inverse of the additive inverse of $x$ equals $x$, which is true because
$$x + (-x) = 0
$$
and from this we that $x$ is the additive inverse of $-x$ which is the additive inverse of $x$.
Answer: The negative of a number is defined to be the unique solution of the equation $a+x=0$ and the solution of this equation is denoted by $-a$. Similarly the solution of the equation $(-a)+y=0$ is $-(-a)$.
Therefore we have $a+(-a)=(-a)+-(-a)$ and since $+$ is commutative in $\mathbb{R}$ and also both cancellation laws hold therefore we get,

$a+(-a)=(-a)+-(-a)\implies a+(-a)=-(-a)+(-a)\implies a=-(-a)$


How to choose priors for experimental data

Question: My question results from the subjectivity of priors, and if there are bodies of work that help to create a more objective approach towards prior choices.
My question specifically is to do in the realm of spectroscopic/experimental data, where prior information of the system beforehand is limited. For example, concerning the amplitude of a peak: it is quite difficult to know much prior information about this beforehand.
Other features such as the FWHM and the peak positions have some prior information about them in databanks for known materials, however for newer materials this is also not known. In this case, would you simply assign uniform priors to all parameters? Even with the danger of generating an improper posterior?
Are there alternatives to uniform priors when weakly informative information is known about a parameter, for example the amplitude must be positive, or a certain other parameter must be bounded between 0 and 1. How can you express this in your prior choices?
Answer:
Are there alternatives to uniform priors when weakly informative information is known about a parameter, for example the amplitude must be positive, or a certain other parameter must be bounded between 0 and 1. How can you express this in your prior choices?

If your prior assigns zero to a particular point in the parameter space, then your posterior will be zero. In this way, you can exclude certain parameter values from ever having a non-zero posterior probability. You should be very careful with this though, limiting it only to cases where such a parameter value is logically or physically impossible (this is sometimes called Cromwell's Rule).
For a prior between 0 and 1, a frequently used choice for an informed prior is a Beta prior; you can play around with the beta distribution here and see how the parameters affect it. This would allow you to have a non-uniform prior which is limited between 0 and 1.
For a non-negative variable, a half-normal or half-cauchy prior might make sense, and will result in a proper posterior. But without more information about your prior knowledge, it's hard to make a concrete recommendation. This will at least make sure your posterior is non-negative, which may be what you're looking for.
Comment: Thank you for the explanation. What further information would you require to make a recommendation: What is the methodological process you go through to decide? I am interested in this, as I hope it will help me follow the bayesian process more effectively.
Comment: There are a number of approaches to turning expert information into priors. A simple, but often effective method, is to use quantiles of the prior distribution, and construct your prior based off of them. This Q/A (https://stats.stackexchange.com/questions/1/eliciting-priors-from-experts) and this link (https://www.johndcook.com/blog/2010/01/31/parameters-from-percentiles/) might be useful.

If you are fitting many parameters at once which are mutually informative, you are probably in a good situation for a hierarchical model (https://en.wikipedia.org/wiki/Bayesian_hierarchical_modeling).
Comment: Thank you for the information. The issue here is that there is little prior expert information when it comes to spectroscopic data such as XPS, X-ray Diffraction, Neutron-Scattering unless you use something like DFT simulation predictions as your informative priors which isn't a simple task. In this way it can be difficult to avoid uniform priors. Are there any resources on priors in chemistry etc  based applications?
Comment: Unfortunately I'm not sure I can help you there; my knowledge of chemistry is quite limited. A search for "bayesian analysis in spectroscopy" on Google produces examples that might provide case studies for you in how priors are constructed here, but I don't have the domain knowledge of spectroscopic data to point you towards any especially good examples.

Alternatively, you could provide more information about your particular problem, in which we might be able to provide so more specific suggestions (what parameters you are estimating, what data you have, etc.).


What is this common left-hand arpeggiated pattern?

Question: I really commonly find that contemporary songs use an arpeggiated up-and-down progression over notes that are in this shape, here are some examples:

C1, G1, C2
C#1, G#, C#2
E1, B, E2
A1, E, A2

Is there a name for this?
How can I tell which sets of these go together?
Comment: @Dom guitarist would call that a _powerchord_, but not if arpeggiated.
Comment: You are referring to notes, right? Not chords
Comment: To answer this, it is important to know the [definition for "arpeggiated"](http://music.stackexchange.com/q/2554/249) (reference for others who don't know what it is).
Comment: It's the first, the fifth and then the octave on all four of them. You mean which set of these go together with each other?
Comment: I know, but why is that so common? Is there a name for that pattern? I mean, googling "first fifth and octave" doesn't exactly turn up much. I also just added in that this is re: piano, forgot to specify that. I don't know about other instruments.
Comment: I guess, yeah....but I figured it was an arpeggiated chrod.
Answer: I suppose that happens in the left hand in the songs you're referring to, while the right hand plays something different?
Then it's a kind of alternate bass.
Comment: Add the third and you get an [Alberti bass](http://en.wikipedia.org/wiki/Alberti_bass)
Answer: In all your examples, the pattern is first, perfect fifth, octave.
I guess you can understand why the first and the octave sound good (sound in unison), right? It's the same note.
The note in between is a perfect fifth. Wikipedia says

The perfect fifth is more consonant, or stable, than any other interval except the unison and the octave

This means that when you play a note, the 'best sounding' note in unison with it (after the octave) is the perfect fifth.
You might understand it better when you write it as 'perfect fifth' rather than 'fifth'.

The term perfect identifies the perfect fifth as belonging to the group of perfect intervals (including the unison, perfect fourth and octave), so called because of their simple pitch relationships and their high degree of consonance.
Comment: Are you looking for "overtones"?
Comment: Also, when you play a note, there are more than one notes being played together. A trained ear can hear this. I can't recall what the name of this is in English, but if anyone can help me, I will add it to my answer. It is a good explanation
Comment: Harmonics or overtones
Answer: In a general sense, that pattern is simply referred to as "open fifths."  (It has other names too, such as a {0,7} unordered pitch class set).  Sticklers might argue that this is not a chord at all but an interval with one note doubled.
It's common because the notes are harmonious with each other even in lower ranges.  A full chord in the bass sounds very muddy, but leaving it "open" allows the notes to ring a bit clearer.  You will see open fifths in the left hand whenever a chord is in the "open position" meaning the notes of the chord are spaced out for a more open sound.  Another common left-hand pattern is 0-5-10 (C1,G1,E2) which also has a pleasant open sound but is more difficult to play as it requires your left hand to stretch to a 10th.
So that explains left hand open fifths, but why does this pattern show up in the right hand as well?  Well, an open fifth is a lot like a triad that is missing its third.  Some chords, however, have their third in the bass (this is known as a 6-3 chord, named after the size of the intervals above the lowest note).  When there is a third in the bass it is very difficult to double it without introducing parallel octaves, which is considered poor voice leading in much of western music.  So if there is a third in the bass, the right hand is often playing open fifths.  You'll find this pattern all over the place in the scores of Mozart and Haydn.
Answer: Assuming that the chords are intended to be read top to bottom, left to right, I would say that you have a I V I chord progression with dominant seventh/ sharp ninth chords.
In this case the seventh is omitted, but the combination of a major and minor 3rd in the same chord (i.e. E G# B G or A C# E C) would usually be called a dominant seventh/ sharp ninth.
This is the classic Hendrix chord in Purple Haze, among other things...
http://en.wikipedia.org/wiki/Dominant_seventh_sharp_ninth_chord
Answer: All three of those are simply I-V-I progressions.  the V-I is called an authentic cadence, or full close. It's the most widely used cadence there is.
I'm not sure what else I can say about it.
V-I is when the music moves from the Dominant chord to the Tonic.  There are arguments that all western music is about how we move from the dominant to the tonic, but that's a huuuuge topic
As for which sets go together, it's all about what key you are in, and the context of what you're playing, and which follows which. (basically it's a way too broad topic, but start by learning about key signatures)
see also:
Wikipedia on Authentic cadences
Answer: In the context of guitar, these are "power chords", usually notated as "5" chords (as in "C5").
Played on three adjacent strings, they are easily movable chords. Move the shape to different strings (e.g., from EAD to ADG) and you get the perfect fourth.
Especially when played on an electric and adding distortion, power chords have a distinctive sound. For examples, see The Kinks' You Really Got Me

Deep Purple's Smoke on the Water

or The Cars' You Might Think


Função de converter números decimais para extenso usando VBA em Excel

Question: Estou com uma função, =SpellNumber(), que ao colocar um número lá, ela solta o número por extenso. Agr, ela solta, na parte dos centavos, and X Cents. Gostaria que ela soltasse with X/100. Alguém sabe como eu altero o código pra ela fazer isso? Aprecio a ajuda e segue o código abaixo:
Option Explicit
'Main Function
Function SpellNumber(ByVal MyNumber)
    Dim Dollars, Cents, Temp
    Dim DecimalPlace, Count
    ReDim Place(9) As String
    Place(2) = " Thousand "
    Place(3) = " Million "
    Place(4) = " Billion "
    Place(5) = " Trillion "
    ' String representation of amount.
     MyNumber = Trim(Str(MyNumber))
    ' Position of decimal place 0 if none.
    DecimalPlace = InStr(MyNumber, ".")
    ' Convert cents and set MyNumber to dollar amount.
    If DecimalPlace > 0 Then
        Cents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & _
                  "00", 2))
        MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
    End If
     Count = 1
    Do While MyNumber <> ""
         Temp = GetHundreds(Right(MyNumber, 3))
        If Temp <> "" Then Dollars = Temp & Place(Count) & Dollars
        If Len(MyNumber) > 3 Then
            MyNumber = Left(MyNumber, Len(MyNumber) - 3)
        Else
             MyNumber = ""
         End If
        Count = Count + 1
    Loop
    Select Case Dollars
    Case ""
        Dollars = "No Dollars"
    Case "One"
        Dollars = "One Dollar"
     Case Else
        Dollars = Dollars & " Dollars"
End Select
Select Case Cents
    Case ""
        Cents = " and No Cents"
    Case "One"
        Cents = " and One Cent"
          Case Else
        Cents = " and " & Cents & " Cents"
End Select
SpellNumber = Dollars & Cents
End Function

' Converts a number from 100-999 into text
Function GetHundreds(ByVal MyNumber)
    Dim Result As String
    If Val(MyNumber) = 0 Then Exit Function
    MyNumber = Right("000" & MyNumber, 3)
    ' Convert the hundreds place.
    If Mid(MyNumber, 1, 1) <> "0" Then
         Result = GetDigit(Mid(MyNumber, 1, 1)) & " Hundred "
    End If
    ' Convert the tens and ones place.
     If Mid(MyNumber, 2, 1) <> "0" Then
        Result = Result & GetTens(Mid(MyNumber, 2))
Else
    Result = Result & GetDigit(Mid(MyNumber, 3))
End If
GetHundreds = Result
End Function

' Converts a number from 10 to 99 into text.
Function GetTens(TensText)
    Dim Result As String
    Result = ""           ' Null out the temporary function value.
    If Val(Left(TensText, 1)) = 1 Then   ' If value between 10-19...
        Select Case Val(TensText)
            Case 10: Result = "Ten"
            Case 11: Result = "Eleven"
            Case 12: Result = "Twelve"
            Case 13: Result = "Thirteen"
            Case 14: Result = "Fourteen"
            Case 15: Result = "Fifteen"
            Case 16: Result = "Sixteen"
            Case 17: Result = "Seventeen"
            Case 18: Result = "Eighteen"
            Case 19: Result = "Nineteen"
            Case Else
        End Select
    Else                                 ' If value between 20-99...
        Select Case Val(Left(TensText, 1))
            Case 2: Result = "Twenty "
            Case 3: Result = "Thirty "
            Case 4: Result = "Forty "
            Case 5: Result = "Fifty "
            Case 6: Result = "Sixty "
            Case 7: Result = "Seventy "
            Case 8: Result = "Eighty "
            Case 9: Result = "Ninety "
            Case Else
        End Select
        Result = Result & GetDigit _
            (Right(TensText, 1))  ' Retrieve ones place.
    End If
    GetTens = Result
End Function

' Converts a number from 1 to 9 into text.
Function GetDigit(Digit)
    Select Case Val(Digit)
        Case 1: GetDigit = "One"
        Case 2: GetDigit = "Two"
        Case 3: GetDigit = "Three"
        Case 4: GetDigit = "Four"
        Case 5: GetDigit = "Five"
        Case 6: GetDigit = "Six"
        Case 7: GetDigit = "Seven"
        Case 8: GetDigit = "Eight"
        Case 9: GetDigit = "Nine"
        Case Else: GetDigit = ""
    End Select
End Function

Comment: Dê um exemplo correcto de valor numérico mas valor por extenso.
Comment: Se eu escrevo: "=SpellNumber(123.45)", sai: "One Hundred Twenty Three Dollars and Forty Five Cents"
Comment: Agora escreva por extenso a forma como pretende ler o número
Comment: Gostaria que saisse: "One Hundred Twenty Three with x/100", sem o "Dollars"e sem o "Cents", sendo X o número de centavos.
Comment: Vou verificar as alterações necessárias
Comment: Obrigado, Jorge!
Comment: @J.Doe Favor editar a pergunta com estes dados e alterar o título para um mais compreensível. Do que pretende realizar, por exemplo: `Função de converter números decimais para extenso`
Comment: @J.Doe por favor verifique e considere-a certa se responder correctamente à sua pergunta.
Answer: Apenas a função SpellNumber  alterada, quando não tem casas decimais apenas apresenta a parte inteira.
Comentei o código antigo relativo aos cêntimos.
Function SpellNumber(ByVal MyNumber)
    Dim Dollars, Temp
    Dim Decimals, Count 'DecimalPlace,

    ReDim Place(9) As String
    Place(2) = " Thousand "
    Place(3) = " Million "
    Place(4) = " Billion "
    Place(5) = " Trillion "

    Decimals = (MyNumber * 100 Mod 100)

    If Decimals <> 0 Then
        Decimals = " with " & Decimals & "/100"
    Else
        Decimals = ""
    End If

    ' String representation of amount.
     MyNumber = Trim(Str(MyNumber))

    ' Position of decimal place 0 if none.
    'DecimalPlace = InStr(MyNumber, ".")
    ' Convert cents and set MyNumber to dollar amount.
    'If DecimalPlace > 0 Then
    '    Cents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & _
    '              "00", 2))
    '    MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
    'End If

    Count = 1
    Do While MyNumber <> ""
         Temp = GetHundreds(Right(MyNumber, 3))
        If Temp <> "" Then Dollars = Temp & Place(Count) & Dollars
        If Len(MyNumber) > 3 Then
            MyNumber = Left(MyNumber, Len(MyNumber) - 3)
        Else
             MyNumber = ""
         End If
        Count = Count + 1
    Loop
    Select Case Dollars
    Case ""
        Dollars = "No Dollars"
    Case "One"
        Dollars = "One Dollar"
     Case Else
        Dollars = Dollars & " Dollars"
End Select

'Select Case Cents
'    Case ""
'        Cents = " and No Cents"
'    Case "One"
'        Cents = " and One Cent"
'          Case Else
'        Cents = " and " & Cents & " Cents"
'End Select

'SpellNumber = Dollars & Cents

SpellNumber = Dollars & Decimals
End Function


Zend Framework funciona com Nginx (sem apache)?

Question: Tenho um projeto desenvolvido em zf2 e atualmente uso uma hospedagem compartilhada com Apache, mas vou migrar para o VPS da Digital Ocean e vou configurar o servidor com Nginx, pois tem melhor desempenho.
Ou seja, ao invés de Apache, vou utilizar Nginx.
Será que meu sistema desenvolvido em ZF2 irá funcionar normalmente no Nginx ou terei que fazer alguma modificação?
Comment: Boa noite, gostaria de saber se alguma das respostas lhe ajudou, se não por favor comente o que acha que falta.
Comment: Olá, obrigado pela resposta de todos, pelo que entendi vai funcionar normal desde que todos os módulos necessários estejam habilitados, só não explicaram aonde fica o arquivo de configuração para habilitar os módulos
Comment: Mas você não perguntou isto, a sua  pergunta só fala de ngnix e apache não vi você perguntar dos modulos zf2.
Comment: Minha pergunta inicial foi sobre funcionar com nginx, mas as respostas evoluíram para ativar os módulos necessários, apenas gostaria de saber onde ativa estes módulos, se é igual um arquivo .htacess onde passa algumas configurações, abração
Comment: Entendo, mas é então você deve editar a pergunta, amigo por favor entenda não somos um fórum e sim um site de Q&A, recomendo que leia o máximo do http://pt.stackoverflow.com/help, espero que entenda isto como uma critica construtiva :) - ps: Vou tentar editar a resposta assim que possível pra dar detalhes sobre os módulos (componentes) do zf2
Comment: Ok, muito obrigado, esta é minha primeira pergunta e estou aprendendo como funciona, aliás a comunidade está de parabéns, muito prestativa!
Answer: Não vejo porque poderia dar algum problema. Servidores HTTP nada mais fazem do que responder a um acesso por meio de uma determinada URL, através de uma determinada porta, com o conteúdo HTTP desejado.
O que você precisa verificar é se todos os módulos que você precisa para o projeto estejam habilitados, e que o virtual host esteja corretamente configurado. Geralmente os módulos incluem suporte à linguagem desejada (no caso, PHP), escrita de URL, SSH, dentre outros. Configuração de virtual host também costuma ser tranquila.
Answer: Acredito que as únicas dependências do Zf2 sejam em relação ao PHP e ao mod_rewrite (se for usar urls amigáveis) como citado no próprio manual do Zf!.
Se for usar as urls amigáveis (o que não é uma obrigação) então terá terá que fazer modificações, já que o arquivo .htaccess não irá funcionar no Ngnix, pois ele é um documento do Apache, no entanto o Ngnix assim como o Apache permite criar urls amigaveis
Provavelmente você pode usar o try_files:
location / {
    try_files $uri $uri/ /index.php;
}

Documentação do Ngnix:
https://www.nginx.com/resources/wiki/start/topics/recipes/zend/#time-for-nginx
É provável que consiga fazer tudo com o Ngnix que iria fazer no Apache, no entanto de outra maneira.
Uma página que pode lhe ajudar a converter o seu arquivo .htacces: http://winginx.com/en/htaccess
Ela não é tão inteligente quanto "uma pessoa", mas ajuda a quebrar um galho, no entanto recomendo dar uma estudada no Ngnix, ele pode ser tão simples quanto o Apache.
Requerimentos:
A pergunta aqui fala apenas de dependências sobre do Zf2 em relação ao Ngnix e não havia a necessidade de postar sobre o php em si, mas irei citar as dependências PHP como um adicional que pode auxiliar outras pessoas com duvidas:

PHP 5.2.4 ou superior

Extensões PHP usadas pelos componentes do Zend:
Nem todas extensões serão necessárias, isto vai depender do componente

apc, Soft, bcmath, bitset, bz2, calendar, com_dotnet, ctype, ZendGData, ZendHttpClient, ZendPdf, ZendRestClient, ZendRestServer, ZendSearchLucene, Zend_Uri, Zend_Validate, curl, date, dba, dbase, dom, Zend_Dom, Zend_Feed, ZendGData, ZendLogFormatterXml, ZendRestServer, Zend_Soap, ZendSearchLucene, ZendServiceAmazon, ZendServiceDelicious, ZendServiceFlickr, Zend_XmlRpc, exif, fbsql, fdf, filter, ftp, gd, ZendPdf, gettext, gmp, hash, ibm_db2, iconv, ZendLocaleFormat, Zend_Mime, ZendPdf, ZendSearchLucene, ZendServiceAudioscrobbler, ZendServiceFlickr, ZendValidateHostname, ZendValidateStringLength, ZendXmlRpcClient, igbinary, imap, informix, interbase, json, ZendSerializerAdapterJson, ldap, libxml, mbstring, mcrypt, memcache, mhash, mime_magic, ming, msql, mssql, mysql, mysqli, ncurses, oci8, odbc, openssl, pcntl, pcre, pdo, pdo_dblib, pdo_firebird, pdo_mssql, pdo_mysql, pdo_oci, pdo_pgsql, pdo_sqlite, pgsql, posix, pspell, readline, recode, Reflection, Zend_Filter, ZendFilterInput, Zend_Json, Zend_Log, ZendRestServer, ZendServerReflection, Zend_Validate, Zend_View, ZendXmlRpcServer, session, Zend_Session, shmop, SimpleXML, Zend_Feed, ZendRestClient, ZendSerializerAdapterWddx, ZendServiceAudioscrobbler, Zend_Soap, Zend_XmlRpc, Soft, soap, Zend_Soap, sockets, SPL, SQLite, standard, sybase, sysvmsg, sysvsem, sysvshm, tidy, tokenizer, wddx, xml, ZendTranslatorAdapterTmx, ZendTranslatorAdapterXliff, XMLReader, xmlrpc, XMLWriter, xsl, zip, zlib, ZendFilterCompress
Comment: Não entendi o negativo na minha resposta, até aonde sei as dependências do Zf2 estão no php e não no Apache, com exceção do `mod_rewrite` (que pode ser ou não usado), se existe algo de errado com a resposta comente por favor, pra que eu possa melhorar ou deletar. Obrigado


wrong written boolean method?

Question: i have this problem with boolean method, description is in comments, but I don't get this: why is this "false" after brackets here? and how can I use if statement to see if condition is right or wrong inside return? I can't modify anything else, but these brackets. I'm totally confused.I understand the code below, first I have condition (a&&b) ? "then something" but in first code I don't get it. Here is my code:
public class Aufgabe5 {

    // returns true if (and only if) both x and y are in the range from 1 to 20 (including 1 and 20)
    // and x is larger than y.
    private static boolean inRangeAndOrdered(int x, int y) {
        return (false /* TODO: modify this expression */);
    }

    // returns 1 if both a and b are true, 0 if a differs from b, and -1 if both a and b are false
    private static int wiredLogic(boolean a, boolean b) {
        return (a && b ? (-1 /* TODO: modify this expression */) : (-1 /* TODO: modify this expression */)) +
               (a || b ? (-1 /* TODO: modify this expression */) : (-1/* TODO: modify this expression */));
    }

Comment: I thought this site was for beginners too, but as I can see, if it's not some super hard question : Let's downvote it! For what people? How should question look like to be upvoted? I'm stuck with these, and if it's easy for you, help. DON'T DOWNVOTE!
Answer: I can't answer why false is after the brackets because I don't know why you have it there? Possibly its an odd requirement that you need. It sounds like you need the false to be there for some reason. However, this method would be easier to write and easier to understand without it.
The below method will achieve your requirements in the comments (while making use of the false).
// returns true if (and only if) both x and y are in the range from 1 to 20 (including 1 and 20)
// and x is larger than y.
private static boolean inRangeAndOrdered(int x, int y)
{
    return (false == !(x >= 1 && x <= 20 && y >= 1 && y <= 20));
}

What this return statement is doing:
First, x >= 1 && x <= 20 will equate to true if x is greater than or equal to 1 and less than or equal to 20.
Second, y >= 1 && y <= 20 will equate to true if y is greater than or equal to 1 and less than or equal to 20.
Then the results of both statements are combined using && and wrapped in brackets. If both x and y are greater than or equal to 1 and less than or equal to 20 this will whole bracketed statement equates to true.
Adding the "not" keyword ! before the brackets will reverse the boolean value. So if the bracketed statement equates to true it will be reversed to false.
Examples:
true == !true = false or false == !false = false
The return statement compares the reversed equated value of the bracketed statement false == !({statement}):

If {statement} = true, it is reversed to false, false equals false, true is returned.
If {statement} = false, it is reversed to true, true does not equal false, false is returned.

This return is essentially using an if statement. It can also be read as the following, however the code I mentioned above is short form:
if (false == !(x >= 1 && x <= 20 && y >= 1 && y <= 20))
    return true;
else
    return false;

The below method achieves the requirements in the comments of your second method:
// returns 1 if both a and b are true, 0 if a differs from b, and -1 if both a and b are false
private static int wiredLogic(boolean a, boolean b)
{
    return (a && b ? 1 : (a == b ? -1 : 0));
}

This return statement is doing three checks to meet the requirements:

If the combination of a and b is true then return 1.
If the combination of a and b is not true and a equals b then a and b are both false, return -1.
If the combination of a and b is not true and a does not equal b then either a is false and b is true or b is false and a is true, return 0.

wrong written boolean method?


Parametric Equations (Basic) - Cartesian equation of curves

Question: $x = 2 \cos t$, $y = 2 \sin t$, $0 \le t \le 2\pi$
Find the Cartesian equation of the curves.
Please help i know it's basic but my problem is that $2 \cos t$ doesn't equal $1 - \sin^2 t$ and if it does how? (maybe i just need a re-freshener).
Help would be greatly appreciated! thank you.
Comment: Tell me which famous formula do you know that includes the basic functions $\sin t,\cos t$?
Answer: $$x=2\cos t,y=2\sin t$$
$$\cos t=\dfrac x2,\sin t=\dfrac y2$$
since $$\cos^2t+\sin ^2t=1$$
so
$$\left(\dfrac x2\right)^2+\left(\dfrac y2\right)^2=1$$
$$x^2+y^2=4$$
this is equation of a circle having centre ($0,0$)  and radius= $2$
Comment: thank you very much, you definitely reminded me since i was forgetting the fundamental theorem.