Proofs of AM-GM inequality

Question: The arithmetic - geometric mean inequality states that
$$\frac{x_1+ \ldots + x_n}{n} \geq \sqrt[n]{x_1 \cdots x_n}$$
I'm looking for some original proofs of this inequality. I can find the usual proofs on the internet but I was wondering if someone knew a proof that is unexpected in some way. e.g. can you link the theorem to some famous theorem, can you find a non-trivial geometric proof (I can find some of those), proofs that use theory that doesn't link to this inequality at first sight (e.g. differential equations …)?
Induction, backward induction, use of Jensen inequality, swapping terms, use of Lagrange multiplier, proof using thermodynamics (yeah, I know, it's rather some physical argument that this theorem might be true, not really a proof), convexity, … are some of the proofs I know.
Comment: I'm curious about the thermodynamics proof $\ddot \smile$
Comment: Would you include that in your post? (And,thermodynamics? ._. )
Comment: What have you seen, so that we don't repeat what you already know?
Comment: Community wiki?
Comment: Please add the proofs you know as answers (just to get them all together).
Comment: @aruna This version is more comprehensive, better to close the other one as a duplicate of this. Age of questions doesn't matter.
Comment: AoPS has some interesting ones: http://www.artofproblemsolving.com/Wiki/index.php/Proofs_of_AM-GM
Comment: Induction, backward induction, use of Jensen inequality, swapping terms, use of Lagrange multiplier, proof using thermodynamics are some of the proofs I know. Unfortunately, the proofs suggested by Hayden are also already on my list.
Comment: http://www.amazon.com/Introduction-Inequalities-Edwin-F-Beckenbach/dp/0394015592
Comment: possible duplicate of [Proving the AM:GM inequality](http://math.stackexchange.com/questions/468140/proving-the-amgm-inequality)
Answer: This is a fairly old answer of mine with a proof that was not very motivated, so I thought I'd update it with some geometric intuition about convexity, which is a good way to understand some inequalities (including Hölder's Inequality, with Cauchy–Schwarz Inequality as a special case).
Consider for simplicity the two-variable case $(x+y)/2 \ge \sqrt{xy}$:

I'm not sure if it comes across in the diagram, but the arithmetic mean will always produce a flat linear plane while the geometric mean will always produce this concave squareroot-like curvy surface which curves downward. Equality is only achieved precisely when $x = y$ and similarly in higher dimensions. The "curve downward" part shows intuitively why the inequality is true for all other values.
Here's a slice view with fixed $y=1$:

Obviously a plot is not a proof but it does give a useful visual.
The proof for more than two variables presented requires elementary properties of logarithms, which uses a common trick using log to transform dealing with multiplication to dealing with addition, which is linear. Starting off with the original statement:
$$ \frac{x_1 + \dots + x_n}{n}\ge (x_1 \dots x_n)^{1/n} $$
Taking logs preserves the inequality since $\log$ is an increasing function:
$$\iff \log \left(\frac{x_1 + \dots + x_n}{n}\right) \ge \frac 1 n \log (x_1 \dots x_n) = \frac{\log x_1 + \dots + \log x_n}{n}$$
$\DeclareMathOperator{\E}{E}$
If we write $\E[X]$ as the mean of $x_i$'s and $\E[\log(X)]$ as the mean of $\log x_i$'s, we can also understand this in the language of expectation:
$$\log(\E[X]) \ge \E[\log (X)]$$
Using the concavity of $\log$, by Jensen's Inequality (proved inductively starting from the definition of convexity, going back to the linearity of expectation, which ultimately comes from addition), the inequality holds.

Original post of Pólya's Proof, using similar ideas of convexity of $e^x$:
Let $f(x) = e^{x-1}-x$. The first derivative is $f'(x)=e^{x-1}-1$ and the second derivative is $f''(x) = e^{x-1}$.
$f$ is convex everywhere because $f''(x) > 0$, and has a minimum at $x=1$. Therefore $x \le e^{x-1}$ for all $x$, and the equation is only equal when $x=1$.
Using this inequality we get
$$\frac{x_1}{a} \frac{x_2}{a} \cdots \frac{x_n}{a} \le e^{\frac{x_1}{a}-1} e^{\frac{x_2}{a}-1} \cdots e^{\frac{x_n}{a}-1}$$
with $a$ being the arithmetic mean. The right side simplifies
$$\exp \left(\frac{x_1}{a} -1 \ +\frac{x_1}{a} -1 \ + \cdots +  \frac{x_n}{a} -1  \right)$$
$$=\exp \left(\frac{x_1 + x_2 + \cdots + x_n}{a} - n \right) = \exp(n - n) = e^0 = 1$$
Going back to the first inequality
$$\frac{x_1x_2\cdots x_n}{a^n} \le 1$$
So we end with
$$\sqrt[n]{x_1x_2\cdots x_n} \le a$$
Comment: This reminds me of a trick I found: $e^x \geq 1+x$ by similar calculations as the start of this answer. Then $e^{1/n} > 1 + 1/n = (n+1)/n,$ so $e^{1 + 1/2 + 1/3 + \ldots + 1/n} > (2/1) (3/2) \ldots ( (n+1)/n ) = n+1,$ so $H_n:= 1 + 1/2 + \ldots + 1/n > \log (n+1),$ and in particular it diverges.
Comment: @qwr : i know this thread is a few years old but i still have a question. How is exp(xi/a - n)=exp(n-n) ?
Comment: Almost all your inequalities are reversed.
Comment: @Martín-BlasPérezPinilla Woops, fixed
Comment: @hukachaka $a$ is defined as the arithmetic mean.
Answer: I shall provide a simple geometric proof of the inequality in the case of two variables (which I have not been able to find anywhere else - a proof involving a triangle in a circle seems to be popular).
Consider the square of side $a + b$ in the figure below.

The area of the square is $(a + b)^2$. But as it completely contains the four blue rectangles, each of area $ab$, it follows that
$(a + b)^2 \ge 4ab \Rightarrow\\
\dfrac{a + b}{2} \ge \sqrt{ab}
$
Further, note that there is a square in middle, of side $(b - a)$, and hence area $(b - a)^2$. Therefore the inequality is strict except when $a = b$.
This proves the two-variable case. The same can be extended to the $n$-variable case. I have tried extending it to three variables, but it is difficult to argue why exactly $27$ rectangular parallelepipeds (of sides $a, b, c$) fit  in the cube (of side $a + b + c$), though I can see it is so. Any suggestions?
Answer: As $(\sqrt{x_1}-\sqrt{x_2})^2 \geq 0$ we have $$\sqrt{x_1 \cdot x_2} \leq \frac{x_1+x_2}{2}.$$ Applying this inequality twice, we get $$(x_1 x_2 x_3 x_4)^{\frac{1}{4}} \leq \frac{\sqrt{x_1 x_2}+\sqrt{x_3 x_4}}{2} \leq \frac{x_1+x_2+x_3+x_4}{4}.$$ By induction, it is not difficult to see that $$(x_1 \cdots x_{2^k})^{\frac{1}{2^k}} \leq \frac{x_1+\ldots+x_{2^k}}{2^k} \tag{1}$$ for all $k \geq 1$.
It remains to fill the gaps between the powers of two. So let $x_1,\ldots,x_n$ be arbitrary  positive numbers and choose $k$ such that $n\leq 2^k$. We set
$$\alpha_i := \begin{cases} x_i & i \leq n \\ A & n< i \leq 2^k \end{cases}$$
where $A:= \frac{x_1+\ldots+x_n}{n}$. Applying $(1)$ to the $(\alpha_1,\ldots,\alpha_{2^k})$ yields
$$\bigg( x_1 \ldots x_n A^{2^k-n} \bigg)^{\frac{1}{2^k}} \leq \frac{x_1+\ldots+x_n+(2^k-n) A}{2^k} = A.$$
Hence,
$$(x_1 \ldots x_n)^{1/n} \leq A = \frac{x_1+\ldots+x_n}{n}.$$
Comment: I believe this one is due to Cauchy.
Comment: I learnt this proof many years ago and remember thinking it was rather brilliant. I hadn't yet learnt that one theorem can have many different proofs - so I thought that this was THE ONLY proof.
Comment: I think this or bof's proofs are the most elementary. Sometimes this proof is shown using forwards-backwards induction but filling in the gaps is easier to understand imo.
Answer: LEMMA. If $a_1,\dots,a_n$ are positive numbers whose product is equal to $1,$ then $a_1+\dots+a_n\ge n,$ with equality only when $a_1=\cdots=a_n=1.$
Proof by induction on $n.$ The case $n=1$ being trivial, we suppose $n\ge2.$ Let $a_1,\ a_2,\ \dots,\ a_n$ be positive numbers with $a_1a_2\dots a_n=1.$ Without loss of generality, we can assume that $a_1=\max\{a_1,\dots,a_n\}\ge1$ and $a_2=\min\{a_1,\dots,a_n\}\le1.$ Thus we have
$$a_1+a_2-a_1a_2-1=(a_1-1)(1-a_2)\ge0,$$
i.e.,
$$a_1+a_2-a_1a_2\ge1.\tag1$$
Since $a_1a_2,\ a_3,\ a_4,\ \dots,\ a_n$ are $n-1$ positive numbers with product equal to $1,$ by the inductive hypothesis we have
$$a_1a_2+a_3+\cdots+a_n\ge n-1.\tag2$$
Adding the inequalities (1) and (2), we get
$$a_1+a_2+a_3+\cdots+a_n\ge1+(n-1)=n.\tag3$$
If equality holds in (3) then we must have equality in (1), that is, $a_1=1$ or $a_2=1,$ whence $a_1=\dots=a_n=1.$

THEOREM. If $x_1,\ x_2,\ \dots,\ x_n$ are positive numbers, then
$$\frac{x_1+x_2+\cdots+x_n}n\ge(x_1x_2\cdots x_n)^{\frac1n},$$
with equality only when $x_1=x_2=\cdots=x_n.$
Proof. Let $g=(x_1x_2\cdots x_n)^{\frac1n}.$ According to the lemma we have
$$\frac{x_1}g+\frac{x_2}g+\cdots+\frac{x_n}g\ge n,$$
i.e.,
$$\frac{x_1+x_2+\cdots+x_n}n\ge g=(x_1x_2\cdots x_n)^{\frac1n}.$$
Equality holds only if $\frac{x_1}g=\frac{x_2}g=\dots=\frac{x_n}g=1,$ that is, $x_1=x_2=\cdots=x_n.$
Comment: I enjoyed this proof a lot. There were so many nice elements. I like how the product is always positive, and how nicely the a_1a_2 terms cancel each other out when you add the inequalities, and how elegantly this lemma is applied to prove the problem. Did you come up with this on your own?
Comment: @Philipp I assumed that $a_1=\max\{a_1,\dots,a_n\}$ and $a_2=\min\{a_1,\dots,a_n\}$.
Comment: How did you get step (2)? Shouldn't it be $a_1+a_2+a_3+\cdots$?
Comment: Oh ok, u've considered $a_1a_2$ as a single number, not as two distinct ones. Got it.
Comment: I wanted an elementary algebraic proof (with the examination of rectangles/squares in 2-dim  driving it) which leads to $\quad \sum_{i=1}^n x_i^n \ge n \prod_{i=1}^n x_i$. $\quad$ But this would inexorably lead to proving your lemma! Although dependent on  'proof aesthetics', can't understand why this is #1 answer.  (+1)
Comment: The fact that $a_1=a_2=1$ is clear but I don't see why you can conclude $a_1=\dots=a_n=1$? It would be possible to have, say $a_3<1$ and $a_4>1$ and still satisfy $a_1+a_2+a_3+\cdots+a_n=n$. Can you elaborate a bit?
Comment: Is this based on the rearrangement inequality?
Comment: @qwr Not that I know of. What makes you think it's based on the rearrangement inequality?
Comment: I read somewhere rearrangement inequality could prove AM-GM.
Comment: There are a few different proofs of the AM-GM inequality. I thought you were commenting on the proof I gave.
Answer: As requested by dani_s, I will give the thermodynamic proof of the AM-GM inequality. This is certainly an example of an original proof, although you might argue about whether or not it's rigorous.
Let's start with a list of numbers $x_i$ for which we want to prove the inequality. Take $n$ identical heat reservoirs with the same heat capacity $c$. Reservoir $i$ had initial temperature $x_i$. Bring those reservoirs in contact with each other such that this system evolves to an equilibrium temperature A.
The first law of thermodynamics (conservation of energy) implies that A equals the arithmetic mean of the $x_i$, AM.
The second law of thermodynamics states that the entropy increases until the equilibrium is reached, where the entropy has a maximum. The corresponding formula of change in entropy is
$$\Delta S=c \ln{\frac{T}{T_0}}$$
where $c$ is the heat capacity, $T_0$ the initial temperature and $T$ the end temperature.
In our case $T_i=A$ for all $i$ and $T_{0,i}=x_i$. The total entropy didn't decrease and therefore,
$$\sum_{i=1}^n c \ln\frac{A}{x_i} \geq 0$$
By writing the sum of logarithms as a logarithm of a product, we recognize the geometric mean. Therefore (since $A=AM$):
$$\frac{AM^n}{GM^n} \geq 1$$
This proves the AM-GM inequality.
Comment: The  assumption is that entropy is minimum when all $T_i$ are equal, is known to be true only because of AGM is known to hold.
Comment: There is no need to argue whether this is or not a rigorous proof, as it isn't.
Comment: interesting and fun concept, but nonetheless very circular
Answer: Bernoulli's Inequality says that for $u\ge-1$ and $0\le r\le1$,
$$
(1+u)^r\le1+ru\tag{1}
$$
Setting $u=\frac xy-1$ in $(1)$ says that for $x,y\gt0$,
$$
\left(\frac xy\right)^r\le(1-r)+r\frac xy\tag{2}
$$
If we multiply $(2)$ by $y$, we get
$$
x^ry^{1-r}\le rx+(1-r)y\tag{3}
$$
Now $(3)$ can be used inductively to get
$$
x_1^{r_1}x_2^{r_2}x_3^{r_3}\dots x_n^{r_n}\le r_1x_1+r_2x_2+r_3x_3+\dots+r_nx_n\tag{4}
$$
where $r_1,r_2,r_3,\dots,r_n\ge0$ and $r_1+r_2+r_3+\dots+r_n=1$.

Inductive step:
Suppose that $(4)$ holds, then we can use $(3)$ to get
  $$
\begin{align}
&\left(x_1^{r_1}x_2^{r_2}x_3^{r_3}\dots x_n^{r_n}\right)^{1-r_{n+1}}x_{n+1}^{r_{n+1}}\\
&\le(1-r_{n+1})\left(r_1x_1+r_2x_2+r_3x_3+\dots+r_nx_n\right)+r_{n+1}x_{n+1}\tag{5}
\end{align}
$$
  where $(1-r_{n+1})(r_1+r_2+r_3+\dots+r_n)+r_{n+1}=1$
Answer: There is a more direct induction proof.
We can assume that $0<a_1\leq \dots \leq a_n$ holds. Let us set $A=\frac{a_1+ \dots +a_n}{n}$.
First notice that $(a_n-A)(A-a_1)\geq 0$, which can be rewritten as $\frac{a_1a_n}{A}\leq a_1+a_n-A $.
Now we assume that the property holds for $n-1$; we will apply it to the positive numbers ${a_2,\ldots , a_{n-1},a_1+a_n-A}$. This gives: $$\left(\frac{\prod_{k=1}^na_k}{A}\right)^{1/(n-1)}\leq \left[(\prod _{k=2}^{n-1}a_k)(a_1+a_n-A)\right]^{1/(n-1)}\leq \frac{a_1+\dots +a_n-A}{n-1}= A.$$
So : $$\prod_{k=1}^na_k\leq (A^{1+1/(n-1)})^{n-1}=A^n.$$
Answer: This is a proof using Buffalo way (see this link for what buffalo way is http://www.artofproblemsolving.com/Forum/viewtopic.php?f=55&t=522084), I couldn't find it anywhere, I jush heard it's possible, so I tried it, hopefully there are no mistakes, but even if there are I think they will be easy to correct, the main idea should still be right. We'll proceed by strong induction, base case holds trivially from inequality $(x_1 - x_2)^2 \geq 0$, assume that AM-GM holds for all $k$ such that $1 < k < n$. Then we wish to prove that $$x_1^n + x_2^n + \cdots + x_n^n - nx_1x_2\cdots x_n \geq 0$$ This inequality is clearly symmetric, hence we may WLOG suppose $x_1 = \min\{x_1,x_2,\cdots,x_n\} = x$, therefore there exist $y_1,y_2,\cdots,y_{n - 1} \geq 0$ such that $x_i = x + y_{i - 1}$ for all $i \in \{1,2,\cdots,n\}$. Therefore the inequality can be rewritten as $$x^n + (x + y_1)^n + (x + y_2)^n + \cdots + (x + y_{n - 1})^n - nx(x + y_1)(x + y_2) \cdots (x + y_{n - 1}) \geq 0$$ This is a polynomial in $x$ and expanding this polynomial we get that the coefficient of $x^{n - k}$, where $1 < k < n$, is $$\binom{n}{k}p_k(y_1,y_2,\cdots,y_{n - 1}) - ne_k(y_1,y_2,\cdots,y_{n - 1})$$ where $p_k$ is $k$-th power sum and $e_k$ is $k$-th elementary symmetric polynomial. So it suffices to prove that $$\binom{n}{k}p_k(y_1,y_2,\cdots,y_{n - 1}) - ne_k(y_1,y_2,\cdots,y_{n - 1}) \geq 0$$ But by inductive hypothesis we get $$\frac{n}{k} \cdot \left(y^k_{i_1} + y^k_{i_2} + \cdots + y^k_{i_k}\right) - ny_{i_1}y_{i_2} \cdots y_{i_k} \geq 0,$$ where $i_1,i_2,\cdots,i_k \in \{1,2,3,\cdots,n - 1\}$ are pairwise distinct. Doing this for all the possible combinations of indices $i_1,i_2, \cdots, i_k$ we in fact get stronger inequality $$\frac{n}{k} \cdot \binom{n - 2}{k - 1} p_k(y_1,y_2,\cdots,y_{n - 1}) - ne_k(y_1,y_2,\cdots,y_{n - 1}) \geq 0.$$ Now also clearly coefficients of $x^n$ and $x^{n - 1}$ are $0$ and coefficient of $x^0$ is just $p_n(y_1,y_2,\cdots,y_{n - 1})$. Hence all the coefficients of our polynomial are non-negative, therefore the polynomial is non-negative, thus the inductive step is proved and the whole proof is finished.
Answer: Let $S(n)$ denote the statement
$$
S(n):\; \frac{x_1+x_2+\cdots+x_n}{n}\geq\sqrt[n]{x_1x_2\ldots x_n},\quad n\in\mathbb{N}.
$$
Base step ($n=1$): The statement $S(1)$ says that $\frac{x_1}{1}\geq\sqrt[1]{x_1}$, which is true because $x_1 = x_1$.
Base step ($n=2$): The statement $S(2)$ says that
$$
\frac{x_1+x_2}{2}\geq\sqrt{x_1x_2},\tag{1}
$$
which is true because
$$
a\leq x \leq b \longleftrightarrow a+b\geq x+\frac{ab}{x}, \qquad 0<a\leq b,\; x>0.\tag{1*}
$$
Inductive step ($S(k)\to S(k+1)$): Fix some $k\geq 1$, where $k\in\mathbb{N}$. Assume that
$$
S(k):\; \frac{x_1+x_2+\cdots+x_k}{k} \geq \sqrt[k]{x_1x_2\ldots x_k}
$$
holds. To be proved is that
$$
\frac{x_1+x_2+\cdots+x_{k+1}}{k+1}\geq\sqrt[k+1]{x_1x_2\ldots x_{k+1}}
$$
follows. If $x_1 = x_2 = \cdots = x_{k+1}$, then the proof is done. If not, let $x_1x_2\ldots x_{k+1} = \rho^{k+1}$. Without loss of generality, assume that $x_1\leq x_i$ and $x_i \leq x_2$ for all $i$; that is, assume that $x_1 < \rho < x_2$. Beginning with the left side of $S(k+1)$ [excluding the $k+1$ divisor],
\begin{align}
x_1+x_2+\cdots+x_{k+1} &\,\geq\, \rho+\frac{x_1x_2}{\rho}+x_3+\cdots+x_k+x_{k+1}\tag{by (1*)}\\
                       &\,\geq\, \rho+k\cdot\left(\sqrt[k]{\frac{x_1x_2}{\rho}x_3\ldots x_{k+1}}\right)\tag{by $S(k)$}\\
                       &\,=\, (k+1)\rho,
\end{align}
one arrives at the right side of $S(k+1)$ [with a $k+1$ multiple], thereby showing that $S(k+1)$ is also true, completing the inductive step. Thus, by mathematical induction, $S(n)$ is true for all $n\geq 1$, where $n\in\mathbb{N}$.
Answer: Draw graph of $y= \ln x$.
Choose $n$ points on it.A polygon of $n$ sides is thus formed whose coordinates of whose centroid is $$G \left (\frac{(x_1+x_2+....x_n)}n, \frac{(y_1 + .....y_n)}n\right ) = \left (\frac{(x_1+x_2+....x_n)}n, \frac{(\ln x_1 + \ln x_2 + .... + \ln x_n)}n\right )$$
Form centroid we draw a perpendicular to $x$ axis and extend it to meet the graph of $y= \ln x$ at $C$ and $y$ axis at $D$.
Now coordinates of point $C$ are $\left (\frac{(x_1+x_2+....x_n)}n, \ln \left (\frac{x_1+x_2+....x_n}n\right )\right )$.
Now $$CD= \ln {\left (\frac{x_1+x_2+....x_n}n\right )}$$   ($  y$ coordinate of $C$).
$$GD = \frac{\ln x_1 + \ln x_2 + .... + \ln x_n}n = \frac{\ln (x_1\cdot x_2\cdot  ....x_n)} n$$ ($y$ coordinate of $G$).
Now $CD> GD$   (as centroid of a convex polygon is always inside the polygon)
$$\therefore \ln {\left (\frac{x_1+x_2+....x_n}n\right )} > \frac{\ln (x_1\cdot x_2\cdot  ....x_n)} n = \ln \left ((x_1 \cdot x_2 \cdot ... x_n)^{\frac 1n} \right )$$ Now base and the number are positive. So we take antilog of both sides and get$$\frac{x_1+x2+....x_n}n > (x_1\cdot x_2\cdot  ....x_n)^{1/n}$$
Now, it is also possible that all the selected $n$ points are only one point. Hence then the centroid is the point itself. Hence $\frac{x_1+x_2+....x_n}n = (x_1\cdot x_2\cdot  ....x_n)^{1/n}$.
Thereby proving that $\frac{x_1+x_2+....x_n}n \geq (x_1\cdot x_2\cdot  ....x_n)^{1/n}$, where equality holds when$ x_1=x_2=...= x_n$.
Comment: Can you please fix the formatting.
Answer: This is not an original  or different proof but since any question, asking for a proof for this inequality, gets closed as a duplicate of this question ... I feel this answer should be here too.

First, let me prove the result that if there are two numbers of the same sum, the numbers which are closer together have a greater product.
$$ t + u = x + y $$
Let $t,u$ be further apart from each other than $x,y$
But, $$ t - u \gt  x - y $$
Consider the following identity, writing the product of two numbers as a function of it's sum and difference. Since we are subtracting a positive quantity, and the sum is the same, the greater product is of the numbers with the lesser difference.
$$4ab = (a+b)^{2} - (a-b)^{2}$$
From this, we clearly see that $$xy \gt tu$$
Now, let's consider a set of numbers
$$a, b, c {\dots} n$$
Let us choose its arithmetic mean, $M$ given by
$$M = \frac{a+b+c+{\dots}n}{n}$$
The product of this series is
$$P = a.b.c.{\dots}n$$
Now, we make another series of numbers
$$a_{1}, b_{1}, c_{1} {\dots} n_{1}$$
We choose this series in such a way that all elements are equal but we make one change. We choose one number less than $M$, (say $a_{1}$) and write $a_{1} = M$.
However, we'd like to preserve the sum and the $AM$ of this series so we'd choose a number greater than $M$, say $b_{1}$ and reduce its value so that $a_{1} + b_{1} = a + b$. Since, $a_{1}$ has been increased, $b_{1}$ must be decreased. All the other values remain as their older counterparts.
$c_{1} = c, d_{1} = d, {\dots} n_{1} = n$
Now we observe,
$P_{1} = a_{1}.b_{1}.c_{1}{\dots}n_{1}$
           $=Mb_{1}.c{\dots}n$
Since the product of the terms $c_{1}d_{1}{\dots}n_{1} = cd{\dots}n$, and $Mb_{1} \gt ab$,
$$\implies P_{1} \gt P$$
Now, we construct another series of terms, $a_{2}, b_{2},c_{2}{\dots}n_{2}$ in the same way where all the terms are equal to their counterparts of the previous series. We write, $ b_{2} = M$, and increase the value of a number less than $M$, (say $c_{2}$) so that the sum $b_{2}+c_{2} = b_{1} + c_{1}$ is preserved, but $b_{2}c_{2} \gt b_{1}c_{1}$, since $b_{2},c_{2}$ are closer together.
Now, we observe the product of this series.
$$P_{2}= a_{2}b_{2}c_{2}{\dots}n_{2}$$
    $$\implies P_{2} = M^{2}c_{2}{\dots}n_{2}$$
So, by the similar logic, $$P_{2} \gt P_{1}$$
We go on constructing many series making a new element equal to M each time and increasing the product we get,
$$P_{n} \gt {\dots} \gt P_{2} \gt P_{1} \gt P$$
$$\implies P_{n} = M^{n} \gt P$$
$$\implies ( {\frac{a+b+c+\dots+n}{n}})^{n} \gt {a.b.c.{\dots}n}$$
But, both the $L.H.S.$ and the $R.H.S$ are positive quantities.
$$\implies \frac{a+b+c\dots+n}{n} \gt {(a.b.c.{\dots}n)}^{\frac{1}{n}}$$
And, Voila !
$$\implies A.M \gt G.M.$$
Comment: This is hiding the formalism of an induction proof :)
Answer:
In the diagrams, the circle is tangential to the horizontal line at $C$ and intersects the vertical line at $A$ and $B$, while the lines themselves intersect at $P$. In the figure on the left, let $a = PA$, $b = PB$, and $c = PC$. By the power of the point $P$, we know $c^2 = ab$ or $c = \sqrt{ab}$.
Then, we shift the circle to the right so that it is tangential to both lines. The circle being a symmetric figure, we know the new $PA$ is $\frac{a + b}{2}$ and therefore $PC$ is also $\frac{a + b}{2}$. But as we moved the circle to the right, the new $PC \geq c$ and hence
$$\frac{a + b}{2} \geq \sqrt{ab}$$
(Note that equality occurs when $A$ and $B$ are the same in the figure on the left.)
I am not sure about this, but I think the proof can be extended to the AM-GM inequality with 3 variables if we consider a sphere with one tangential plane and one intersecting plane, and we apply the above proof to each 'slice'... by extension, one could consider the $n$-dimensional sphere intersecting with $(n-1)$-dimensional planes, but as I said, I am very unsure about this.
(The credit for this proof goes to Sujay Kazi, a friend at a math club I attend. He recently presented this proof and I cannot recall seeing it in the usual lists of AM-GM proofs, so I am including it here.)
Comment: Very nice proof! :)
Answer: Just consider a probabilistic approach of the proof using the convexity of the function $-\log x$
and using Jensen's inequality.
Let $\{a_1,a_2,a_3,\ldots,a_n\}$ be a set of positive numbers. Consider a distribution for a random variable $X$ by placing weight $1/n$ on each of these numbers.Then the mean of the random variable $X$ is the arithmetic mean (AM), $$E(X)=n^{-1}\sum_{i=1}^n a_i$$Then since $-\log x$ is a convex function,we have by Jensen's inequality that
$$-\log\left(\frac {\sum_{i=1}^n a_i}{n}\right)\le E(-\log X)=-\frac{1}{n}\left(\sum_{i=1}^n \log a_i\right)=-log(a_1a_2a_3....a_n)^{1/n}$$
or equivalently $$\log\left(\frac {\sum_{i=1}^n a_i}{n}\right)\ge \log(a_1a_2a_3....a_n)^{1/n}$$
and hence we can see that $$(a_1a_2a_3....a_n)^{1/n}\le \frac{\sum_{i=1}^n a_i}{n}$$
As we can see the inequality on the left hand side of this inequality is the geometric mean and the right hand side is the arithmetic mean for any set of positive numbers.
Note: If you replace $a_i$ by $1/a_i$ we get the relationship between the harmonic mean ,the arithmetic mean and the geometric mean
Comment: my favorite proof. utilizing the fact that this is a corollary of the behavior of convex functions and tying it together is much better IMO than ad hoc algebraic manipulations
Answer: Applying the Log sum inequality (direct consequence of Jensen inequality)
$$ \sum a_i \log \frac{ b_i}{a_i} \le a \log \frac{b}{a}$$
where $a=\sum a_i$ and $b=\sum b_i$, $a_i\ge 0$, $b_i\ge 0$; setting $b_i=x_i/n$ $a_i=1/n$ we get
$$  \frac{1}{n}\sum \log  x_i \le \log \left( \frac{\sum x_i}{n}\right) $$
or
$$\log\left (\frac{x_1+ \ldots + x_n}{n} \right) \geq \frac{ \log x_1 +\log x_2 +\cdots  \log x_n}{n}$$
Answer:
$$
\frac{x_1+x_2+....+x_n}{n}\geq\sqrt[n]{x_1x_2....x_n}
$$

Using $\color{blue}{\text{Forward-Backward Induction/Cauchy Induction}}$,
Our base case is $n=2$ as $n=1$ is trivial.
Base Case:
$$
P(2):(\sqrt{x_1}-\sqrt{x_2})^2\geq0\implies x_1+x_2-2\sqrt{x_1x_2}\geq0\\
\implies x_1+x_2\geq2\sqrt{x_1x_2}\implies \frac{x_1+x_2}{2}\geq\sqrt{x_1x_2}
$$
$P(2)$ is true.
Inductive Step:
1.) Forward Part:
Let the inequality holds for $n=k$, ie. $P(k)$ is true.
$$
P(k):\frac{x_1+x_2+...+x_k}{k}\geq\sqrt[k]{x_1.x_2....x_k}
$$
$$
P(2k):\frac{x_1+x_2+...+x_{2k}}{2k}=\frac{1}{k}\Big(\frac{x_1+x_2}{2}+\frac{x_3+x_4}{2}+...+\frac{x_{2k-1+x_{2k}}}{2}\Big)\geq\frac{\sqrt{x_1x_2}+\sqrt{x_3x_4}+...+\sqrt{x_{2k-1}x_{2k}}}{k}\\\geq\sqrt[k]{\sqrt{x_1x_2x_3....x_{2k-1}x_{2k}}}=\sqrt[2k]{x_1x_2...x_{2k}}
$$
$P(2k)$ is true whenever $P(k)$ is true.
2.) Backward Part:
Substitute $x_k=\frac{x_1+x_2+...+x_{k-1}}{k-1}$ in $P(k)$,
$$
P(k-1):\frac{x_1+x_2+...+x_k}{k}\geq\sqrt[k]{x_1x_2...x_k}\\
\frac{x_1+x_2+...+x_{k-1}+\frac{x_1+x_2+...+x_{k-1}}{k-1}}{k}\geq\sqrt[k]{x_1x_2...x_{k-1}.\frac{x_1x_2...x_{k-1}}{k-1}}\\
\bigg(\frac{x_1+x_2+...+x_{k-1}}{k-1}\bigg)^k\geq x_1x_2...x_{k-1}.\frac{x_1x_2...x_{k-1}}{k-1}\\
\bigg(\frac{x_1+x_2+...+x_{k-1}}{k-1}\bigg)^{k-1}\geq\frac{x_1x_2...x_{k-1}}{k-1}\\
\frac{x_1+x_2+...+x_{k-1}}{k-1}\geq \sqrt[k-1]{\frac{x_1x_2...x_{k-1}}{k-1}}
$$
$P(k-1)$ is true whenever $P(k)$ is true.
$\implies$ By the forward-backward induction AM-GM inequality is true for all $n$.
Comment: In the final part, how you conclude the 4th inequality?
Answer: This is a plausibility argument rather than a complete proof. Without loss of generality we may assume that $x_1,x_2,\dots,x_n\in[0,1].$ Let $p_i=x_i^{1/n}\in[0,1].$
Consider the following variant of Russian Roulette. You are faced with a panel of $n$ buttons. If you press the $i^{\text{th}}$ button, then with probability $p_i$ you will get a fatal electric shock. You are required to press a button $n$ times. The probabilities $p_1,\dots,p_n$ are known to you, but the buttons are not labeled, you don't know which is which. You can choose between two strategies.
I. Press each button once.
II. Choose a button at random and press it $n$ times.
It is INTUITIVELY OBVIOUS that strategy II is better: you have a better chance of survival pressing the same button that you already pressed and lived, than pressing an untried button. (Prove this rigorously and you have a proof of the AM-GM inequality.)
Now, the probability of survival with strategy I is
$$p_1p_2\cdots p_n=(x_1x_2\cdots x_n)^{1/n}$$
and with strategy II it's
$$\frac{p_1^n+p_2^n+\cdots+p_n^n}n=\frac{x_1+x_2+\cdots+x_n}n,$$
so the fact that strategy II dominates strategy I is expressed by the AM-GM inequality
$$(x_1x_2\cdots x_n)^{1/n}\le\frac{x_1+x_2+\cdots+x_n}n.$$
Answer: Just came up with this proof that uses only the Cauchy-Schwarz inequality. Not sure if it's already known.
We first show the following result for polynomials.

Let $p$ be a polynomial with non-negative coefficients.
  Then $\sqrt{p(a) \, p(b)} \geq p(\sqrt{ab})$
  for all $a, b \geq 0$.

Proof. Let $p(x) = c_n x^n + c_{n-1} x^{n-1} + \cdots + c_0$. Then let $\vec{v} := (\sqrt{c_n a^n}, \sqrt{c_{n-1} a^{n-1}}, \dots, \sqrt{c_0 a^0})$,
and similarly define $\vec{w} = (\sqrt{c_n b^n}, \sqrt{c_{n-1} b^{n-1}}, \dots, \sqrt{c_0 b^0})$. The result is immediate from Cauchy-Schwarz. $\square$
We use this result to show AM-GM for two variables.

Let $a, b \geq 0$. Then $\frac{a+b}{2} \geq \sqrt{ab}$.

Proof. Let $P_n$ be the $n^\text{th}$-order Taylor polynomial of  $e^x$. By the previous result, we have
$$\sqrt{P_n(a) \, P_n(b)} \geq P_n(\sqrt{ab})$$
for all $n \geq 0$. The desired result follows by taking $n \to \infty$ and noting that $e^x$ is increasing. $\square$
I am not sure whether this result can be extended to multiple variables.
Answer: If $a_1,...,a_n>0$, and $0<p\le q$, by Hölder inequality:
$$\left(\frac{1}{n}\sum_{k=1}^na_k^p\right)^{\frac{1}{p}}\le\left(\frac{1}{n}\sum_{k=1}^na_k^q\right)^{\frac{1}{q}}.$$
Also, using De l'Hopital we get:
$$\lim_{p\rightarrow 0^+}\left(\frac{1}{n}\sum_{k=1}^na_k^p\right)^{\frac{1}{p}}=\exp\left(\frac{1}{n}\sum_{k=1}^n \log(a_k)\right)=\left(\prod_{k=1}^na_k\right)^{\frac{1}{n}}$$
So:
$$\forall q>0, \left(\prod_{k=1}^na_k\right)^{\frac{1}{n}}\le\left(\frac{1}{n}\sum_{k=1}^na_k^q\right)^{\frac{1}{q}}.$$
In particular for $q=1$ we get AM-GM.
Comment: I think Hölder's inequality is way more general than AM-GM and proving the latter through the former is something artificial.
Comment: @pointguard0 If that is your problem, you can always use Cauchy Schwarz to get the result for $p=1/2,q=1$, then $p=1/4, q=1/2$, and so on...
Answer: An alternate proof for the case $n=3$: it is equivalent to show that $a^3+b^3+c^3-3abc \geq 0$ for positive reals.
$$\begin{align}
  a^3+b^3+c^3 - 3abc & = \\
  c^3 + (a+b)^3 -3ab(a+b)-3abc & = \\
  c^3 + (a+b)^3 - 3ab(a+b+c) & = \\
  (a+b+c)^3 - 3c(a+b)(a+b+c) - 3ab(a+b+c) & = \\
  (a+b+c)^3 - 3(ab+ac+bc)(a+b+c) & = \\
  (a+b+c) \cdot ((a+b+c)^2 - 3(ab+ac+bc)) & = \\
  (a+b+c) \cdot ((a^2+b^2+c^2) - (ab+ac+bc)) & = \\
  (a+b+c) \cdot \cfrac{(a-b)^2+(b-c)^2+(c-a)^2}{2}
\end{align}$$
And it is obviously true.
(P.S.: we can use the same technique of transfinite induction from here too!)
Answer: I think we can use Korovkin's inequality :

Korovkin's inequality :
Let $x_1,x_2,\cdots,x_n$ be positive numbers then :
$$\frac{x_1}{x_2}+\frac{x_2}{x_3}+\cdots+\frac{x_{n-1}}{x_n}+\frac{x_n}{x_1}\geq n$$

Proof :
See https://archive.org/details/InequalitieslittleMathematicsLibrary/page/n15
Using Korovkin's inequality  and putting $\frac{x_{i}}{x_{i+1}}=y_i$ we have :
$$y_1+y_2+\cdots+y_{n-1}+y_{n}\geq n$$
Where $y_1y_2\cdots y_{n-1}y_n=1$
Putting $a_i\alpha=y_i$ where $\alpha$ is a positive numbers we have :
$$a_1+a_2+\cdots+a_{n-1}+a_{n}\geq \frac{n}{\alpha}$$
Where $a_1a_2\cdots a_{n-1}a_n=\frac{1}{\alpha^n}$
We get :
$$a_1+a_2+\cdots+a_{n-1}+a_{n}\geq \frac{n}{(\alpha^{n})^{\frac{1}{n}}}$$
or
$$a_1+a_2+\cdots+a_{n-1}+a_{n}\geq n(a_1a_2\cdots a_{n-1}a_n)^{\frac{1}{n}}$$
Done!
Comment: Please copy your answer [here](https://math.stackexchange.com/a/3693858/72152) to this link: https://math.stackexchange.com/questions/3798002/is-it-true-that-sum-i-1n-ngx-ig-gx-i-ge-n2g-g2n-for-all.  In a week, I may copy your answer into the link so that the answer is preserved.  The answer will be a Community Wiki post, and you can remove the part that belongs to you, and put it in your own separate answer.  (I'm not sure if you were notified from my comment in the deleted post.)
Answer: By analyzing rectangles we discover the following identities, true for all real numbers $u$ and $v$,
$\tag 1 u(u+w) = \frac{u^2}{2} + \frac{u}{2} (u + w) + (u w)/2$
$\tag 2 \frac{u^2+(u+w)^2}{2} - u(u+w) = \frac{w^2}{2}$
For the impetus for deriving these identities, see this answer to

$\quad$ Intuitive understanding of $\sqrt{a b} \leq \frac{a+b}{2}, \:
> a,b \ge 0$

The second identity can be used to immediately  derive the AM-GM inequality for two variables.
It is important that any proof keeps track of the
$\quad$ equality hold if and only if ...
for the AM-GM inequality.
Although two other answers discuss forward-backward induction, I must insist that nothing compares to the 'algebraic crispness' found in wikipedia/The subcase where $n \lt 2^k$. It is this subcase (the 'go backward' part of the induction) that is the most challenging, and I copy it directly from the source in the next section.

The subcase where $n \lt 2^k$
If $n$ is not a natural power of $2$, then it is certainly less than some natural power of $2$, since the sequence $2, 4, 8, . . . , 2^k, . . .$ is unbounded above. Therefore, without loss of generality, let $m$ be some natural power of $2$ that is greater than $n$.
So, if we have $n$ terms, then let us denote their arithmetic mean by $\alpha$, and expand our list of terms thus:
$
{\displaystyle x_{n+1}=x_{n+2}=\cdots =x_{m}=\alpha .}
$
We then have:
\begin{aligned}\alpha &={\frac {x_{1}+x_{2}+\cdots +x_{n}}{n}}\\[6pt]&={\frac {{\frac {m}{n}}\left(x_{1}+x_{2}+\cdots +x_{n}\right)}{m}}\\[6pt]&={\frac {x_{1}+x_{2}+\cdots +x_{n}+{\frac {m-n}{n}}\left(x_{1}+x_{2}+\cdots +x_{n}\right)}{m}}\\[6pt]&={\frac {x_{1}+x_{2}+\cdots +x_{n}+\left(m-n\right)\alpha }{m}}\\[6pt]&={\frac {x_{1}+x_{2}+\cdots +x_{n}+x_{n+1}+\cdots +x_{m}}{m}}\\[6pt]&>{\sqrt[{m}]{x_{1}x_{2}\cdots x_{n}x_{n+1}\cdots x_{m}}}\\[6pt]&={\sqrt[{m}]{x_{1}x_{2}\cdots x_{n}\alpha ^{m-n}}}\,,\end{aligned}
so
$
{\displaystyle \alpha ^{m}>x_{1}x_{2}\cdots x_{n}\alpha ^{m-n}}
$
and
$
{\displaystyle \alpha >{\sqrt[{n}]{x_{1}x_{2}\cdots x_{n}}}}
$
as desired.
Comment: I wanted to extend the 2-dim proof to higher dimension and prove $\quad \sum_{i=1}^n x_i^n \ge n \prod_{i=1}^n x_i$. $\quad$ The techniques employed in [bof's answer](https://math.stackexchange.com/a/1665056/432081) gets the job done.
Answer: Another answer. We can prove this alternative result:
If $a_1, \ldots, a_n$ are positive reals such that $a_1 +  \dots + a_n = n$, then $a_1 \dots a_n \leq 1$.
We can suppose wlog that $a_1 \leq \dots \leq a_n$.
Notice that we can suppose $a_n \not= 1$, or else we could just solve the same problem for $n-1$.
By "pigeonhole principle", we know that $a_1 \leq 1 \leq a_n$. If we change them by their arithmetical mean, the sum stays the same, but the product increases. Indeed, the product "increases" by $(\frac{a_1+a_n}{2})^2-a_1a_n = (\frac{a_1-a_n}{2}) \geq 0$, with equality if and only if $a_1=a_n$.
That way, we can always increase the sum whenever there are at least two different terms. The only way it can't be done is if all terms are equal; and this is the supremum value.
(Another possible solution would be change $a_n$ by $1$ and $a_1$ by $(a_1+a_n)-1$; the sum stays the same but the product "increases" by $a_1+a_n-1-a_1a_n = (1-a_1)(a_n-1) \geq 0$; that way the maximum occurs if all terms are $1$).
Answer: AM-GM inequality says that for any $ a_1, \dots , a_n > 0 $, we have $ \dfrac{a_1 + \cdots + a_n}{n} \geq  \sqrt[n]{a_1 \cdots a_n} $ with equality holding if and only if $ a_1 = \cdots = a_n $.
Here is Cauchy's Backward Induction proof, but with the backward part slightly modified (and hopefully more intuitive). We'll first prove the inequality, and then think about when equality holds. For brevity, let $ P_n $ mean "For any $a_1, \dots a_n > 0, \dfrac{a_1 + \cdots + a_n}{n} \geq \sqrt[n]{a_1 \cdots a_n}$ ".
$P_1$ holds trivially.
$P_2$ is true because $ \dfrac{a_1 + a_2}{2} \geq \sqrt{a_1 a_2} $ can be written as $ a_1 + a_2 - 2\sqrt{a_1 a_2} \geq 0 $, which is just $ (\sqrt{a_1} - \sqrt{a_2})^2 \geq 0 $.
$ P_4 $ comes from $ P_2 $, as $ \dfrac{a_1 + a_2 + a_3 + a_4}{4} = \dfrac{\dfrac{a_1 + a_2}{2} + \dfrac{a_3 + a_4}{2}}{2} \geq \dfrac{\sqrt{a_1 a_2} + \sqrt{a_3 a_4}}{2} \geq \sqrt{\sqrt{a_1 a_2}\sqrt{a_3 a_4}} = \sqrt[4]{a_1 \cdots a_4} $.
Similarly $P_8$ comes from $P_4$, $P_{16}$ comes from $P_8$, etc.
In general, if we know a $ P_{2^k} $ holds then $ P_{2^{k+1}} $ must hold as
$ \dfrac{ a_1 + \cdots +a_{2^{k+1}} }{2^{k+1}} = \dfrac{ \dfrac{ a_1 + \cdots a_{2^k} }{2^k} + \dfrac{ a_{2^{k} + 1} + \cdots a_{2^{k+1}} }{2^k} }{2} \geq \dfrac{(a_1 \cdots a_{2^k})^{ \frac{1}{2^k} }  + (a_{2^k + 1} \cdots a_{2^{k+1}})^{ \frac{1}{2^k} } }{2} \geq \sqrt{ (a_1 \cdots a_{2^k})^{ \frac{1}{2^k} } (a_{2^k + 1} \cdots a_{2^{k+1}})^{ \frac{1}{2^k} } } = (a_1 \cdots a_{2^{k+1}})^{\frac{1}{2^{k+1}}} $.
So it is clear $P_k$ holds whenever $ k $ is a power of $2$.
It now suffices to show "If a $P_{k+1}$ holds, then $P_k$ must hold". [Informally, we showed we can jump to powers of $2$, but there are gaps so now we are trying to show we can also take single steps backwards]. So we'll try to prove this:
Fix any $ a_1, \dots, a_k > 0 $. Now we are to show $ \dfrac{a_1 + \cdots + a_k}{k} \geq (a_1 \cdots a_k)^{\frac{1}{k}} $ , but we have the information $ \dfrac{ a_1 + \cdots + a_k + t }{k+1} \geq (a_1 \cdots a_k t)^{\frac{1}{k+1}} $ for any $ t > 0 $. In order to match the info's RHS to that of the goal we can try picking a $ t $ such that $ (a_1 \cdots a_k t)^{\frac{1}{k+1}} = (a_1 \cdots a_k)^{\frac{1}{k}} $, i.e we can try setting $ t = (a_1 \cdots a_k)^{\frac{1}{k}} $, and in fact it works :
$ \dfrac{ a_1 + \cdots a_k + (a_1 \cdots a_k)^{\frac{1}{k}} }{k+1} \geq (a_1 \cdots a_k)^{\frac{1}{k}} $, giving the required inequality $ \dfrac{a_1 + \cdots + a_k}{k} \geq (a_1 \cdots a_k)^{\frac{1}{k}} $.
[We could've also tried to match info's LHS to that of the goal, i.e we could've tried setting $ t = \dfrac{a_1 + \cdots a_k}{k} $, and even this happens to work !].
So the inequality part is proved. Now we'll think about when the equality is true. The $P_2$-inequality becomes equality if and only if $ \sqrt{a_1} - \sqrt{a_2} = 0 $, i.e if and only it $ a_1 = a_2 $. The $P_4$-inequality becomes equality if and only if $ \sqrt{a_1 a_2} = \sqrt{a_3 a_4}, a_1 = a_2 $ and $ a_3 = a_4 $, i.e. if and only if $ a_1 = \cdots = a_4 $. Proceeding so, it is clear $P_{2^k}$-inequality becomes equality if and only if $ a_1 = \cdots = a_{2^k} $. Now looking at the backwards induction step above, we see that in general equality holds if and only if all the numbers taken are equal.
Answer: We use the method if infinite descent.
Let $P_n$ be the proposition that there is some set $S_n=\{a_1,a_2,\dots a_n\}$ with $a_i\geqslant0$ and $\sum a_i=n$ and for which $\prod a_i > 1$.
We would like to show that $P_n$ is always false. Suppose, for the sake of contradiction, that there is some $n$ for which $P_n$ is true and let $m$ be the smallest such $n$.
Clearly $P_1$ is false and so $m \geqslant 2$.
In order for $\sum a_i=n$ there must be at least one element bigger than $1$ and one less than $1$ (they cannot all equal $1$ because $\prod a_i > 1$) so we can say $a_1>1$ and $a_2<1$.
$$(a_1-1)(1-a_2)>0  \implies a_1+a_2-1 >a_1 a_2 \tag 1$$
We now replace $a_1$ with $a_1+a_2-1$ and $a_2$ with $1$. The sum ($\sum a_i$) doesn't change and, by (1), the product increases, so we still have $\prod a_i > 1$.
But now one of the elements of $S_m$ is equal to $1$ we can define $S_{m-1}=S_m \setminus  \{1\}$ and for this set we have $\sum a_i=m-1$ and $\prod a_i > 1$. This proves $P_{m-1}$ and so contradicts the definition of $m$ and so our assumption that such an $m$ exists must be false and so $P_n$ is false for all $n$.
With the hard work done, AM-GM follows immediately. Suppose
$$\frac{x_1+ \cdots + x_n}{n} < \sqrt[n]{x_1 \cdots x_n}$$
Then define
$$a_i = \frac{n \, x_i}{x_1+ \cdots + x_n}$$
This would prove $P_n$ which we have shown to be false and so no such inequality can be true.
Answer: Here are two variations of the same proof via Hadamard's Determinant Inequality which has an elementary proof via Cholesky Decomposition.
Let $D$ be an $n\times n$ diagonal matrix with $d_{i,i}:=x_i\gt 0$
Proof 1:
The expedient route is to introduce complex numbers and let $F$ be the (unitary) Discrete Fourier Transform matrix.  The matrix $F^*DF$ has constant diagonal necessarily equal to $\frac{1}{n}\sum_{i=1}^n x_i$ (check the trace).
$\prod_{i=1}^n x_i = \det\big(D\big)= \det\big(F^*DF\big)\leq \big(\frac{1}{n}\sum_{i=1}^n x_i\big)^n$
by Hadamard's Determinant Inequality with equality iff $F^*DF$ is diagonal, and $F^*DF$ has constant diagonal so this means
$F^*DF=\big(\frac{1}{n}\sum_{i=1}^n x_i\big)\cdot I\implies D=\big(\frac{1}{n}\sum_{i=1}^n x_i\big)\cdot I$
i.e. equality occurs iff $x_1=x_2=\cdots = x_n$
Proof 2:
An easy way to mimic the above but work over $\mathbb R$ is to consider that when $n=2$ the DFT is
$Q=\frac{1}{\sqrt{2}}\begin{bmatrix}1 &1\\
1& -1\end{bmatrix}$
and the result follows.
For $n\gt 2$, select $k$ such that $2^k \geq n$ and using the Kronecker Product, write
$Q_k:=\underbrace{Q\otimes Q \otimes\ldots\otimes Q}_{Q \text{ occurs k-times}}$
i.e. $Q_k$ is a $2^k\times 2^k$ real orthogonal matrix where every element has the same modulus. (After re-scaling, it is also a Hadamard matrix.)
Let $D_k$ be the following $2^k\times 2^k$ diagonal matrix:
$D_k:=\begin{bmatrix}D &\mathbf 0\\
\mathbf 0& (\frac{1}{n}\sum_{i=1}^n x_i)\cdot I_{r}\end{bmatrix}$
with $r:= 2^k-n$
remark: focusing on $2^k$ and padding excess entries with the mean is reminscent of Cauchy's original proof.
Then $Q_k^T D_kQ_k$ has constant diagonal, with each entry equal to $\frac{1}{n}\sum_{i=1}^n x_i$
$\big(\prod_{i=1}^n x_i\big)\big(\frac{1}{n}\sum_{i=1}^n x_i\big)^{2^k-n} = \det\big(D_k\big)= \det\big(Q_k^T D_kQ_k\big)\leq \big(\frac{1}{n}\sum_{i=1}^n x_i\big)^{2^k}$
$\iff \big(\prod_{i=1}^n x_i\big)\leq \big(\frac{1}{n}\sum_{i=1}^n x_i\big)^n$
by Hadamard Determinant Inequality, and again with equality iff $D_k=\big(\frac{1}{n}\sum_{i=1}^n x_i\big)\cdot I$,
i.e. iff $x_1=x_2=\cdots = x_n$
Answer: (Muirhead's theorem). A necessary and sufficient condition that $[\alpha ']$ should be comparable to $[\alpha]$ for all positive values of the $\alpha$ is that one of $(\alpha ')$ and $(\alpha)$ should be majorized by the other. If $(\alpha ')\prec (\alpha)$ then $[\alpha ']\leq[\alpha]$ with equality only when $(\alpha ')$ and $(\alpha)$ are identical or when all the $\alpha$ are equal.
Note that the AM-GM inequality is equivalent to $$\frac{1}{n} \sum_{k=1}^{n} x_k^n \geq x_1 x_2\cdots x_n$$
Now notice that $$\frac{1}{n}\sum_{k=1}^{n} x_{k}^{n}=[n,0,\ldots,0] \quad \text{and} \quad x_1 x_2\cdots x_n=[1,1,\ldots ,1].$$
By Muirhead's theorem, $$[n,0,0,\ldots ,0] \geq [1,1,\ldots ,1].$$
Answer:
My idea is to use only the Cauchy Schwartz inequality by induction.

Applying the Cauchy_Schwartz inequality on the vectors $(\sqrt{a},\sqrt{a})^T$ and $(\sqrt{b},\sqrt{b})^T$ we get:
$$\sqrt{ab} +\sqrt{ab} \le (a+b)^{1/2}(a+b)^{1/2} $$
that is $$\sqrt{ab} \le \frac{a+b}{2}~~~~~~\color{red}{\text{AM-GM for $n =2$}}$$

Hypothesis of induction: Assume that for all $p\in\{1,2,\cdots, n-1\}$ we have,
  \begin{align*}
\color{blue}{(a_1a_2\cdots a_p)^{1/p}\leq \frac{a_1+a_2+\cdots+a_p}{p}}
\end{align*}
  We want to prove that it is true for $n$. we will discuss two case: $n =2p$ and $n=2p-1$

If $n =2p$ Then we proceed as follows:
Using that case: $n=2$  and the case $n=p$, we have,
$$ \begin{align}\color{blue}{\frac{a_1+a_2+\cdots+a_n}{n}  }&= \frac{1}{2}\left(\overbrace{\frac{a_1+a_2+\cdots+a_p}{p}}^a+\overbrace{\frac{a_{p+1}+a_{p+2}+\cdots+a_n}{p}}^b  \right) \\
&\ge\sqrt{\left(\frac{a_1+a_2+\cdots+a_p}{p}\right) \left(\frac{a_{p+1}+a_{p+2}+\cdots+a_n}{p}\right)}\\
&\ge\sqrt{(a_1a_2\cdots a_p)^{1/p}(a_{p+1}a_{p+2}\cdots a_n)^{1/p}}\\
&=\sqrt{(a_1a_2\cdots a_n)^{1/p}}  = \color{blue}{(a_{p+1}a_{p+2}\cdots a_n)^{1/n} } ~~~~~~\color{red}{\text{AM-GM for $n =2p$}} \end{align}$$
If $n =2p-1$ (we use the case $n=2p$, as follows.we have,  $n+1 =2p $ and $p<n$ : Then taking $$ a_{n+1} = \frac{a_1+a_2+\cdots+a_n}{n}$$
in the previous case we obtain,
\begin{align}&\frac{a_1+a_2+\cdots+a_{n+1}}{n+1}   \ge (a_1a_2\cdots a_{n+1})^{\frac{1}{n+1}}\\
&\Longleftrightarrow\frac{1}{n+1}\left(a_1+a_2+\cdots+a_n+\overbrace{\frac{a_1+a_2+\cdots+a_n}{n}}^{a_{n+1}}  \right) \ge \left(a_1a_2\cdots a_{n}\left(\overbrace{\frac{a_1+a_2+\cdots+a_n}{n}}^{a_{n+1}}\right)  \right)^{\frac{1}{n+1}}\\
\\&\Longleftrightarrow\frac{a_1+a_2+\cdots+a_n}{n} \ge \left(a_1a_2\cdots a_{n}\left(\frac{a_1+a_2+\cdots+a_n}{n}\right)  \right)^{\frac{1}{n+1}}\\
&\Longleftrightarrow\left(\frac{a_1+a_2+\cdots+a_n}{n}\right)^{\frac{n}{n+1}} \ge \left(a_1a_2\cdots a_{n}\right)^{\frac{1}{n+1}}
\\&\Longleftrightarrow \color{blue}{\frac{a_1+a_2+\cdots+a_n}{n} \ge \left(a_1a_2\cdots a_{n}\right)^{\frac{1}{n}}}~~~~\color{red}{\text{AM-GM for $n =2p-1$}}\end{align}
Comment: Please avoid posting duplicate answers: https://math.stackexchange.com/a/2527699/44121   You have already been contacted by a moderator in such regard.

Proofs of AM-GM inequality


using \thanks in pandoc

Question: according to the pandoc manual, a variable "thanks" can used in the YAML of a markdown file to replicate Latex's \thanks command, like so:
---
title: super awesome paper
author: albert enstein
thanks: university of alberta
---

but instead it puts the asterisk on the title and not the author, where it is supposed to go.
EDIT How do I put thanks on the author and not the title with pandoc?
Comment: you'll have to use a custom [template](http://pandoc.org/MANUAL.html#templates)..
Answer: As the comments already points out, you will probably need to create a custom template. The behaviour you describe is the proper behaviour of the /thanks command.
What you want looks like the authors affiliation section for a titlepage. This can be accomplished using the institute variable in the YAML header. It is only supported in a few document classes. The code from it can be found in the default latex template (pandoc -D latex):
$if(institute)$
\providecommand{\institute}[1]{}
\institute{$for(institute)$$institute$$sep$ \and $endfor$}
$endif$

Try this instead of the thanks variable, just lookup which classes supports this prior to your tests.

using \thanks in pandoc


Ajustar colunas na Table do Tkinter

Question: Estou usando o Tkinter no Python, e também usando o recurso Table.
No meu código tenho uma linha, conforme a seguir:
table = Table (frame, dataframe=frame_entrada[['id', 'nome', 'usando_limite', 'telefone']], width = (largura - 100), height = (altura - 50), showtoolbar=False, showstatusbar=False)
No entanto, quando executo o código, algumas colunas da tabela que aparecem no visor do computador não mostram os textos completos, como por exemplo, a coluna  'nome' corta os nomes completos de alguns clientes(dá pra ver apenas o início dos nomes, não o nome completo0. Como faço para ajustar automaticamente (ou até manualmente) a largura das colunas ao conteúdo das células?
Answer: Você está posicionado o elemento Table em um frame, você tem que ver como você esta posicionando esse Frame, você esta usando o método .grid() ou .pack(), com grid você tem que especificar a posição dos elementos como se estivessem em uma tabella ( row e column) no entanto pack simplemente coloca o elemento em uma nova riga do root
Espero ter sido claro
Comment: Só preciso ajustar a largura da coluna à largura do conteúdo das células da planilha, ainda não consegui fazer, nem achei nada sobre.
Comment: @Ricardo você consegue editar a pergunta mostrando o codigo completo?
Answer: Sim, estou o grid. A tabela tá exibindo normalmente na tela, com todos os campos corretamente. Só preciso ajustar a largura de algumas colunas que estão 'cortando' os dados exibidos, como a coluna 'nome'. Só quero ajustar a coluna ao conteúdo da célula...

Ajustar colunas na Table do Tkinter


React Native/Expo yet another SyntaxError: Unexpected token import while testing

Question: I'm developing a mobile app using React-Native and Expo.
Everything is doing great and the app is running as expected.
But my tests are not running when importing some @expo libraries.
The error is the classical one:
    SyntaxError: Unexpected token import
Giving the full context of the erro:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import glyphMap
                                                                                ^^^^^^
SyntaxError: Unexpected token import

Googling a solution I ended up most of the time with something similar to what is mentioned here.
So I wrote on my package.json
  "jest": {
    "transformIgnorePatterns": [
      "/!node_modules\\/@expo"
    ],
    "preset": "react-native"
  }

I also have tried changing the module name to:

/!node_modules\/expo
/!node_modules\/expo/vector-icons
/node_modules/@expo/vector-icons

I also followed another answer and added .babelrc with the content:
{
  "presets": ["babel-preset-expo", "react-native"],
  "env": {
    "test": {
      "plugins": [
        "babel-plugin-dynamic-import-node"
      ]
    }
  }
}

Unfortunately, none of these solutions worked for me.
To give more context, it is a React Native application with Expo, running on OSX
I receive another 5 warnings besides the error above.
The warnings are regarding duplicated module names(probably unrelated but anyway):
jest-haste-map: duplicate manual mock found:
  Module name: ErrorUtils
  Duplicate Mock path: /<project_dir>/node_modules/react-native/Libraries/Core/__mocks__/ErrorUtils.js
This warning is caused by two manual mock files with the same file name.
Jest will use the mock file found in:
/<project_dir>/node_modules/react-native/Libraries/Core/__mocks__/ErrorUtils.js
 Please delete one of the following two files:
 /<project_dir>/node_modules/react-native/node_modules/fbjs/lib/__mocks__/ErrorUtils.js
/project_dir/node_modules/react-native/Libraries/Core/__mocks__/ErrorUtils.js

jest-haste-map: @providesModule naming collision:
  Duplicate module name: camelcase
  Paths: /<project_dir>/node_modules/react-native/node_modules/yargs-parser/node_modules/camelcase/package.json collides with /<project_dir>/node_modules/react-native/node_modules/yargs/node_modules/camelcase/package.json

This warning is caused by a @providesModule declaration with the same name across two different files.
jest-haste-map: @providesModule naming collision:
  Duplicate module name: bser
  Paths: /<project_dir>/node_modules/react-native/node_modules/bser/package.json collides with /<project_dir>/node_modules/react-native/node_modules/fb-watchman/node_modules/bser/package.json

This warning is caused by a @providesModule declaration with the same name across two different files.
jest-haste-map: @providesModule naming collision:
  Duplicate module name: core-js
  Paths: /<project_dir>/node_modules/react-native/node_modules/core-js/package.json collides with /<project_dir>/node_modules/react-native/node_modules/fbjs/node_modules/core-js/package.json

This warning is caused by a @providesModule declaration with the same name across two different files.
jest-haste-map: @providesModule naming collision:
  Duplicate module name: yargs
  Paths: /<project_dir>/node_modules/react-native/node_modules/yargs/package.json collides with /<project_dir>/node_modules/react-native/node_modules/uglify-js/node_modules/yargs/package.json

This warning is caused by a @providesModule declaration with the same name across two different files.

Versions:
react-native: 0.46.1
@expo/vector-icons: 5.1.0
jest: 20.0.4
Any other idea?
**** UPDATE ****
Changing the transformIgnorePatterns to: "/!node_modules\/\@expo"
doesn't make it work, but at least change to another error.
Invariant Violation: Native module cannot be null.

  at invariant (node_modules/react-native/node_modules/fbjs/lib/invariant.js:44:7)
  at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:31:1)
  at Object.<anonymous> (node_modules/expo/src/Location.js:6:26)
  at Object.<anonymous> (node_modules/expo/src/Expo.js:8:1)

Comment: did you figure this out
Answer: I had the same issue. I eventually resolved it by removing and reinstalling jest-expo. Make sure that your version of jest-expo matches your version of Expo.

npm uninstall jest-expo
npm cache clean # or npm cache verify (if Node 5+)
npm install --save-dev jest-expo


Shadow box em imagem React Native

Question: Estou tendo dificuldade para colocar um shadow na imagem, tentei colocar na View e na Image mas não funcionou.
<View style={styles.ContainerImageProfile}>
    <Image style={styles.ImageProfile} source={{uri: 'profile.png'}} />
</View>

ContainerImageProfile: {
        width: 90,
        height: 90,
        borderRadius: 50,
        backgroundColor: 'red',
        overflow: 'hidden',
        marginTop: 100,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.8,
        shadowRadius: 50,

    },
    ImageProfile: {
        width: '100%',
        height: '100%'
    },

Answer: Você está tentando usar isso para Android? esses atributos de Shadow são suportadas somente pelo IOS, como você pode verificar em: https://facebook.github.io/react-native/docs/shadow-props.html
como alternativa você pode usar usar o atributo de estilo elevation, por exemplo:
ContainerImageProfile: {
       ...
       elevation: 1
       ...
    }

senão, acredito que somente com uma biblioteca de terceiro

Shadow box em imagem React Native


SQL+ REGEXP + phone_number of all contacts having 5th digit of their phonenumber as '5' using REGEXP_SUBSTR()

Question: Write a query to display the first_name, city, state and phone_number of all contacts having 5th digit of their phonenumber as '5'. Display the records in ascending order based on their first_name.
Note:Use REGEXP_SUBSTR().
I need help on how to check for the 5th character to be 5 using regular expression
This what I have so far:
SELECT first_name, city, state, phone_number
FROM contact
WHERE REGEXP_SUBSTR(phone_number, '^([[:digit:]]{4})([[:digit:]]{1})([[:digit:]]{4})',\1\2\3)
ORDDER BY first_name ASC;

Comment: Welcome to SO.  Please take some time to read [ask].  This is not a private coding service.  If you want someone to help you, please show some effort and a [mcve]
Comment: why regexp_substr?  A regexp_like which aimed to match the pattern seems more appropriate here: `where regexp_like(phone_number, '^.{4}5')`
Comment: The assignment calls for using REGEXP_SUBSTR(). the editor seems to mark all other ways wrong
Answer: There are two problems here. First, you need to remove everything but digits from the phone number. Second, you need to determine if the fifth digit of the remaining numbers is '5'.
To remove all non-numeric characters you can use
REGEXP_REPLACE(PHONE_NUMBER, '[^0-9]', '')

For example, if your phone number is (123)456-7890' the above will return1234567890`.
Next, you need to determine if the fifth character of the above is the digit '5'. Now, the easy way to do it would be to use
SUBSTR(phone#, 5, 1) = '5'

but of course we can't do things the easy way. To do this using REGEXP_SUBSTR you'd use
'5' = REGEXP_SUBSTR(phone#, '^([0-9]{4})(5)([0-9]{5})$', 1, 1, 'i', 2)

So, putting the above together with your query we get
SELECT first_name, city, state, phone_number
  FROM contact
  WHERE '5' = REGEXP_SUBSTR(REGEXP_REPLACE(PHONE_NUMBER, '[^0-9]', ''),
                              '^([0-9]{4})(5)([0-9]{5})$', 1, 1, 'i', 2)
  ORDER BY FIRST_NAME ASC

SQLFiddle here
Best of luck.
Comment: Thanks a lot! this helps me understand Regular Expressions - It is quite confusing from the materials available online
Answer: select first_name, city, state , phone_number from contact
where SUBSTR(phone_number, 5, 1) = '5' order by first_name asc;
Comment: What about using REGEXP_SUBSTR?


Commerce Customizable product (Example: add/remove topics for pizza)

Question: I'm trying to find a way to give the chance to the customers to "customize
" their products.
Straight example:
Luigi has got a Pizzeria and he would like to sell his pizze online where customers can add or remove topics.
Is there a way to get this option with the basic function of Drupal commerce?
Maybe playing around with products and rules?
This could be very useful for a lot of website type.
I found this module Commerce Customizable Products , it seems to do half of the job. I can add my topics and then with rules I can update the price. It looks like i cannot show the basic topics. Every pizza has to start empty.
Is there anyone who was had experience with it? Any suggestion?
If someone wanted to build a module, I would like to help with it.
Thanks in advance.
12/09/2012 UPGRADE ---------------------
Using Customizable Products I've created a new line item with a term reference field.
It will be visible in the product page and will show all the term from that taxonomy.
In the product I've got the term field(manage display: hidden) where the editor can select the pizza toppings.
Now, because the line item will print all the terms I would like to create a function that checks the term in the product and puts a flag on the right line item term.
Then, because customers can add and remove toppings from the pizza, in the view I would like to create another function that check if the user has unflagged the basic toppings and print the sign " - " before the toppings.
So the pizzeria will receive:
Pizza:
-ham
+salami
Ham was in the basic toppings.
What API can I use to get this work?
Answer: I think this Josh Millar video will help.
Customizable Product with Drupal Commerce: Pizza Store
Comment: Better later than never :D I'm going to have a look this night.


Parsing a text with "xxx = { .. }" in C# with Sprache

Question: As you may already guess, I need some help. I'm currently working on a WPF with a friend, but we have a problem: We need to parse a certain type of text but we have just no idea how to do it. We found Sprache and it seems like a great parser, but we don't know how to use it. Also: English isn't our native language so the introduction article isn't very easy to understand for us.
So we made the decision to ask about it here on Stackoverflow.
The text we want to parse is located in a simple .txt file and looks like this:
<code>focus_tree = {
id = german_focus

country = {
    factor = 0

    modifier = {
        add = 10
        tag = GER
    }
}

default = no

focus = {
    id = GER_autobahn
    icon = GFX_goal_generic_construct_infrastructure
    x = 0
    y = 0
    cost = 10
    ai_will_do = {
        factor = 12
    }

    completion_reward = {
        custom_effect_tooltip = GER_autobahn_tt
        hidden_effect = {
            64 = {
                if = {
                    limit = { is_controlled_by = ROOT }
                    add_building_construction = {
                        type = infrastructure
                        level = 10
                        instant_build = yes
                    }
                }
            }
            59 = {
                if = {
                    limit = { is_controlled_by = ROOT }

                    add_building_construction = {
                        type = infrastructure
                        level = 10
                        instant_build = yes
                    }
                }
            }
            60 = {
                if = {
                    limit = { is_controlled_by = ROOT }
                    add_building_construction = {
                        type = infrastructure
                        level = 10
                        instant_build = yes
                    }
                }
            }
            54 = {
                if = {
                    limit = { is_controlled_by = ROOT }
                    add_building_construction = {
                        type = infrastructure
                        level = 10
                        instant_build = yes
                    }
                }
            }
        }
    }
}
</code>
(It's from a game called "Hearts of Iron IV" and only a small part of the whole thing)
Could you guys give us a little help or a small hint to start up?
Thanks in advance,
Stuffi
Answer: That looks a lot like JSON, but with unquoted tokens instead of strings, equals signs (=) instead of colons (:), and no commas between properties. Why don't you check out the library SpracheJSON and see if you can modify it slightly to parse your file?


Similaridade musical a partir de padrões de descritores de MPEG-7

Question: Estou desenvolvendo pesquisas na área de similaridade musical para recomendação de músicas e criei uma base de dados para teste com 1.000 músicas. Gostaria de criar uma playlist com 10 músicas semelhantes a uma música escolhida entre essas mil, utilizando descritores MPEG-7.
Eu extrai 30 segundos de cada música para ter um padrão de características extraídas pelos descritores MPEG-7. Eu não gostaria de gerar classificações de sons em gêneros músicas, somente criar uma playlist pelo ritmo similar ao da música selecionada. Se uma música lenta for selecionada, essa playlist será de músicas lentas (as dez mais similares).
Tentei extrair alguns descritores como Audio Spectral Centroid, Audio Power, o que me deu um vetor. Porém, utilizando o cálculo da distância euclidiana no MATLAB, não consegui uma similaridade muito boa. Como posso construir esse prototipo utilizando os descritores MPEG-7?
Eu extraí um vetor de características para os descritores Audio Spectral Centroid e o Audio Power onde em ambos, para 30 segundos, ficou um vetor de 1000 posições, pois a extração de características do sinal de audio ocorre a cada 30ms. A duvida justamente é em saber se estou utilizando os descritores certos para esse tipo de trabalho.
<code><AudioDescriptor xsi:type="AudioSpectrumCentroidType">
    <SeriesOfScalar hopSize="PT30N1000F" totalNumOfSamples="1002">
        <Raw> 0.0 -1.6024935 -0.6072393 -0.7425593 -0.8901987 -1.1543454 -1.1027017 -0.64731646 -0.96495366 -1.022632 -0.8076392 -0.993545 -0.66203004 -0.93275607 -1.1654149 -0.9243456 -1.2580872 -1.339062 -1.5594536 -1.5959411 -1.7814989 -1.6296328 -1.5468938 -1.0133578 -1.250789 -1.0111073......</Raw>
    </SeriesOfScalar>
</AudioDescriptor>
</code>
Esse é uma das características extraídas, o Audio Spectrum Centroid, que indica o centro de gravidade da amplitude. Mas não sei ao certo qual descritor utilizar e como devo utilizar para isso.
Comment: É fato. O conceito é muito interessante. Mas o melhor é você mostrar seu código para *`Tentei extrair alguns descritores`* e *`utilizando o cálculo da distância euclidiana`*.
Comment: Por favor, edite a pergunta para incluir essas informações.
Comment: Eu não conheço muito do domínio de processamento de áudio, e por isso não me arrisco a escrever uma resposta. Mas, não me parece que a distância Euclidiana seja apropriada para características como as que você citou. Você já tentou utilizar o produto escalar normalizado (também chamado de [similaridade cosseno](http://en.wikipedia.org/wiki/Cosine_similarity)) para medir a similaridade entre seus vetores? Aqui tem uma sugestão de cálculo no Matlab: http://stackoverflow.com/a/14340447/2896619
Comment: Opa, por nada. Sobre os descritores, eu imagino que também se utilize a Transformada Rápida de Fourier e/ou Autovetores. Esse link da Wikipedia pode lhe ser útil: http://en.wikipedia.org/wiki/Musical_similarity
Comment: Onde está sua dúvida sobre programação ??
Comment: Olá. A sua pergunta é interessante e a pertiência dela ao escopo do site [está em discussão aqui](http://meta.pt.stackoverflow.com/a/275/73)).
Comment: Olá Luiz, irei dar uma estudada a respeito sim...muito obrigado. A duvida também é quais os descritores usar para esse tipo de projeto
Comment: Eu sugeriria tentar fazer uma redução de dimensionalidade (usando PCA) antes de calcular a distância. Talvez consiga alguma melhora. Isso se os descritores forem bons, claro.
Answer: O assunto é complexo e não é fácil responder sem entrar em alguns detalhes. Vou tentar de uma maneira simples abordar os pontos levantados pela pergunta, vamos lá:
Algo de extrema relevância ao se comparar ritmos é conhecer quantas batidas por minuto um áudio possui, claro que para efetuar este tipo de análise você vai precisar de uma janela maior, 30 milissegundos é insuficiente para mensurar batidas por minuto (bpm). Isso é de grande ajuda para conhecer se um determinado áudio possui um estilo lento ou mais agitado, mas só esta informação ainda não é o suficiente para conseguir bons resultados. Uma boa lista de descritores no domínio do tempo/frequência seria:
Descritores no domínio do tempo:

RMS (Root Mean Square) - faz análise da energia em um sinal de áudio, pode ser útil para determinar se o áudio analisado possui grande intensidade ou não.
Zero Crossing Rate - faz análise para saber quantas vezes um sinal de áudio cruzou o eixo x, possui uma analogia na variação do áudio.
Low Energy Rate - faz uma análise da porcentagem(quantidade) dos
frames capturados que estão abaixo da média do RMS, com isso você
saberá a porcentagem dos frames que possui menos energia do que a
média. Consequentemente, dá para saber se o áudio analisado está na maioria
das vezes com intensidade maior ou não.

Descritores no domínio do Espectro:

Spectral Entropy - calcula a entropia de um sinal de áudio, a
entropia nada mais é do que a medida do desarranjo em determinado
sistema. Deixe-me exemplificar, imagine que você possui dentro de
uma caixa de sapato uma coleção de carrinhos e todos eles estão
organizados (enfileirados) por cor, imagine agora que você tire um
pouco fora de ordem isso (desarrume), neste momento você terá uma
medida de entropia. Imagine agora que você pegue a caixa e balance
forte, todos os carrinhos vão estar em desordem total caracterizando outra medida de entropia. Este tipo de característica deve ser útil na verificação de quão organizado um determinado sinal
de áudio é.
Spectral Flux - faz a medida do fluxo dos espectros. Lembrando que
análise de sinais de áudio as análises são feitas dentro de
Janelas (blocos), o Spectral Flux é calculado bloco a bloco, o bloco
atual é subtraído do bloco anterior e os seus resultados são
indicativos da quão rápido é a variação do sinal.
Spectral Irregularity - faz a medida da irregularidade do sinal, ele
funciona parecido com o Spectral Flux, esta função vai produzir um
serrilhado, dentação nos resultados. Ele calcula a diferença dentro
do bloco capturado e não bloco a bloco como é feito no Spectral Flux.
Spectral Centroid - possui relação com o brilho do sinal, calcula a
energia relativa entre a maior e menor frequência. Isto dá pistas no
brilho do sinal.
Spectral RollOff - Rolloff espectral é definido como a quantidade de
vezes (frequência) em que a energia do espectro está abaixo de um
determinado ponto. Tem indicações de uma onda assimétrica à direita.
Spectral Skewness - calcula o grau de assimetria de um sinal de
áudio, este descritor vai retorna valores de quão assimétrico um
determinado frame é. Certamente este tipo de informação dá
cateterísticas timbrais na forma de onda analisada.
Spectral Kurtosis  - o Spectral Skewness calcula a assimetria do
sinal e o Kurtosis calcula o grau de achatamento de uma onda.
MFCC (Mel-frequency cepstrum) - coleta informações essenciais (coeficientes) que ajudam reconhecer padrões.

Agora que você sabe o que cada descritor faz, monte um vetor para cada bloco de análise, neste caso teremos:

Os treze primeiros são os resultados dos coeficientes do MFCC
O 14º valor é o mean da Centroid
O 15º valor é o standard deviation(std) da Centroid
16º mean Irregularity
17º std(standard deviation) Irregularity
18º mean Entropy
19º std Entropy
20º mean Flux
21º std Flux
22º mean Kurtosis
23º std Kurtosis
24º mean Rolloff
25º std Rolloff
26º mean Skewness
27º std Skewness
28º mean RMS(Root Mean square)
29º std RMS(Root Mean square)
30º mean ZCR(Zero Crossing Rate)
31º std ZCR(Zero Crossing Rate)
32º LER(Low Energy Rate)

Depois do 32º ainda falta mais 5 descritores que são os rítmicos pegos pelo Beat Histogram (histograma da batida) ou seja no total você vai ter um vetor com 37 posições cada um deles descrevendo algo!
Para não estender muito, tente outros algoritmos de "procura por similaridade", além da distância euclidiana tente KNN, LSH, DP ou Redes Neurais (Random Forests, MLP).
Comment: Classe magistral, muchas gracias!


Formula for testing for equivalence for binary paired data

Question: I am trying compute p-values for an equivalence test of paired, binary data (coming from two different tests, without known ground truth).
I followed the paper of Liu et al (DOI: 10.1002/sim.1012) and also the formula given in the PASS manual (Chapter 165, Equivalence Tests for the Difference Between Two Correlated Proportions) and implemented the computation of the asymptotic Wald-type test, based on samples (not RMLE), which is explained in detail in section 2.2 of Liu.
The function is like this:
getPvalue = function (x01, x10, n, delta = 0.1) {
    p01 = x01/n
    p10 = x10/n
    c = x10 - x01
    d = x01 + x10
    theta = p10 - p01
    theta2 = theta*theta
    Zl = (c + n*delta)/sqrt(d - n*theta2)
    Zu = (c - n*delta)/sqrt(d - n*theta2)
    message ("Zl ", Zl, "  Zu ", Zu)

    # tail probability is the pvalue
    pvalue_l = 1 - pnorm(Zl)
    pvalue_u =  pnorm(Zu)
    return (c(pvalue_l, pvalue_u))
}

To reproduce the example from Liu, Table VII, i have to call
x10 = 5
x01 = 4
n = 37+5+4+4

getPvalue (x01, x10, n, delta = 0.10)

Unfortunately, the output is different:
> getPvalue (x01, x10, n, delta = 0.10)

Zl 2.002225932798  Zu -1.334817288532
0.0226302189005887 0.0909680768336303

but, if i subtract 0.01 from delta, i get the correct output:
> getPvalue (x01, x10, n, delta = 0.10-0.01)

Zl 1.8353737717315  Zu -1.1679651274655
0.033225163588974 0.121410415838873

Now this is also true for the other example given, the same numbers, with delta = 0.15-- if i plug in 0.15-0.01=0.14 i get the correct numbers.
getPvalue (x01, x10, n, delta = 0.15-0.01)

Zl 2.669634577064  Zu -2.002225932798
0.00379669184108278 0.0226302189005886

So i am puzzled, am i doing something wrong or didn't just get how delta is defined?
I also searched for a R package that can compute exactly this statistics, but was not able to find one. If one can give me a hint, that would be better than my own coding...
Answer: Sorry that my answer comes 3 years (exactly!) late. I guess you have probably figured it out yourself years ago, but this answer might help others puzzled by the same inconsistency.
Note that the sample size in this numerical example is rather small (n=50), so that the continuity correction should be applied as default when generating table VII. Therefore the calculation for Zl and Zu would be slightly different. The updated formulae were shown at the end of section 2 in Liu's paper:
Zl = (c + n*delta-0.5)/sqrt(d - n*theta2)
Zu = (c - n*delta+0.5)/sqrt(d - n*theta2)

The reason that your trick of a 0.01 offset works is more like a coincidence: n=50 in this example so that n*0.01 happens to be equivalent to 0.5 in the code above.
Once you replace the Zl and Zu calculations in the function getPvalue(), you should be getting the same results as in table VII:
> getPvalue(x01, x10, n, delta = 0.15)
Zl 2.669634577064  Zu -2.002225932798
[1] 0.003796692 0.022630219

> getPvalue(x01, x10, n, delta = 0.1)
Zl 1.8353737717315  Zu -1.1679651274655
[1] 0.03322516 0.12141042

Comment: unbelievable, thank you. i didn't pursue the issue further because the difference wasn't very big and i checked the numbers with another software. in the end, these are sample calculations for medical purposes, so i could have just rolled some dice to get the numbers. anyway, absolutely great that you found the error and answered!


WPF MaterialDesignFilledComboBox - Center HintText vertically

Question: I have this ComboBox using the MaterialDesignFilledComboBox style.
<ComboBox ItemsSource="{Binding SomeData}"
          Style="{StaticResource MaterialDesignFilledComboBox}"
          materialDesign:HintAssist.Hint="Some hint text"
</ComboBox>

Notice the assignment of the materialDesign:HintAssist.Hint="Some hint text" property.
When I have not chosen an item in the ComboBox's drop-down-menu, the Hint property ("Some hint text") is the only visible text in the ComboBox. That is fine.
Above the Hint, there is an "unused space".
If I select an item in the drop-down-menu, the "unused space" is occupied by the Hint and showing the "Some hint text".
Question
My designer dislike the "above space" when there is no item selected in the drop-down-menu.
Is it possible to center the Hint vertically in the ComboBox when there is no item selected?
My findings
Looking into the MaterialDesignFilledComboBox's template (MaterialDesignFloatingHintComboBoxTemplate).
I found the SmartHint control at rows 374 - 397. This control seem to be the placeholder for the Hint.
If I add this style as a resource to the ComboBox, I have some limitied control of the SmartHint object in my ComboBox.
For instance:
<ComboBox ItemsSource="{Binding SomeData}"
          Style="{StaticResource MaterialDesignFilledComboBox}"
          materialDesign:HintAssist.Hint="Some hint text"
    <ComboBox.Resources>

    <ComboBox.Resources>
</ComboBox>

The setter with the Visibility = Collapsed actually works.
The setters of the VerticalAlignment and the VerticalContentAlignment properties don't work. Even if they would work, they would not given me the exact result I want, but prove that I can control the position of the control in some way.
Any suggestions?
/BR
Steffe
Answer: Try to set the HintAssist.IsFloating attached property of the ComboBox to false:
<ComboBox ItemsSource="{Binding SomeData}"
          Style="{StaticResource MaterialDesignFilledComboBox}"
          materialDesign:HintAssist.IsFloating="False"
          materialDesign:HintAssist.Hint="Some hint text" />

You could set it conditionally depending on whether an item is selected using a Style:
<ComboBox ItemsSource="{Binding SomeData}" materialDesign:HintAssist.Hint="Some hint text">
    <ComboBox.Style>

        </Style>
    </ComboBox.Style>
</ComboBox>

Thanks to @mm8 I found a way to partially solve this problem...But there is a problem with the graphics of the ComboBox
When I select the first item in the drop-down-menu, both the hint text and the text of the selected item, get all merged/mangled together into an unreadable mess.

That's a flaw of the third-party control.
You could work around it by handling the SelectionChanged and programmatically call the ApplyTemplate method of the SmartHint:
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox cmb = (ComboBox)sender;
    HintAssist.SetIsFloating(cmb, cmb.SelectedItem != null);
    SmartHint smartHint = FindVisualChild<SmartHint>(cmb);
    if (smartHint != null)
    {
        smartHint.ApplyTemplate();
    }
}

private static T FindVisualChild<T>(Visual visual) where T : Visual
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
    {
        Visual child = (Visual)VisualTreeHelper.GetChild(visual, i);
        if (child != null)
        {
            T correctlyTyped = child as T;
            if (correctlyTyped != null)
            {
                return correctlyTyped;
            }

            T descendent = FindVisualChild<T>(child);
            if (descendent != null)
            {
                return descendent;
            }
        }
    }

    return null;
}

XAML:
<ComboBox ItemsSource="{Binding SomeData}"
          SelectionChanged="OnSelectionChanged"
          Style="{StaticResource MaterialDesignFilledComboBox}"
          materialDesign:HintAssist.IsFloating="False"
          materialDesign:HintAssist.Hint="Some hint text" />

Comment: @mm6: Thank you!
It worked now :)
Comment: Thank you for the suggestion. That somewhat worked.
I have tried to set the IsFloating depending on the value of the SelectedItem property in the ComboBox. But that kinda worked. Please see my own answer of this topic.
Comment: @Mc_Topaz: Please see my edit for how to use a `Style` to set the property conditionally.
Comment: I tried you solution but I get the same problem of the Hint's text is merged with the SelectedItem's text :'(
Comment: That's a flaw of the third-party control I am afraid.
Comment: @Mc_Topaz: See my second edit for a solution.
Answer: Try changing the Padding property
<Setter Property="Padding" Value="0 -10 0 0" />

Comment: Thank for the suggestion.
But it didn't effect the Hint's position in any way.
Comment: This is strange. The hint changes the position in my case. Maybe you have VerticalAligment = Top. This may interfere with.


Testing robust regression model made from training set in R

Question: I have done a robust regression on my training-dataset and would now like to see whether the model fits the test-training set. However, I do not know how to do this. I have already made sure my test-set only contains the variables used in the model, that is the firs step I believe, but what is next?
Answer: If I understand your question correctly: the next step involves using the model you've generated to predict the outcomes of the test/validation dataset. This can be completed using the predict() function in R, where your first argument is your model H1.final.model and the second is the test/validation set.
This will output predictions of the data set based upon the coefficients you've established in your regression model. You can cross-reference these predicted outcomes against the defined outcomes of your test set in a number of different ways.


General Linear Model without the main effects

Question: In the post here, a contributor (dmk38) makes an interesting, and may I add a very commonsense observation, that to include or not to include the main effects in an interaction model containing the product term should be guided by theory and hypothesis that is being tested.
I have a similar situation where the product term (X1*X2) is significant. However, when I use X1, X2 and X1*X2 in the model, the latter becomes insignificant. I am using the general linear model in SPSS.
I am only interested in the significance of X1*X2 interaction and I can justify it based on my hypothesis that I am assessing the relationship between X1 and Y and how this relationship is moderated by X2. I already know that there is a strong correlation between X1 and Y (so there is little point of assessing the main effect of X1 on Y in the model.)
I am certainly not 'fishing around' for significance but just tried the two approaches above i.e. one with the main effects and one without the main effects. Both models contained the product term.
Question: Given the confusion in the above post, I am unsure if the above approach which leaves out the main effects is a valid approach (though it makes intuitive sense to a non-statistician like me!)
Comment: Have you read all the *other* answers to that post? Only extremely rarely, if ever, does it make sense to do this. That post has lots of good answers; it needn't be re-hashed.
This might even be a duplicate question.
Comment: @Adhesh, in the post you link to, I personally liked the answer by Galit Shmueli. You _may_ leave your model just with the interaction, without the main effects, but this will make your single predictor faceless: you cannot say that it is a _interaction_ anymore; it is merely some IV that was once computed as a product of some outside variables.
Answer: If the values of X1 and X2 are positive and positively correlated with Y, then of course X1*X2 will be significant when used alone in a model: it is positively correlated with both X1 and X2 and therefore should be correlated with Y.  But that tells us nothing.
Let's look at a small example using the following data:
<code>X1      X2      Y
14.041  13.6205 25.6893
17.1413 14.2088 32.3733
18.2874 16.1873 34.261
18.285  14.6539 31.8483
13.9504 13.6742 26.6726
17.0211 13.9576 31.6815
15.6146 17.4936 32.7113
14.4232 16.9606 30.4182
14.8142 15.5246 31.1612
15.4794 14.4887 31.1827
10.9243 16.1642 28.1331
14.8455 15.1099 29.4972
</code>
X1, X2, and X1*X2 (scaled down by 1/20 for easy plotting) are correlated with Y, but the product X1*X2 clearly is much more strongly correlated with Y than either of X1 or X2:

(Correlation is a useful way to describe these relationships because all three plots appear sufficiently linear and homoscedastic.)
Let's do some regression.

Y ~ X1*X2.  The p-value is 0.000072 and the mean square residual is 1.37.
Y ~ X1 + X2.  The p-values are .00041 and .00038, respectively.  The mean square residual is 1.33.  The individual p-values are not as low as in the preceding model (if you care about such things) and the mean square residual is only a tiny bit lower, despite using two variables instead of 1.
Y ~ X1 + X2 + X1*X2.  The p-values are .00033, .0028, and 0.129, respectively.  The interaction (X1*X2) is not significant.  (The mean square error has improved to 1.098, though.)

This perfectly conforms to the description of the problem: the significance of the interaction goes away when accompanied by X1 and X2 in the model.
What is going on?  I generated these data by drawing X1 and X2 independently from a Normal(15,2) distribution and then forming Y by adding Normal(0,1) error to X1 + X2.  In other words, apart from that error, Y depends linearly on X1 and X2; there is no interaction.
We can understand this geometrically: the plot of a surface of the form $Y = \alpha X_1 + \beta X_2$, for positive $\alpha, \beta, X_1, X_2$, is a plane; the plot of a surface of the form $Y = \gamma X_1 X_2$ ($\gamma$ positive) is a very flat hyperboloid of one sheet, assuming $X_1$ and $X_2$ stay away from $0$.  That hyperboloid can be a more than adequate approximation to the plane (first regression) which in turn might be a better model for $Y$.
As others have explained at length in the referenced thread, it is rare that you can interpret an interaction by itself (regression 1); you need to include it in the context of the linear terms (regression 3) or formulate a different model altogether (as described in my reply in the referenced thread).
Answer: The problem which arises is an issue of interpretation. Consider a simple linear regression model with a continuous main effect and continuous outcome. Suppose further you have a binary factor and you're interested in the model with interaction. When you adjust for the lower level terms, the interaction parameter has a meaningful definition: it is interpreted as the difference in slopes between regression lines between groups defined by the binary indicator.
When the lower level terms are dropped, there is no such interpretation. The quantity estimated has no physical meaning. It imposes the constraint that the two regression lines share the same intercept, but have different slopes. Putting such constraints on intercepts is ill-advised. As a parameter, the no-main-effects interaction term is strictly distinct from the orthodox parameter which has the main effects.
To answer your question, the X1:X2 terms in your two different model specifications are estimating two completely different parameters. It shouldn't be surprising to us that one is estimated to be significant and the other isn't, consequently.
Answer: I remember having read an very interesting article on this topic. I am very sorry not to be able to link it but the message was that interaction terms between two variables say $x_1$ and $x_2$ must have all three terms:
$y = \beta_0 +\beta_1x_1 + \beta_2x_2 + \beta_3x_1 \times x_2$
however, otherwise you may well run into omitted variable bias problems. In the meantime this may help you a bit: Understanding Interaction Models
Comment: Your linked article has the points you make, in section 3 "Include All Constitutive Terms."


.NET 4.0 dll loading 4.5

Question: Can an assembly that has been targeted for 4.0 load an assembly that was targeted for 4.5?
For example, a project targeting 3.5 cannot load assemblies that were built against 4.0.
Comment: Why is this a comment and not an answer?
Answer: 4.5 is an inplace update to 4.0. So yes.
An assembly built against Fx 4.0 can not reference an assembly built against Fx 4.5.
However
An assembly built against Fx 4.5 can reference an assembly built against Fx 4.0.
Answer: I think it's a bad idea since your .NET4 app will also run on the machine with .NET4 only (without .NET4.5 installed). In this case, your app may run into issues because it may be trying to .NET4.5 functionality but .NET4.5 is not present on the machine. I strongly recommend building .NET4.5 app instead.
Comment: Payo didn't say that the machine would not have 4.5 installed.
Comment: Unless app will have to run on Win XP, which is supported only up to .NET 4.0, in this case you have to compile every assembly against Framework 4.0

.NET 4.0 dll loading 4.5


Fazer textfield se movimentar ao adicionar itens no listview

Question: A minha dúvida é a seguinte: Ao colocar o id do colaborador e clicar em adicionar, entra na lista o id e nome do colaborador, como na foto:

Ao adicionar, o colaborador sobrepõe o textfield... To tentando fazer com que o text field fique sempre embaixo do ultimo item da lista.

É um listview simples e um textfield simples. Segue o código
ListView.builder(
   scrollDirection: Axis.vertical,
   shrinkWrap: true,
   itemCount: listaUsers.length,
   itemBuilder: (context, index) {
      return ListTile(
         dense: true,
         title: Row(
            children: <Widget>[
               Text(
                  listaUsers[index]
                  .id
                  .toString(),
                  style: TextStyle(color: Colors.black, fontSize: 13),
               ),
               Text(" - "),
               Text(
                  listaUsers[index].name,
                  style: TextStyle(color: Colors.black, fontSize: 13),
               ),
            ],
         ),
         onTap: () => _onTapped(user),
         trailing: IconButton(
            icon: Icon(Icons.remove),
            onPressed: () {},
         )
      );
   }),
   Padding(
      padding: EdgeInsets.only(left: 10),
      child: Container(
         padding: EdgeInsets.only(left: 15, right: 15),
         child: Row(children: <Widget>[
            Expanded(
               child: TextField(
                  controller: addColaborador,
                  decoration: InputDecoration(
                     hintText: "ID COLABORADOR",
                     contentPadding: EdgeInsets.only(bottom: 0),
                     labelStyle: TextStyle(color: Colors.blueAccent)
                  ),
               ),
            ),
            IconButton(
               icon: Icon(Icons.add),
               onPressed: () {
                  _buscarId();
               },
            )
         ]
      )
   )
)

Answer: Você poderia adicionar o TextField abaixo do ListView.builder dentro de uma Column, assim conforme for adicionando os itens no ListView, ele cresce e empurra o TextView para baixo.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  TextEditingController controller = TextEditingController();

  final List<String> list = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ListView'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: SingleChildScrollView(
          child: Column(
            children: [
              ListView.builder(
                  shrinkWrap: true,
                  itemCount: list.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text(list[index]),
                      trailing: IconButton(
                        icon: Icon(Icons.remove),
                        onPressed: () {
                          setState(() {
                            list.removeAt(index);
                          });
                        },
                      ),
                    );
                  }),
              Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: controller,
                      decoration: InputDecoration(
                        hintText: 'ID COLABORADOR',
                      ),
                    ),
                  ),
                  IconButton(
                      icon: Icon(Icons.add),
                      onPressed: () {
                        if (controller.text != null) {
                          setState(() {
                            list.add(controller.text);
                            controller.clear();
                          });
                        }
                      }),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Answer: Acredito ser simples, adicione o textfield sempre após o ultimo item.
Video
ListView(
    scrollDirection: Axis.vertical,
    shrinkWrap: true,
    children: List.generate(listaUsers.length, (index) {
      Widget child = ListTile(
          dense: true,
          title: Row(
            children: <Widget>[
              Text(
                listaUsers[index].id.toString(),
                style: TextStyle(color: Colors.black, fontSize: 13),
              ),
              Text(" - "),
              Text(
                listaUsers[index].name,
                style: TextStyle(color: Colors.black, fontSize: 13),
              ),
            ],
          ),
          onTap: () => _onTapped(user),
          trailing: IconButton(
            icon: Icon(Icons.remove),
            onPressed: () {},
          ));

      return child;
    }).toList()
      ..add(Padding(
          padding: EdgeInsets.only(left: 10),
          child: Container(
              padding: EdgeInsets.only(left: 15, right: 15),
              child: Row(children: <Widget>[
                Expanded(
                  child: TextField(
                    controller: addColaborador,
                    decoration: InputDecoration(
                        hintText: "ID COLABORADOR",
                        contentPadding: EdgeInsets.only(bottom: 0),
                        labelStyle: TextStyle(color: Colors.blueAccent)),
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.add),
                  onPressed: () {
                    _buscarId();
                  },
                )
              ])))))


Multi-row latex table with R

Question: I have this data frame :
mydf <- data.frame(rowFactor1 = c(rep("S4",6),rep("S5",6),rep("S6",6)),
                   rowFactor2 = rep(c("All","T1/T2(V)"), 9),
                   colFactor1 = rep(c(rep("Ml",2),rep("Mp",2),rep("Mra",2)), 3),
                   x = c(
                     "8.73",
                     "0.46 / 8.28 ( 2 )",
                     "7.02",
                     "0.84 / 8.28 ( 3 )",
                     "0.55",
                     "0.90 / 1.20 ( 0 )",
                     "8.14",
                     "2.02 / 1.57 ( 5 )",
                     "0.55",
                     "2.90 / 1.28 ( 4 )",
                     "1.73",
                     "3.46 / 8.28 ( 6 )",
                     "6.02",
                     "0.87 / 8.90 ( 5 )",
                     "1.55",
                     "0.90 / 1.20 ( 1 )",
                     "6.24",
                     "2.02 / 1.57 ( 7 )"
                   ))

How to create a Latex table with multiple rows using mydf on R?
I tried to use the tabular function of the R package tables
tab1 <- tabular(Heading()*RowFactor(rowFactor1, spacing = 1,
                                    c("S4","S5","S6"))*
                  Heading()*RowFactor(rowFactor2,
                                      levelnames = c("All","T1/T2(V)")) ~
                  Heading()*Factor(colFactor1,
                                   levelnames = c("Ml","Mp","Mra")),
                data = mydf)
latex(tab1)

I had this table without x's values (8.73, 0.46 / 8.28 ( 2 ) ...) and filled with a single value 1.

Thanks for your help !
Comment: I think you are looking for `library (tidyr) mydf %>%
 spread(colFactor1, x)`
Comment: @tmfmnk thank you for your suggestion but I need a Latex table using R.
Comment: @FloraGrappelli Please don't edit post to add thank you lines. Please read https://meta.stackoverflow.com/a/328380/2777074
Answer: If you wish to use strings in the table, maybe convert your x factor to character:
mydf$x <- as.character(mydf$x)

Then include the x strings as follows:
library(tables)

tab1 <- tabular(Heading()*RowFactor(rowFactor1, spacing = 1,
                                    c("S4","S5","S6"))*
                  Heading()*RowFactor(rowFactor2,
                                      levelnames = c("All","T1/T2(V)")) ~
                  Heading()*Factor(colFactor1,
                                   levelnames = c("Ml","Mp","Mra"))*
                  Heading()*(x)*Heading()*identity,
                  data = mydf)
latex(tab1)

Also consider alternatives to tabular for Latex tables:
Tools for making latex tables in R

Multi-row latex table with R


Scraping unique links from website with Python only retrieving 1 link

Question: I'm trying to scrape only unique urls from a website and write them to a file as absolute links.
WHen I initially scrape the site, I retrieve 253 links. However, when I use set() to retrieve only unique links and use code to turn them into absolute links, it only returns 1 url. I played around with it and removed the function unique_urls thinking that could be causing it, but it did the same thing. I'm new to Python and still grasping loops, so it could easily be something I've overlooked. Any ideas? Thank you.
import bs4
import requests
from bs4 import BeautifulSoup, SoupStrainer
import csv

url = "https://www.census.gov/programs-surveys/popest.html"
r = requests.get(url)
raw_html = r.text
soup = BeautifulSoup(raw_html, 'html.parser')
results = soup.find_all("a")

print ('Number of links retrieved: ', len (results))

def unique_urls(tags,url):
    cleaned_urls = str(link.get("href"))

for link in results:
    link = link.get("href")
    if link.startswith('/'):
        cleaned_urls.add('https://www.census.gov' + hrefs)
    elif link.startswith('#'):
        cleaned_urls.add(hrefs)
    else:
        unique_urls.add(cleaned_urls)

print ('Number of links retrieved: ', len )

Comment: Before adding the `set()` you got 253 links, afterwards it returned only 1, and when you removed the `set()` to go back to what you first had, there was still only 1 result? Am I understanding that correctly? Can you provide a [mcve]?
Comment: No, sorry. When I removed the unique_urls function. Someone I know suggested I try it without the function, but I still used the set method. Not sure if that makes sense. When I get home, I can post an example. Thank you.
Comment: I don't understand the `unique_urls()` function, it takes two parameters which are unused, yet does use a variable which seemingly isn't defined anywhere. Neither of the functions here seem to return anything, it's probably best to refactor your code to take and return values, rather than messing with global variables.
Comment: Also, how do you define which links you're interested in?
Answer: use below code for unique urls
import bs4
import requests
from bs4 import BeautifulSoup, SoupStrainer
import csv
import re

url = "https://www.census.gov/programs-surveys/popest.html"
r = requests.get(url)
raw_html = r.text
soup = BeautifulSoup(raw_html, 'html.parser')
results = soup.find_all("a")

print('Number of links retrieved: ', len(results))

list_urls = []
for link in results:
    link = link.get("href")
    if link is None or link == "#content":
        pass
    else:
        if re.match(r"https://", link):
            list_urls.append(link)
print("******* total urls*********")
print("total count of urls: ", len(list_urls))
print("*********** after unique*****")
unique_urls = set(list_urls)
print("length of unique urls:", len(set(list_urls)))

Comment: I went through the csv file and I think I should be getting 122 links, but only 92 are showing up.
Answer: Is this what you require ?. I actually get only 92 valid and unique URL.
import bs4
import requests
from bs4 import BeautifulSoup, SoupStrainer
import csv
from functools import partial
from operator import is_not

import re

filter_null = partial(filter, partial(is_not, None))

checklink = []

url = "https://www.census.gov/programs-surveys/popest.html"
r = requests.get(url)
raw_html = r.text
soup = BeautifulSoup(raw_html, 'html.parser')
results = soup.find_all("a")

print ('Number of links retrieved: ', len (results))

for result in results:

    checklink.append(result.get('href'))
    L =list(filter_null(checklink))

    regex = re.compile(r'http')

    selected_files = list(filter(regex.match, L))
distinctTitle  = (list(set(selected_files)))

#def unique_urls(tags,url):
#    cleaned_urls = str(link.get("href"))
#
#for link in results:
#    link = link.get("href")
#    if link.startswith('/'):
#        cleaned_urls.add('https://www.census.gov' + hrefs)
#    elif link.startswith('#'):
#        cleaned_urls.add(hrefs)
#    else:
#        unique_urls.add(cleaned_urls)

print ('Number of Unique and cleaned links retrieved: ', len(distinctTitle))

Comment: I wrote a solution myself, and found 122 links. Can you share the result you get?