Intuition and derivation of the geometric mean

Question: I've run through a bunch of searches, especially here on SO, but I simply couldn't find something that answers a question that has been on my mind lately. How was the geometric mean derived? What is the intuition behind it. Most simply use the final equation as a justification for its existence.
The $n$-th root of the product of all elements equation really doesn't do it justice.
Could someone elaborate on how and why is it interesting?
Comment: It is sounds terrible to ask how the concept was *derived*. Terminology aside, suppose you make a\$500 investment over $n$ years with annual growth rates of $a_1\%$, $a_2\%,\dots,a_n\%$. This is the same as a constant growth rate per year, over $n$ years, of what percent? You need to solve $(1+a_1/100)(1+a_2/100)\cdots(1+a_n/100) = (1+r/100)^n$, so $1+r/100$ is the geometric mean of $1+a_1/100, 1+a_2/100,\dots,1+a_n/100$. (The initial investment could have been *anything* and the answer for $r$ would come out the same; the use of 500 as the principal doesn't affect the choice for $r$.)
Comment: What's wrong with the *geometric* definition of the geometric mean? A *rectangle* with side lengths $a$, $b$ has the same area as the *square* of side length $\sqrt{ab}$; a *shoebox* with side lengths $a$, $b$, $c$ has the same volume as the *cube* with side length $\sqrt[3]{abc}$; likewise for higher dimensions. In general, a mean is simply a *single* value that can replace each member of a list of values yet achieve the same result. Just as the arithmetic mean of values preserves their sum, the geometric mean of values preserves their product. (The harmonic mean ... well ... look it up.)
Comment: For example, if your initial investment had growth rates over 3 years of 10\%, 20\%, and -30\%, this does *not* mean you come out even; in fact you end up with a net loss. The arithmetic-geometric mean inequality shows that if your investment grows over $n$ years at rates of $a_1\%, a_2\%, \dots,a_n\%$ and $a_1 + a_2 + \cdots + a_n = 0$, you will wind up with *less* than the  principal unless every $a_i$ is $0$. This is a concrete application of the arithmetic-geometric mean inequality where the result to many seems counterintuitive at first (being misled by sum of growth rates being $0$).
Comment: The phrase "why it works" doesn't make sense. Do you mean "why is it interesting"?
Comment: @KCd Yes, that is acceptable. I just wish some intuition about it, how it was derived etc.
Comment: By the way, if you have a principal that increases by $a\%$ and then decreases by $a\%$, the reason for an overall net loss is a simple fact of algebra: $(1+x)(1-x) = 1-x^2$. Specifically, the value of your investment will be multiplied by $(1+a/100)(1- a/100)$, which is $1 - (a/100)^2 < 1$, hence an overall loss. This much can be done without saying anything about geometric means.
Answer: Took some time to condense this answer and, in the process, make it more readable.
If I may join on the festivities, here are my two cents!
It seems to me that you have an issue with the general formalization of mathematical concepts/constructs and the expected intuition behind them (inferrred from KCd's comment). You're not the only one, this is generated by lousy school systems which portray many mathematical concepts like they were pulled out of someone's behind. And this bugs people, some turn to malicious attempts of disproving mathematics ( to a point of bitter hate) and some invest the time to investigate the backdrop and find out whether that's truly the case.
It most certainly is not. Let me address the problem in logical chunks relating to your questions. To understand the geometric mean, let us make sure you understand the arithmetic mean.
The Arithmetic Mean
Let's take a step back and take a look at the arithmetic mean, from which you should be able to understand the need for multiple means and how they can be formulated:
$$A = \frac{1}{k}\sum_{i=1}^{k}x_i$$
It is astonishing how many people use this, without having the slightest idea of what it is. Of what it represents. You often hear "Add all the elements together and divide by the number of elements - that's the average."
Ask that person what is this average, where does this relationship stem from - you'll probably get a wall of silence - or even worse - more explanations which use the thing they're actually trying to explain.
So, let's explore this organically, which means our logic will drive us into the wall before reaching the correct answer. Say we have an array of a few rather random (accidentally odd) numbers:
$$R = [3, 5, 11]$$
They could be anything. Money, unit-less values, grades in school - irrelevant. Now, the problem:
How do we find out a number $n$ which relates to all inputs as close as possible?
What does it mean to lie as close as possible? It means that the absolute difference between the input and a supposed value $n$ is as low as possible. Let's formalize such a statement by trying to estimate how $n=6$ relates to all of our values:
$$\Delta x_1 = | 3 - 6 |= 3 $$
$$\Delta x_2 = | 5 - 6 |= 1 $$
$$\Delta x_3 = | 11 - 6 |= 5 $$
$$\Delta[3,1,5]$$
Now, we can see the how far $n$ is from every input. We want minimal numbers here, as small as the inputs permit (because they modulate the final output). We could spend all day searching for the smallest possible $\Delta$-difference array which is given as a function of $n$, or we could do something clever. We want the a number whose distance from every input is as small as possible. Well, we could add up all the differences:
$$ d(n) = \sum_{i=1}^{k}( | x_i - n | )$$
Where $k$ is the number of inputs. In the previous example, that gives us a total "miss of $d(6) = 9$. We want $d(n)$ to be as small as possible which simply means to be maximally close to all of the inputs.
You could track the possible solution as the lowest point which the function $d(n)$ reaches, but as the function is both linear and limited to positive values means it doesn't have a continuous derivative at the point of reflection, which is exactly the point we're looking for.
Well, the only reason we used absolute values was to denote that we desire positive values, because negative distances don't make sense. What else can give us positive values, preserve order and relieve our problem of a non-continuous first derivative? Raise the equations to the power of $2$!
$$ d(n) = \sum_{i=1}^{k}(x_i - n )^2$$
Well, that was quick. What have we gained? We now have our distances squared and summed, but positive. And guess what, we now have a unique peak value:
$$\frac{d}{dn}d(n) = 0$$
So, let's first expand our $d(n)$ before deriving and extrapolating the $n$ at $d'(n) = 0$, here are the steps:
$$ d(n) = kn^2 - 2n\sum_{i=1}^{k}(x_i) + \sum_{i=1}^{k}(x_i^2) $$
Differentiating:
$$ \frac{d}{dn}d(n) = 2kn - 2\sum_{i=1}^{k}(x_i) $$
And the winner is:
$$ 2kn - 2\sum_{i=1}^{k}(x_i) = 0 $$
$$ n = \frac{2\sum_{i=1}^{k}(x_i)}{2k} $$
$$ n = \frac{\sum_{i=1}^{k}(x_i)}{k} $$
$$ n = \frac{1}{k}\sum_{i=1}^{k}(x_i) = A $$
Could it be? Oh, yes. That's the elusive, proper definition of an arithmetic mean. Nobody woke up one day and simply wrote out the final equation. It was an important issue to resolve, to find what is the value around which all inputs tend to be accumulating.
And that's the whole point of it, when you try to reduce the sum of accumulated distances by respecting all the inputs included, you will find that the value drops around the most populated areas of the number line. Also, when you have only two values, that's simply resolves down to the middle between two points on the numberline. The more inputs you have, the more precisely can you define the central tendency.
The Geometric Mean
We have greatly covered some of the background concerning the arithmetic mean which answers the question we posed as: "What single number best describes a set of numbers, a number which therefore lies as close as possible to all inputs?"
We interpreted it as the least squared sum of the errors (geometrically, a point on a number line which is as the bare minimum distance from all inputs, naturally moving to the highest concentration of inputs). The derived expression is as follows (from the previous discussion):
$$A = \frac{1}{k}\sum_{i=1}^{k}x_i$$
Verbosely, it adds up all the elements and divides by the number of elements. You have a total sum of all the inputs and you divide it in $k$ equal parts. The number that you get from the former definition is one which when added to itself $k$ times gives the original sum (which is simply inferred by the definition of basic arithmetic operations).
So basically, it replaces the varying elements with a constant term which preserves the sum. And this is the average by the very definition of the concept. If every day is the same, it's considered average. If every day is legendary then every day is, again, average, there is no oscillation. It's the same.
And this is facilitated simply by having a total sum of all the inputs and dividing that sum in $k$ equal parts. This is also why when you take the average between two points, it's the middle point. The total length is divided into two equal parts, defining a point on the number line directly inbetween separating the two partitions.
So, in simplest terms, arithmetic mean replaces all the inputs with one constant and requires it to add up to the original total sum. In contrast, geometric mean answers the question: "If all inputs were, again, the same value, what would be that value to multiply up to the original product." It is expressed as:
$$G = \sqrt[n]{\prod_{i=1}^{n}x_i} = (\prod_{i=1}^{n}x_i)^{\frac{1}{n}} $$
Looks wild? It's just simple algebra which drives a simple concept, as I hope you'll see further below.
I hope everyone now sees why I emphasized on understanding the arithmetic mean first, since the concepts are related in terms of goals, providing an average value which needs to be employed in the calculation that must satisfy some properties which are specific to its problem.
So, what is the problem of the geometric mean? Relative values. When each of the inputs or elements of the set is defined in terms of the previous. That is at the heart of percentages, stating how much of the total you have.
The percentage, $\%$ - that's a unit. It's defined as:
$$\% = \frac{1}{100}$$
$\%$ is a hundreth. Standing alone it means you've got one hundredth of the base unit $1$. Doesn't make much sense on it's own. It needs to be defined in terms of a definite initial value. Then you can say that you've got $20\%$ of it, which amounts to $20/100$ or $2/10$ or $1/5$ of the total value.
Imagine now a problem that involves relative growth, which is quite common. In the first year, you gain 30%, second - 40%, third - 50%. The naive approach would be to calculate the arithmetic mean to return the average change over the 3 years - returning a value of $40\%$.
But here you're making an assumption that for each year you use the original total multiplied by respectively $1.3$, $1.4$, $1.5$. Let's assume that the initial value is $v_0$:
$$\frac{1.3v_0 + 1.4v_0 + 1.5v_0}{3} = A$$
You see how the actual value is the same for all elements? What actually happens is this ($v_0$ is constant, we can factor it out):
$$v_0\frac{1.3 + 1.4+ 1.5}{3} = 1.4v = v_0 + 0.4v_0 $$
And this simply isn't right. Since we've expressed our values in terms of percentages of the initial value, the elements are dependent on one another, after the first year, the $v$ is no longer $v_o$. And this breaks down.
We need to understand the motivation for the geometric mean, like we did with the arithmetic mean. When considering the geometric mean, most get fooled by its name. To someone new to the concept, such a term might be intimidating.
So, we've talked about relative growth, expressing values as percentages which depend upon an undisclosed value (when evaluating the geometric term, we are agnostic of the value because we don't need to know it). If they indeed depend on one another and must be expressed in terms of the previous, we can express it as a product whose very definition lends itself to the problem:
$$v_0*1.3*1.4*1.5 = v_0x^n$$
We are, essentially looking for a value which, when multiplied by itself $3$ times (the number of percentages per respective years), gives the same final value as if we simply repeatedly multiplied each year with the respective $1.3$, $1.4$ and $1.5$. Now, since we don't care about the $v_0$ and we are trying to express the values in relative notions of percentages, we can just get rid of it:
$$1.3*1.4*1.5 = x^3$$
Let's be even more explicit:
$$1.3*1.4*1.5 = x*x*x$$
I hope this drives the notion home. One, average $x$ that does the same job as every other element on the left side. Now, we've defined the concept of a root as the number which when multiplied by itself $n$ times gives the value of which we're taking the root in the first place. So, take the $n$-th root of both sides, where in this case $n=3$:
$$\sqrt[3]{1.3 * 1.4 * 1.5} = \sqrt[3]{x^3}$$
What is the number which multiplied by itself three times gives $x^3$? Well, that's $x$, right? And that gives the following expression:
$$x = \sqrt[3]{1.3 * 1.4 * 1.5} = ~1.3976$$
That totals down to an average growth $39.76\%$ over the period of three years. See how it is just a little bit smaller than the arithmetic mean? That's actually quite a useful property called the arithmetic-geometric inequality which states that it is either less or equal to the arithmetic mean. The actual differences can be quite drastic, especially when dealing with ratios, relative values, growth etc.
And this simply generalizes to the first expression:
$$G = \sqrt[n]{x_1x_2 \ldots x_n}= \sqrt[n]{\prod_{i=1}^{n}x_i}$$
As the arithmetic mean protects the total sum, the geometric mean protects the total product (and solves our problem of dependent values). We mentioned that the arithmetic mean can be visualized as something that divides a number line in $n$ equal parts, which when added together give the original total.
EQUAL, you say?
Indeed. You could imagine having four sides of a rectangle (that means that the two values are the same). If you add them up, that is the perimeter of the rectangle. Now, divide it in four equal $a$ parts. Woah, what's that? Add them together to make sure we have the sum:
$$a + a + a + a = 4a = S$$
That seems awfully like the circumference of a square. And that's exactly what it is. It has the same circumference as the rectangle, but just one value is needed to describe the same thing.
Now, onto the geometric mean. If you had, as Day Late Don described, a rectangle with sides $a$ and $b$, their product is the area (as per agreement when the multiplication was defined, that's the geometric interpretation). So, which number when multiplied by itself $n = 2$ times gives the same area as the rectangle $ab$? That's right, $G = \sqrt{ab}$.
Do you see what we have here? G is the side of a square which when multiplied with itself gives the same area as the more complicated product of two different values. We have found a central value that does the job of all other values. As the arithmetic mean preserves the imaginary circumference, the geometric mean preserves the imaginary area. Respectively, that's protecting the sum. And protecting the area.
Amazing, huh? By trying to figure out a completely different problem without even contemplating the applications within geometry, we have acquired a new useful tool should we ever need it in our investigations.
Mr. Ayman Hourieh has answered the correspondence between the arithmetic mean and the geometric mean when we try to log both sides. The product reduces to a sum because of the nature of logarithms ($\log{(ab)} = \log{a} + \log{b}$. Should any questions arise, again, don't hesitate to ask.
Comment: Sir, you just made my day. Great answer.
Comment: This is amazing! My head thanks you, the weird feeling of irritation is gone. Answering so much and still leaving traces to follow. I'd give you a thumbs up, but all I can is mark it as an answer. Which it truly is. Everyone has been so helpful, thanks all!
Comment: How does this address the question at all? There is a long discussion on the arithmetic mean, but when it comes to the geometric mean nothing is said.
Comment: Domagoj, you've outdone yourself... wow.
Comment: Wow, that's quite a bit of text! I love the approach to deriving the arithmetic mean, is that the way it was originally defined? A lot of useful info!
Comment: @Fractal: that's basically the concept of *regression/least squares*. Here it is applied to the problem "what is the one number that 'best' approximates this bunch of numbers", for some mathematically precise definition of "best" (in this case the least squares criterion).
Comment: Of course, when Gauss took the least squares route, he made assumptions like the errors in the data having a normal distribution, but that looks to be a tale for another time...
Comment: Many thanks, J.M.! I'll try to find out more.
Comment: @KCd There, hopefully the extension satisfies the question more profoundly.
Comment: Interestingly, if you *do* use the absolute value approach to find the most representative number, what you get is the median.
Comment: i really like this explanation it really is the personification of an intuitive explanation something which a lot of people cant do , I liked this "As the arithmetic mean protects the total sum, the geometric mean protects the total product" part , however for ur explanation of the arithmetic mean you highlighted the distance point (deviations) and a number which all the input are as close as possible to and this really helps visualize the whole "measure of central tendency" aspect, is there a similar explanation for geometric mean to show the aspect of central tendency with distance etc?
Answer: Here is one motivation for the geometric mean: By taking the logarithm of both sides of the geometric mean definition, you'll find that the logarithm of the geometric mean is the mean of logarithms of values:
\begin{align*}
G &= \left(\prod_{i=1}^{n}a_{i}\right)^\frac{1}{n} \\
\Rightarrow \log{G} &= \frac{1}{n}\sum_{i=1}^{n}\log{a_{i}}
\end{align*}
When the numerical ranges of values are too large, you may want to use logarithms of values, and hence the geometric mean.
For example, let's say you're studying a value that grows exponentially over time (like human population, compound interest, etc). The geometric mean makes more sense when studying this value, as illustrated by this example in Wikipedia.
As for why the geometric mean works better for values that grow exponentially: When a value grows exponentially, its logarithm grows linearly. Therefore, linear approximation via the geometric mean works, because it's based on the logarithms of values.
Comment: What's an example where you'd want to do this (i.e., use logarithms of values simply because the numerical range is too large)?
Comment: @KCd Please see the update in my answer and the link to an example in Wikipedia.
Comment: Question, why does the arithmetic mean over-state the growth in comparison to the geometric mean?
Comment: @Rebuq See my latest addition to the answer.
Comment: And as a point of interest, there are at least two other means which are $f^{-1}(\textrm{arithmetic mean}(f(x_i)))$, namely the harmonic mean ($f(x) = x^{-1}$) and the RMS ($f(x) = x^2$).
Comment: @Rebuq: The reason the arithmetic mean overstates the growth is the arithmetic-geometric mean inequality. Look up this inequality!
Answer: Essentially, the arithmetic mean is the mean according to addition, and the geometric mean is the mean according to multiplication. What I mean by this is that, if we have some numbers $a_1,a_2,\ldots,a_n$ and we are interested in only addition, then we might seek to find some number $\mu$ such that
$$a_1+a_2+\ldots+a_n=\underbrace{\mu+\mu+\ldots+\mu}_{\text{$n$ times}}$$
- that is, if we replaced every $a_i$ with $\mu$, we would get the same answer when we summed all of them. To imagine this, consider if we had a bunch of glasses of water. Transferring water from one to another doesn't change the overall sum - so if $a_i$ were the amount of water in in each glass to start with, $\mu$ would be the amount in each cup were the amounts transferred to be equal. Notice the above equation can rearrange to
$$\frac{a_1+a_2+\ldots+a_n}{n}=\mu$$
which is the standard definition.
The geometric mean is just the same, except we use multiplication instead of addition. So, we want to solve
$$a_1\cdot a_2\cdot\ldots\cdot a_n=\underbrace{\mu\cdot\mu\cdot\ldots\cdot \mu}_{\text{$n$ times}}$$
where we get that the product of every element is preserved when we replace all the elements with $\mu$. This could be imagined as, if we had rectangular prism in $n$ dimensions (that's easy to imagine right? Just let $n$ be not-very-big), then the product of all its side lengths $a_i$ would be its volume. Moreover, if stretched one dimension by a factor $c$ while compressing another by the same factor, the volume would be preserved - so the geometric mean $\mu$ would be the sidelength of the hypercube with the same volume. The above formula, of course, simplifies to
$$\sqrt[n]{a_1\cdot a_2\cdot\ldots\cdot a_n}=\mu.$$
A nice note to add to this answer is that a weighted average, with weights $w_i$ can just be interpreted as the solution to
$$w_1a_1+w_2a_2+\ldots+w_na_n=w_1\mu+w_2\mu+\ldots+w_n\mu$$
where, again, we replace every $a_i$ with $\mu$. I suppose this generalizes to create an "average" with respect to any $f$ where the average satisfies $f(a_1,a_2,\ldots\,a_n)=f(\mu,\mu,\ldots,\mu)$ - where "arithmetic mean" is the where $f$ is the sum and "geometric mean" is where $f$ is the product (just the same as the difference between "arithmetic" and "geometric" progression) - and "weighted average" is a weighted sum, and so on.
Answer: One important motivation for the geometric mean is in sequential percentage increases.
If you have a sequence of percentage increases, and want to know the average percentage increase over the period, you must use the geometric mean.
The arithmetic mean (or other forms of average) will not cut it.
So, this has important applications in financial mathematics.
If the average percentage increase is $\bar{p}$% per year, then we expect an amount to increase by a factor of $(1+\bar{p}/100)$ per year.
So, the total increase ought to be $(1+\bar{p}/100)^n$, if we want the average to make sense.
If we know the individual increases are $p_1, p_2, ... p_n$, then the total increase will be $(1+p_1/100)(1+p_2/100)...(1+p_n/100)$
So, the motivation for the n-th root should be clear - if we have the individual increases, we can access the total increase, and then we'll need to take the n-th root to correctly calculate the average increase.
Comment: Again, the most important question - why doesn't the arithmetic mean *cut it*?
Comment: I have updated my answer in this respect. The geometric mean is necessary because increases multiply up, rather than add up.
Comment: @Rebuq: I illustrated in my comment to your question why the arithmetic mean is not the correct tool to use: even if the sum of the growth rates averages to 0, that does *not* mean your investment returns to its original value, but in fact there will be a net loss.
Answer: To expand on Domagoj Pandža's great answer, the "distance" function for the geometric mean is:
$$
d(n) = \sum_i \left( \ln x_i - \ln n \right)^2.
$$
The geometric mean $n = \prod_i x_i^{1/k}$ can be derived as the function that minimizes the value of this distance function.
Proof
Expand:
$$
d(n) = \sum_i (\ln x_i)^2 - 2 \ln n \sum_i \ln x_i + k (\ln n)^2
$$
Differentiate with respect to $n$:
$$
\frac{d}{dn}d(n) = -\frac{2}{n} \sum_i \ln x_i + \frac{2k}{n} \ln n
$$
Solve $d d(n) / dn = 0$:
$$
\frac{2k}{n} \ln n = \frac{2}{n} \sum_i \ln x_i\\
k \ln n = \sum_i \ln x_i \\
\ln n = \frac{1}{k} \sum_i \ln x_i \\
n = \exp \frac{1}{k} \sum_i \ln x_i \\
$$
The last line is the geometric mean, expressed in log form.
Log form of geometric mean
The geometric mean is:
$$
n = \prod_i x_i^{1/k},
$$
which implies that:
$$
\ln n = \ln \prod_i x_i^{1/k} \\
= \frac{1}{k} \sum \ln x_i. \\
$$
Thus the geometric mean may also be written as:
$$
n = \exp \frac{1}{k} \sum \ln x_i.
$$


Left hand Fingering for G Root Position Dominant 7th Chord?

Question: I notice that a lot of people recommend playing a G root position dominant 7th chord in the left hand with the fingers 5, 3, 2, 1. But to me, 5, 4, 2, 1 is more comfortable.
Is it considered "bad" practice to play root position dominant 7th chords this way? Is there a reason the fingerings 5, 3, 2, 1 seem to be played more often than 5, 4, 2, 1?
Answer: One source to refer to is Cooke, Mastering the Scales and Arpeggios:

http://hz.imslp.info/files/imglnks/usimg/d/d3/IMSLP69769-PMLP140424-Cooke-Mastering_the_Scales_and_Arpeggios.pdf

Cooke uses the fingering 5-4-2-1 for a root position dominant seventh chord in the left hand.

One reason to use 4 instead of 3 on the third of the chord (B natural for G7 in C major)  is it leaves the third finger free to "C" for common chord changes like G7 to C.
Another resource for scales and arpeggios: Knott, Scale and Arpeggio Manual.

https://imslp.org/wiki/Scale_and_Arpeggio_Manual_(Knott%2C_Thomas_B.)

...Part II has the chord materials. Knott seems to use the third finger as standard, however that part starts with a discussion about how to choose between the 4th and 3rd fingers in the left hand. Essentially, choose the finger physically closest to the piano key to play.
A long time ago a professional pianist recommended to me: Cortot, Rational Principles of Piano Technique.

https://imslp.org/wiki/Rational_Principles_of_Piano_Technique_(Cortot%2C_Alfred)

That edition is in Italian, I can't find an English version online. At any rate, page 86 has this figure:

...although the clef is treble I believe the finger numbering above the staff are right hand and those below are left hand.
Answer: Those are probably the two most viable options. I suppose you are playing in root position, pinky on G. The following chord, 9 times out of 8, will be C in some form, and if one wants to play a second inversion of it, it's easier to keep pinky on that G, and then with 5 3 2 1, there's two fingers to lift to play C and E, whereas with 5 4 2 1, there's a 5 3 1 option for the C triad. But, really, the matter is fairly insignificant, and will hinge more on each individual's hand, and fingering disposition.


How can I resolve $\sum_{x=0}^{\infty} xe^{-x/\theta}$?

Question: I stumble on this summation during an exercise. How can I resolve $\sum_{x=0}^{\infty} xe^{-x/\theta}$?
Comment: hint: set $u:=\dfrac 1{\theta}$ and compute $\displaystyle \frac d{du} \sum_{x=0}^\infty e^{-x\,u}$.
Comment: The duplicate question that this is linked to is really impossible to find, because it has no keywords in the title that actually describe it. This question is much better, and has a better answer.
Comment: you can approximate it by an Gaussian integral, which is (relatively) easy, because solutions are generally known.
Answer: Here is a slightly more general strategy that can be adapted here: If $|r| < 1$, we have
$$\sum\limits_{x = 0}^{\infty} r^x = \frac{1}{1 - r}$$
Taking a derivative on both sides leads to
$$\sum\limits_{x = 1}^{\infty} x r^{x - 1} = \frac{1}{(1 - r)^2}$$
or by a change of indices,
$$\sum\limits_{x = 0}^{\infty} (x + 1) r^{x} = \frac{1}{(1 - r)^2}$$
So applying this last statement combined with the first,
$$\sum\limits_{x = 0}^{\infty} x r^x = \frac{1}{(1 - r)^2} - \frac{1}{1 - r} = \frac{r}{(1 - r)^2}$$
So choose $$r = e^{-1/\theta}$$
Comment: even though I totally agree with this strategy, I wonder why is [Wolframalpha](http://www.wolframalpha.com/input/?i=summation+of+x*exp%28-x%2Ft%29) giving a different result: $\frac{e^{1/x}}{(e^{1/x}-1)^2}$.
Comment: @srodriguex The forms are equivalent: Multiply my expression top and bottom by $e^{2/\theta}$.
Answer: In addition to the general solution, you have to cut off those terms with $\theta <0$, because the general term $xe^{-\frac{x}{\theta}}$ diverges and the series cannot converge.


Riemann Sum Question Help Needed

Question: Ive got another question today:
Define $f : [−2, 2] →$ $\mathbb{R}$ by f(x) = $x^2 -4$. Let $Q = \{−2, 0, 1, 2\}$, and consider the
corresponding Riemann sum $S_Q(f, ξ)$. What values can the Riemann sum $S_Q(f, ξ)$
get? Conclude that
$\int_{-2}^{2} f(x) dx<0$
I can easily conclude that $\int_{-2}^{2} f(x) dx<0$ but cant really explain the first part of this question. Any help will be appreciated.
Comment: hint: find the max and min of $f$ over the subintervals.
Comment: what do you assume the sub-intervals as?? @DeepSea
Answer: Well, for the upper Riemann sums. You can do this by finding the sup of the function evaluated at each subinterval of your partition Q that is the sup between f(-2),f(0) and then the sup at f(0),f(1) and so on.. After finding the sups of each subinterval you just multiply that sup with the distance of the corresponding subinterval and find the sum. Example: sup[f(-2),f(0)](-2-0) + sup[f(0),f(1)](0-1)+... Similar argument would be made for the lower Riemann sum but for the inf rather than sup.

Riemann Sum Question Help Needed


How can I save parts of the URL to the database when a certain page is viewed?

Question: Can a page be created the normal way (not by module) in Drupal 7, using Content Type an so forth, yet still trigger a module and pass a variable from the URL.
The idea is to let the web team create their page as normal, but require the last part of the path to be a variable. Then a module is called to take that variable and do magic with it.
We want the module to work with the variable in the background, NOT render a page.
Comment: Yes, you'll need to give more specifics as to what the code will accomplish with that variable is in order to provide an accurate answer.
Comment: Marketing creates the page with a URL that contains a variable representing the user. User gets an email and clicks on button that goes to page. When they get to the page the module is triggered to collect the variable data from the URL. The module will then save that value to a DB. That's all.
Comment: You can take a look at the statistics module, perhaps it already does what you are looking for.
Answer:
Marketing creates the page with a URL that contains a variable
representing the user. User gets an email and clicks on button that
goes to page. When they get to the page the module is triggered to
collect the variable data from the URL. The module will then save that
value to a DB.

Use template_preprocess_node
Have the URL in the e-mail formatted like this:
example.com/node/1?param1=value1?param2=value2

If it's required that the user must be logged in
example.com/user/login?destination=node/1?param1=value1?param2=value2

I used /node/1 as an example, but you can use its url alias instead if it has one.
Then in your mymodule.module file
function mymodule_preprocess_node(&$variables) {
  $node = $variables['node'];
   if ($node->type == 'article') { // checks its Article Content Type
     $params = drupal_get_query_parameters();
     if (!empty($params)) {
       // do more magic to get each param value on its own
       // save to the DB
     }
   }
}


Copy file on remote server using WinSCP .NET Assembly

Question: I have been using WinSCP .NET Assembly in one of my projects to transfer files from one FTP server to another. Now, I want to copy a file from one directory to another (both present on the same FTP server). I have found the following method in WinSCP .NET assembly:
MoveFile(string sourcePath, string targetPath)

But it moves the file from source directory to target path (Deletes from source path) whereas I want to keep a copy on both paths.
I have found out that there is a method called duplicate in WinSCP client that performs the copy operation but it is not available in assembly.
Is there any way to retain the original file at source path and create a copy at destination as well?
Note:
My question is specific to WinSCP .Net assembly. I am not asking about FTP protocol.
Comment: Possible duplicate of [How to copy a file on an FTP server?](https://stackoverflow.com/questions/16005388/how-to-copy-a-file-on-an-ftp-server)
Answer: Use Session.DuplicateFile method:
public void DuplicateFile(string sourcePath, string targetPath)

Though note that it works only if the server actually supports the duplication, what most servers don't.
While the GUI "Duplicate" feature will fall back to "download and upload" (called "Duplicate via local temporary copy" in GUI). In .NET assembly, you can do the same using Session.GetFiles and Session.PutFiles, Session.DuplicateFile won't do it for you automatically.
Comment: Thanks for support. i have also found out that DuplicateFile(string sourcePath, string targetPath); function is available in latest version of the assembly (5.13.3). Is this following the same "Duplicate via local temporary copy" concept?
Comment: True! I've completely forgot that `DuplicateFile` has been released already. I've updated my answer.


error installing rpy2 on os x 10.6: unable to execute gcc-4.0

Question: I am attempting to install rpy2 using pip with:
    $ sudo pip install rpy2

which exits with an error:
    gcc-4.0 -fno-strict-aliasing -fno-common -dynamic -arch ppc -arch i386 -g -O2 -DNDEBUG -g -O3 -DR_INTERFACE_PTRS=1 -DHAVE_POSIX_SIGJMP=1 -DCSTACK_DEFNS=1 -DRIF_HAS_RSIGHAND=1 -I./rpy/rinterface -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/opt/local/lib/R/include/x86_64 -I/opt/local/lib/R/include -c ./rpy/rinterface/_rinterface.c -o build/temp.macosx-10.3-fat-2.7/./rpy/rinterface/_rinterface.o

    unable to execute gcc-4.0: No such file or directory

    error: command 'gcc-4.0' failed with exit status 1

I have attempted to also install rpy2 with macports, however the install completed but rpy2 would not import.  I have install XCode, Version 4.0.2 Build 4A2002a, and gcc is installed.
    $ which gcc

returns:
    /usr/bin/gcc

and
    $ gcc

returns:
    i686-apple-darwin10-gcc-4.2.1: no input files

It seems that it is looking for an older version of gcc and I have no idea how to point it in the right place.  Any help would be greatly appreciated.
Answer: It seems to think that you're using OSX 10.3: build/temp.macosx-10.3, which might be the reason why it's trying to look for an old gcc compiler.
You should be able to overwrite the compiler with the CC environment:
export CC=gcc
pip install rpy2

I think it's a typical distutils issue.
Comment: Thank's for the help.  I followed your link and landed [here](http://stackoverflow.com/questions/5967065/python-distutils-not-using-correct-version-of-gcc/5968410#5968410).  However, I couldn't get this to work.  In a python environment, I get:

        >>> from distutils import sysconfig
        >>> sysconfig.get_config_var('LDSHARED')
        'gcc-4.0 -bundle -undefined dynamic_lookup -arch ppc -arch i386   -g'
        >>> sysconfig.get_config_var('CC')
        'gcc-4.0'

(Sorry, formatting seems not to work), but I seem unable to change the 'CC' variable
Answer: ::HACK WARNING::
This may cause something else to break in the future, but if you don't think the version of gcc that compiles your rpy2 makes a difference, you could create a symlink named /usr/bin/gcc-4.0 pointing to /usr/bin/gcc and then try the pip install again
Answer: If it helps any, I solved this issue with sym links, and I think it will work for you. I wrote this with my version of gcc in mind, which is 4.2:
cd /usr/bin
rm cc gcc c++ g++
ln -s gcc-4.2 cc
ln -s gcc-4.2 gcc
ln -s c++-4.2 c++
ln -s g++-4.2 g++
ln -s gcc-4.2 gcc-4.0

There ya go!
Answer: An Idea would point gcc-4.0 to the default gcc flag:

sudo ln -s /usr/bin/gcc /usr/bin/gcc-4.0


Poisson Distribution and Total propability theorem question

Question: The number of balls we get from our grandpa follows the poisson distribution with $\lambda =1/5$ ball/year.  The probability of getting a red ball from him is 0.08 .
Q: Calculate the probability of getting a red ball in the upcoming 5 years.
I know that i have to use the total probability theorem but i cant figure out how. Any help is appreciated.
Answer: Let $N$ be the number of balls obtained from grandpa and let $R$ be the number of red balls with $0 \le R \le N$. Clearly, if you know $N$, then $R \sim \mathcal{B}(N, p)$ where $p = 0.08$. So you can condition on $N$ to get
$$
\mathbb{P}[R = 0]
 = \sum_{n=0}^\infty \mathbb{P}[R = 0, N = n]
 = \sum_{n=0}^\infty \mathbb{P}[R = 0 | N = n] \mathbb{P}[N=n]
$$
and both factors are now easy to compute. Can you finish?
Comment: Can you please be more specific? The answer to my question according to my textbook is $\sum_{i=0}^\infty (1-0.92^i) \mathbb{P}[N = i]$ . I dont know how the first part $(1-0.92^i)$ is produced, The binomial formula does not give this as an output .
Comment: I gave you an example, mine deals with $\mathbb{P}[R=0]$. You actually need $\mathbb{P}[R>0]$. Can you use my approach? $0.92^i$ will come from the Binomial formula (for $k=0$)
Comment: Yes now i got it. So the complete answer for others to see is $\sum_{i=0}^\infty \mathbb{P}[R <= 1] \mathbb{P}[N = i] = \sum_{i=0}^\infty [1-\mathbb{P}[R = 0]] \mathbb{P}[N = i]  = \sum_{i=0}^\infty [1-\binom{i}{0}0.08^0 0.92^i] \mathbb{P}[N = i]  = \sum_{i=0}^\infty (1-0.92^i) \mathbb{P}[N = i]$ . Thank you for your help gt6989b
Comment: @ΧρηστοςΚαρυστινος yes, exactly :-)


Determinant of $\left(\begin{smallmatrix} -bc & b^2+bc & c^2+bc \\ a^2+ac & -ac & c^2+ac \\ a^2+ab & b^2+ab & -ab \end{smallmatrix}\right)$

Question: I started by adding $C_1$ goes to $C_1 + C_2 + C_3$.
After that well nothing seemed good to continue I have tried other steps too but it keeps getting more complex.
Comment: Possible duplicate of [To show: $\det\left[\begin{smallmatrix} -bc & b^2+bc & c^2+bc\\ a^2+ac & -ac & c^2+ac \\ a^2+ab & b^2+ab & -ab \end{smallmatrix}\right]=(ab+bc+ca)^3$](https://math.stackexchange.com/questions/2016733/to-show-det-left-beginsmallmatrix-bc-b2bc-c2bc-a2ac-ac-c) – found quickly with [Approach0](https://approach0.xyz/search/?q=%24%5Cbegin%7Bvmatrix%7D%20-bc%20%26%20b%5E2%2Bbc%20%26%20c%5E2%2Bbc%20%5C%5C%20a%5E2%2Bac%20%26%20-ac%20%26%20c%5E2%2Bac%20%5C%5C%20a%5E2%2Bab%20%26%20b%5E2%2Bab%20%26%20-ab%20%5Cend%7Bvmatrix%7D%24&p=1)
Comment: Why can't you just calculate the determinant normally? It would be faster than bothering with whatever this is.
Answer: Let $a+b+c=3u$, $ab+ac+bc=3v^2$ and $abc=w^3$.
Thus, our determinant it's $$-a^2b^2c^2+2abc\prod_{cyc}(a+b)+\sum_{cyc}a^2b^2(a+c)(b+c)=$$
$$=-w^6+2w^3(9uv^2-w^3)+\sum_{cyc}a^2b^2(c^2+3v^2)=$$
$$=-w^6+2w^3(9uv^2-w^3)+3w^6+3v^2(9v^4-6uw^3)=27v^6=(ab+ac+bc)^3.$$
Comment: I'm a high school student so I don't the cyc function
Comment: @Aashay agrawal It's a sing only. For example, $\prod\limits_{cyc}(a+b)=(a+b)(b+c)(c+a).$


Prove that $x+g$ is homeomorphism

Question: Problem: Assume we have $g:\mathbb{R}^n\longrightarrow \mathbb{R}^n$ of $C^1$ class with derivative bounded uniformly by some constant $M<1$. Consider $h=\mathcal{id}_{\mathbb{R}^n}+g:\mathbb{R}^n\longrightarrow \mathbb{R}^n$. Prove:

$h$ is homeomorphism
$h^{-1}$ is Lipschitz function

My solution:
Clearly $h$ is continous, if $h(x)=h(y)$ than $|x-y|=|g(x)-g(y)|$ what contradicts increment theorem if $x\not = y$ so we have that $h$ is injective. From known fact from topology injective continous function between $\mathbb{R}^k$ is homeomorphism on image.
My question: I think that assumption of being of $C^1$ class can be ommited (if differentiability is kept) because all arguments work than, am I right ? Any ideas how to prove $2$?
Comment: Why is $h^{-1}$ differentiable?
Comment: You are right, I don't konw even if it is true.
Comment: Any idea how to improve that ?
Answer: Here is how I would prove questions 1. and 2.
1. $h$ is an homeomorphism
By the mean value theorem you have for $x,y \in \mathbb R^n$ $$\Vert g(x) - g(y) \Vert = \Vert (h(x) - h(y)) - (x-y)\Vert \le M \Vert x-y \Vert$$ hence by the reverse triangle inequality $$(1-M)\Vert x- y \Vert \le \Vert h(x)-h(y)\Vert$$ which implies that $h$ is injective. According to following post (which rely on Banach-Fixed point theorem) $h$ is also surjective. $h$ image is $\mathbb R^n$.
$h$ is differentiable as the sum of two differentiable maps. Also for all $x \in \mathbb R^n$, $h^\prime(x)$ is invertible. If not, there exists $k \in \mathbb R^n \setminus \{0\}$ with $0=h^\prime(x).k = k + g^\prime(x).k$ which leads to $\Vert k \Vert = \Vert g^\prime(x).k \Vert$ in contradiction with $\Vert g^\prime(x) \Vert \le M < 1$.
According to the inverse function theorem $h$ is invertible, the inverse being continuously differentiable. In particular $h$ is an homeomorphism from $\mathbb R^n$ onto $\mathbb R^n$.
2. $h^{-1}$ is Lipschitz function
For $x \in \mathbb R^n$ you have $$\Vert h^\prime(x) - \mathcal{id}_{\mathbb{R}^n} \Vert = \Vert g^\prime(x) \Vert \le M < 1$$ hence $$(h^\prime(x))^{-1} = \sum_{k=0}^\infty (\mathcal{id}_{\mathbb{R}^n}-h^\prime(x))^k$$ which implies $$\Vert (h^\prime(x))^{-1} \Vert \le \frac{1}{1-\Vert \mathcal{id}_{\mathbb{R}^n} - h^\prime(x) \Vert}= \frac{1}{1-\Vert g^\prime(x) \Vert} \le \frac{1}{1-M}$$
Using again mean value theorem, and the equality $$(h^{-1})^\prime(h(x))=(h^\prime(x))^{-1}$$ valid for all $x \in \mathbb R^n$ we get that $h$ is a Lipschitz function with coefficient $\frac{1}{1-M}$.
Comment: Nice, actually it accures that $h$ is diffeomorphism with bounded derivative from above and below.

Prove that $x+g$ is homeomorphism


When conducting a t-test why would one prefer to assume (or test for) equal variances rather than always use a Welch approximation of the df?

Question: It seems like when the assumption of homogeneity of variance is met that the results from a Welch adjusted t-test and a standard t-test are approximately the same.  Why not simply always use the Welch adjusted t?
Answer: I would like to oppose the other two answers based on a paper (in German) by Kubinger, Rasch and Moder (2009).
They argue, based on "extensive" simulations from distributions either meeting or not meeting the assumptions imposed by a t-test, (normality and homogenity of variance) that the welch-tests performs equally well when the assumptions are met (i.e., basically same probability of committing alpha and beta errors) but outperforms the t-test if the assumptions are not met, especially in terms of power. Therefore, they recommend to always use the welch-test if the sample size exceeds 30.
As a meta-comment: For people interested in statistics (like me and probably most other here) an argument based on data (as mine) should at least count equally as arguments solely based on theoretical grounds (as the others here).

Update:
After thinking about this topic again, I found two further recommendations of which the newer one assists my point. Look at the original papers (which are both, at least for me, freely available) for the argumentations that lead to these recommendations.
The first recommendation comes from Graeme D. Ruxton in 2006: "If you want to compare the central tendency of 2 populations based on samples of unrelated data, then the unequal variance t-test should always be used in preference to the Student's t-test or Mann–Whitney U test."
In:
Ruxton, G.D., 2006. The unequal variance t-test is an underused
alternative to Student's t-test and the Mann–Whitney U test.
Behav. Ecol. 17, 688–690.
The second (older) recommendation is from Coombs et al. (1996, p. 148): "In summary, the independent samples t test is generally acceptable in terms of controlling Type I error rates provided there are sufficiently large equal-sized samples, even when the equal population variance assumption is violated. For unequal-sized samples, however, an alternative that does not assume equal population variances is preferable. Use the James second-order test when distributions are either short-tailed symmetric or normal. Promising alternatives include the Wilcox H and Yuen trimmed means tests, which provide broader control of Type I error rates than either the Welch test or the James test and have greater power when data are long-tailed." (emphasis added)
In:
Coombs WT, Algina J, Oltman D. 1996. Univariate and multivariate omnibus hypothesis tests selected to control type I error rates when population variances are not necessarily equal. Rev Educ Res 66:137–79.
Comment: Meta-response: Good point.  But your data might not behave like mine! :-)
Comment: Henrik, would you mind if I edit the answer to: (1) change the terminology by calling the tests Student's t-test and Welch's t-test (as I've found in most of the literatura); (2) include another paper that suggests it in the discussion: https://www.rips-irsp.com/article/10.5334/irsp.82/ (it emphasizes the bias that happens when you pick the tests based in the Levene's test of homogeneity).
Answer: Of course, one could ditch both tests, and start using a Bayesian t-test (Savage-Dickey ratio test), which can account for equal and unequal variances, and best of all, it allows for a quantification of evidence in favor of the null hypothesis (which means, no more of old "failure to reject" talk)
This test is very simple (and fast) to implement, and there is a paper that clearly explains to readers unfamiliar with Bayesian statistics how to use it, along with an R script. You basically can just insert your data send the commands to the R console:
Wetzels, R., Raaijmakers, J. G. W., Jakab, E., & Wagenmakers, E.-J. (2009). How to Quantify Support For and Against the Null Hypothesis: A Flexible WinBUGS Implementation of a Default Bayesian t-test.
there is also a tutorial for all this, with example data:
http://www.ruudwetzels.com/index.php?src=SDtest
I know this is not a direct response to what was asked, but I thought readers might enjoy having this nice alternative
Comment: always these bayesian guys...
Comment: Another Bayesian alternative to the t-test is Kruschke's BEST (Bayesian estimation supersedes the t test) routine. More info here: http://www.indiana.edu/~kruschke/BEST/ . An online version here: http://www.sumsar.net/best_online/ .
Answer: Because exact results are preferable to approximations, and avoid odd edge cases where the approximation may lead to a different result than the exact method.
The Welch method isn't a quicker way to do any old t-test, it's a tractable approximation to an otherwise very hard problem: how to construct a t-test under unequal variances.  The equal-variance case is well-understood, simple, and exact, and therefore should always be used when possible.
Comment: I think I tend to agree more with John Tukey -- "*Far better an approximate answer to the right question, which is often vague, than an exact answer to the wrong question, which can always be made precise.*"
Comment: The equal-variance (Student) t-test itself is merely an (ill-understood) approximation when the *population* sample variances are unequal. Therefore, unless it is known that the population variances are equal, it is better to use an approximation to the correct sampling distribution (the Welch-Satterthwaite) than to use a perfectly accurate distribution that does not apply to the data model.
Comment: If you *really* need a strict control over Type I error rate you could do worse than Behrens & Fisher's original test. It is exact in the sense that e.g. Fisher's Exact Test is exact: Type I errors are guaranteed not to exceed the nominal rate, whatever the true values of the nuisance parameters. (And its rejection regions are sensible ones.)
Answer: Two reasons I can think of:

Regular Student's T is pretty robust to heteroscedasticity if the sample sizes are equal.
If you believe strongly a priori that the data is homoscedastic, then you lose nothing and might gain a small amount of power by using Studen'ts T instead of Welch's T.

One reason that I would not give is that Student's T is exact and Welch's T isn't.  IMHO the exactness of Student's T is academic because it's only exact for normally distributed data, and no real data is exactly normally distributed.  I can't think of a single quantity that people actually measure and analyze statistically where the distribution could plausibly have a support of all real numbers.  For example, there are only so many atoms in the universe, and some quantities can't be negative.  Therefore, when you use any kind of T-test on real data, you're making an approximation anyhow.
Comment: (1) is incorrect when the underlying population variances are greatly different.  As an extreme case--to see why this is so--consider what happens when one population has no variance at all. The Student t would in effect be comparing data from the other population to a constant, but it would think it has twice as many degrees of freedom.  The error it makes would be comparable to just using a Z test.
Comment: While this is true @whuber it's only for very extreme cases. I was just looking at a 1e6:1 variance difference and p ≈ .053. So it can happen but I'd still argue it's pretty robust with equal N.
Comment: @John A 1e6:1 variance ratio is *huge*, regardless of what the $n_i$ might be.  The Student's t is likely to be misleading in that case.
Comment: @whuber, I'm just suggesting that while your comment above is technically true, Welch correction isn't the solution to the problem you pose as an example and it's not even really very critical of the robustness of the test in terms of alpha rates (which is what (1) usually means). As you suggest, when (extreme) unequal variance is an issue you've got other problems, but that's really a different topic.
Answer: The fact that something more complex reduces to something less complex when some assumption is checked is not enough to throw the simpler method away.
Comment: Especially where students are concerned.
Answer: I would take the opposite view here.  Why bother with the Welch test when the standard unpaired student t test gives you nearly identical results.  I studied this issue a while back and I explored a range of scenarios in an attempt to break down the t test and favor the Welch test.  To do so I used sample sizes up to 5 times greater for one group vs the other.  And, I explored variances up to 25 times greater for one group vs the other.  And, it really did not make any material difference.  The unpaired t test still generated a range of p values that were nearly identical to the Welch test.
You can see my work at the following link and focus especially on slide 5 and 6.
http://www.slideshare.net/gaetanlion/unpaired-t-test-family
Comment: The unpaired student t test has two formulas.  The large sample formula is applied to samples with more than 30 observations.  The small sample formula is applied to samples with less than 30 observations.  The main difference in those formulas is how they calculate the pooled standard error.  The small sample formula is much more complicated and counterintuitive.  And, in reality it really makes very little difference.  I have tested that several times.  That's why I think most people have forgotten about this distinction.  And, they use most of the time the large sample formula.
Comment: I'm sorry, what distinction are you making between the large sample formula and the small sample formula?  Are you calculating the variances using a population formula in large samples rather than using a sample estimate of the population variance?
Answer: With the assumption of equal variance, one can derive the non asymptotic distribution of t statistics. But when the assumption is violated, two variance terms cannot be cancelled, and we cannot simplify the distribution of statistics to a fixed one. Thus test can't be done.
Welch t test is an approximation which is robust and give an approximate degree of freedom. But it is not "exact", which means its type one error is not exactly what you want theoretically.
From my perspective, even when homogeneity test doesn't reject "equal variance", there is still risk to use t test assuming same variance. Because the true variance difference may be small/not significant, but not zero. We need a test without relying on "same variance", rather than use homogeneity test for "same variance".
https://arxiv.org/abs/2210.16473. Here is my new paper, hope it can help with your question. It can derive "exact" or non-asymptotic t statistics when variances of two groups are different, and it reaches the maximal degree of freedom that an "exact test" can allow. In small sample cases, it significantly outperforms Welch's t-test, in the sense of type one error. ($\mu_1=\mu_2=0$,$\sigma_1=1,\sigma_2=2,n_1=5,n_2=50$)
Its idea is: paired t test can always give an exact test, even when variances are unequal. But it loses some information when n1<n2, because it can only use n1 data points from n2 samples. This paper uses an orthogonal matrix to project the longer vector (n2) into a length (n1) vector, then we can use paired t test, with enough/compressed information.
Go here for instruction of use, a package developed by me:  https://github.com/hobbitish1028/Te_test
Comment: That's ingenious, but any inferences you make from i.i.d. samples oughtn't to depend on their ordering. The same can be said, of course, of Scheffé's solution of the Behrens-Fisher problem; he later wrote that he developed it "before I had much consulting experience, and since then I have never recommended the solution in practice" (Scheffé (1970), *J. Am. Stat. Assoc.*,  **65**, 332, "Practical Solutions of the Behrens-Fisher Problem").
Comment: +1 Thank you for sharing this nice idea.
Answer: It's true that the frequentist properties of the Welch corrected test are better than the ordinary Student's T, at least for errors. I agree that that alone is a pretty good argument for the Welch test. However, I'm usually reluctant to recommend the Welch correction because it's use is often deceptive. Which is, admittedly not a critique of the test itself.
The reason I don't recommend the Welch correction is that it doesn't just change the degrees of freedom and subsequent theoretical distribution from which the p-value is drawn. It makes the test non-parametric. To perform a Welch corrected t-test one still pools variance as if equal variance can be assumed but then changes the final testing procedure implying either that equal variance cannot be assumed, or that you only care about the sample variances. This makes it a non-parametric test because the pooled variance is considered non-representative of the population and you conceded that you're just testing your observed values.
In and of itself there's nothing particularly wrong with that. However, I find it deceptive because a) typically it's not reported with enough specificity; and b) the people who use it tend to think about it interchangeably with a t-test. The only way I ever know that it has been done in published papers is when I see an odd DF for the t-distribution. That was also the only way Rexton (referenced in the Henrik answer) could tell in review. Unfortunately, the non-parametric nature of the Welch corrected test occurs whether the degrees of freedom have changed or not (i.e. even if the sample variances are equal). But this reporting issue is symptomatic of the fact that most people who use the Welch correction don't recognize this change to the test has occurred. I just interviewed a few colleagues and they admitted they had never even thought of it.
Therefore, because of this, I believe that if you're going to recommend a non-parametric test don't use one that often appears parametric or at least be very clear about what you're doing. The official name of the test should be Non-Parametric Welch Corrected T-test. If people reported it that way I'd be much happier with Henrik's recommendation.
Comment: Thank you.  Apart from the reporting issue--which it would be unfair to characterize as a fault of the test!--this seems to come down to some sort of objection on your part that the Welch test is non-parametric.  What could possibly be the matter with that?  *Ceteris paribus*, that has to be considered an advantage, not a problem.
Comment: I couldn't find any support in your answer for why the Welch test might be "deceptive."  Could you explain the basis for that?
Comment: It's a distinction that's generally not made clear. I admit in the answer that it's not in and of itself a problem but most people tend to treat it parametrically, which is an error. I don't think here is the place to have the discussion about benefits or costs of non-parametric testing. Also, it wasn't mentioned in the thread and it may be an issue for many people. As an aside, two of our intro stats class teach it in parallel with the Student t-test, and promote it, but have a whole separate section on non-parametric tests.
Comment: Can you clarify what you mean by "makes the test nonparametric"?
Comment: Perhaps my edits clarified things @whuber. I should have been clear that it's not guaranteed to be deceptive but often is to both the user of the test and reader of the test results.
Comment: Isn't paragraph 2 sufficient?
Comment: Umm, not really; especially since that's exactly the part that led me to ask. Maybe we're starting from different places. What definition of the word 'nonparametric' are you using here?
Comment: Statistics are parametric if they are based on population parameters. What makes this non-parametric as a test is that, even though you estimate an effect variance that looks like the parameter estimate in an equal variance t-test, you don't actually do a test that maintains that assumption of a fixed population parameter and allow it to vary.


Bash: how to know if the last command's output ends with a newline or not?

Question: Most of the time the output of a command ends with the newline character. But sometimes it does not, so the next shell prompt is printed in the same line together with the output.
Example:

root@hostname [~] # echo -n hello
  helloroot@hostname [~] #

I've always found that very annoying.
Now, I could just add a "\n" at the beginning of the the PS1 variable, but most of the time that will print one extra line I dont need.
Is it possible to know whether the last command's output ended with a newline or not?

Solution:
(Thanks to Dennis)
PS1='$(printf "%$((`tput cols`-1))s\r")\u@\h [\w]\$ '

Comment: The whole thing can be done as just: `PS1='\[\e[7m%\e[m$( printf "%*s" "$((COLUMNS-1))" "" )\r\e[K\]\u@\h [\w]\$ '`
Comment: This should be moved to superuser.
Comment: I like your version! You used `$()` in one place and backticks in another. You can use `$()` in both.
Comment: I know. But for me it's easier to read that way
Comment: I wouldn't use `tput cols` because it just outputs the value of the COLUMNS variable anyway, and it's slower because it's not a shell builtin.  You'll also want to include `\e[K` (equivalent to `tput el`) to delete the inserted whitespace so that you don't get a bunch of trailing whitespace when copying and pasting in the default case.  Finally, you need to enclose all this magic between `\[` and `\]` or else bash will try to second-guess your cursor position and it'll mess up when you edit your command/history.
Answer: I've been experimenting with the following to emulate the feature from zsh in Bash:
$ unset PROMPT_SP; for ((i = 1; i <= $COLUMNS + 52; i++ )); do PROMPT_SP+=' '; done
$ PS1='\[\e[7m%\e[m\]${PROMPT_SP: -$COLUMNS+1}\015$ '

It issues a reverse video percent sign, followed by a bunch of spaces to make it wrap to the next line, then a carriage return, followed by a dollar sign and a space. You can add prompt escapes after the "\015" to customize your prompt.
Using this depends on how your terminal handles right margin line wrapping (automatic margins). The length of PROMPT_SP is arbitrary, but should be at least 80 or whatever your usual terminal width is. You may need to hard-code that value if $COLUMNS isn't set yet by the time the for loop is run in ~/.bashrc. You may want shopt -s checkwinsize if it's not already set.
Comment: @davidchambers: The background of the character is displayed in the foreground color and the character itself is displayed in the background color. See `man 5 terminfo` and search for "reverse video" to see some documentation that uses this terminology.
Comment: I wonder why someone downvoted *each answer*. Hmmm... no explanation. How helpful.
Comment: Here's another way, without using a loop, to create the pad string: `printf -v PROMPT_SP '%*s' $((COLUMNS + 52)) ''`
Comment: What is a "reverse video percent sign"? The word "video" has me confused, and I haven't been able to find the answer on Google.
Answer: zsh tries to solve your problem. If the last output ends without a newline, you will get:
$ echo -n 'abc'
abc%
$

Where the % uses inverted background/foreground. Not sure if it's portable to bash in any way.
Answer: No it isn't possible.  Bash itself does not process or see the output of the program it has started.
It just occured to me that it might be possible to write a program to set PROMPT_COMMAND to, which would check the current position of the cursor and issue a newline if the cursor was not at the left edge.
Comment: Good idea. The only problem is... is it possible to know the cursor position?
Answer: I got this idea from @Teddy of detecting the horizontal cursor position and issuing a newline if it isn't at the first column.
In bash, we can detect the cursor position using this command: IFS=';' read -sdR -p $'\E[6n' ROW COL. More information in this answer: https://unix.stackexchange.com/a/183121/340297
The COL variable holds the current column where the cursor is. If $COL is not equal to 1, add a newline before setting the PS1 variable.
Here is my implementation:
_set_prompt() {
    IFS=';' read -sdR -p $'\E[6n' ROW COL # Get cursor position
    [ $COL -ne 1 ] && echo '' # Add newline if cursor is not at 1st column
    PS1="........." # Your PS1 variable
}

PROMPT_COMMAND=${PROMPT_COMMAND:+$PROMPT_COMMAND; }'_set_prompt'

And here is the result (with different PS1):

echo -n doesn't include newline, but newline is issued before displaying the prompt. Whereas, there is no extra newline if newline is already printed by the normal echo command.


DNS queries get routed to localhost on Ubuntu 9.04

Question: For some reason, all DNS queries on one of my Ubuntu 9.04 boxes get routed to localhost, which results in no domain names being resolved. When trying for instance dig example.com, it hangs for ~20 seconds, before quitting with the message ";; connection timed out; no servers could be reached". However, dig example.com @18.104.22.168 returns the correct result immediately. This problem applies to all DNS queries, not only from dig.
$ cat /etc/resolv.conf
184.108.40.206
188.8.131.52

I do not have a .digrc, NetworkManager has been uninstalled, and the network is otherwise working (e.g. I can use it normally for hosts in /etc/resolv.conf). I do not have a local DNS server installed, and nmap confirms that nothing is listening on port 53. I have several other boxen running Ubuntu 9.04 on the same network, DNS is working fine on all of them.
I have used strace to confirm that dig actually reads resolv.conf:
open("/etc/resolv.conf", O_RDONLY|O_LARGEFILE) = 6
(...)
read(6, "22.214.171.124\n220.127.116.11\n"..., 4096) = 27

I have also used tcpdump to confirm that the problem is indeed DNS queries getting routed to localhost:
$ sudo tcpdump -i lo
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on lo, link-type EN10MB (Ethernet), capture size 96 bytes
14:11:54.175580 IP localhost.45910 > localhost.domain: 38233+ A? example.com. (29)
14:11:54.175633 IP localhost > localhost: ICMP localhost udp port domain unreachable, length 65
14:11:55.175542 IP6 ip6-localhost.54963 > ip6-localhost.domain: 38233+[|domain]
14:11:55.175575 IP6 ip6-localhost > ip6-localhost: ICMP6, destination unreachable[|icmp6]

I am out of ideas for resolving this issue, so any input and suggestions are most welcome.
Answer: A record in /etc/resolv.conf should look like
nameserver 126.96.36.199

Comment: I cannot belive i didn't see that, and went off on a wild hunt with strace, nc, tcpdump, and friends... Thanks anyway!
Answer: The format of /etc/resolv.conf is incorrect, it should read:
search domain.com
nameserver 220.127.116.11
nameserver 188.8.131.52

The search line is of course optional. If it exists it will be used to qualify hostnames, eg. looking up the address for router will return the address for router.domain.com
Answer: If you've changed this recently, have you tried "service network restart" or restarting all of the server?
Sounds pretty newb, but that's what it takes when resolv.conf is modified.
Comment: You don't have to restart any networking after modifying /etc/resolv.conf
Comment: Ubuntu doesn't even have a *service* command. If anything restarting networking will most likely overwrite resolv.conf


Mediatemple: Using another IP address as mail server

Question: I have a mediatemple dv server and it has 3 IP addresses. Currently, it uses one of the IP addresses for the mail server. How do I use another IP address? Is it possible to use two of the IP addresses for the mail server?
Sorry, I'm new to this.
Comment: What do you hope to gain by using 2 IP addresses for 1 mail server?
Answer: I work for (mt) Media Temple. Technically you could use a custom configuration of your vhosts to use 2 IP's for email, but it'd be a bit of a pain. I echo Sam's question of why you are wanting to do this?
Comment: Using two IP addresses is unnecessary. I was just wondering if it's possible. Truth is I only need to change the IP address for my mail server. How do I do this? TIA


Stuck with DNX reference issue in ASP.NET 5/VS2015

Question:
This is the Error which I am getting and i have installed with Powershell 3.0 Kindly help me with the solution. Not sure how do overcome this issue. I have tried to upgrade dnvm but nothing works out :(
PATH=.\node_modules\.bin;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External;%PATH%;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External\git
C:\Users\Selva\.dnx\runtimes\dnx-clr-win-x18.104.22.168-beta8\bin\dnx.exe "C:\Users\Selva\.dnx\runtimes\dnx-clr-win-x220.127.116.11-beta8\bin\lib\Microsoft.DNX.PackageManager\Microsoft.DNX.PackageManager.dll" restore "C:\Projects\MVA\src\MVA" -s "C:\Program Files (x86)\Microsoft Web Tools\DNU"
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.DNX.PackageManager' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.DNX.PackageManager'
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
   at Microsoft.Dnx.Runtime.Loader.LoadContext.Load(AssemblyName assemblyName)
   at Microsoft.Dnx.Host.Bootstrapper.RunAsync(List`1 args, IRuntimeEnvironment env, String appBase, FrameworkName targetFramework)
   at Microsoft.Dnx.Host.RuntimeBootstrapper.ExecuteAsync(String[] args, BootstrapperContext bootstrapperContext)
   at Microsoft.Dnx.Host.RuntimeBootstrapper.Execute(String[] args, BootstrapperContext bootstrapperContext)
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
PATH=.\node_modules\.bin;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External;%PATH%;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External\git
C:\Users\Selva\.dnx\runtimes\dnx-clr-win-x184.108.40.206-beta8\bin\dnx.exe "C:\Users\Selva\.dnx\runtimes\dnx-clr-win-x22.214.171.124-beta8\bin\lib\Microsoft.DNX.PackageManager\Microsoft.DNX.PackageManager.dll" restore "C:\Projects\MVA\src\MVA" -f "C:\Program Files (x86)\Microsoft Web Tools\DNU"
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.DNX.PackageManager' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.DNX.PackageManager'
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
   at Microsoft.Dnx.Runtime.Loader.LoadContext.Load(AssemblyName assemblyName)
   at Microsoft.Dnx.Host.Bootstrapper.RunAsync(List`1 args, IRuntimeEnvironment env, String appBase, FrameworkName targetFramework)
   at Microsoft.Dnx.Host.RuntimeBootstrapper.ExecuteAsync(String[] args, BootstrapperContext bootstrapperContext)
   at Microsoft.Dnx.Host.RuntimeBootstrapper.Execute(String[] args, BootstrapperContext bootstrapperContext)
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
PATH=.\node_modules\.bin;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External;%PATH%;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External\git
C:\Users\Selva\.dnx\runtimes\dnx-clr-win-x22.214.171.124-beta8\bin\dnx.exe "C:\Users\Selva\.dnx\runtimes\dnx-clr-win-x184.108.40.206-beta8\bin\lib\Microsoft.DNX.PackageManager\Microsoft.DNX.PackageManager.dll" restore "C:\Projects\MVA\src\MVA" -f "C:\Program Files (x86)\Microsoft Web Tools\DNU"
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.DNX.PackageManager' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.DNX.PackageManager'
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
   at Microsoft.Dnx.Runtime.Loader.LoadContext.Load(AssemblyName assemblyName)
   at Microsoft.Dnx.Host.Bootstrapper.RunAsync(List`1 args, IRuntimeEnvironment env, String appBase, FrameworkName targetFramework)
   at Microsoft.Dnx.Host.RuntimeBootstrapper.ExecuteAsync(String[] args, BootstrapperContext bootstrapperContext)
   at Microsoft.Dnx.Host.RuntimeBootstrapper.Execute(String[] args, BootstrapperContext bootstrapperContext)
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

My Project.Json goes like below
{
  "webroot": "wwwroot",
  "userSecretsId": "aspnet5*************************************",
  "version": "1.0.0-*",

  "dependencies": {
    "EntityFramework.SqlServer": "7.0.0-beta5",
    "EntityFramework.Commands": "7.0.0-beta5",
    "Microsoft.AspNet.Mvc": "6.0.0-beta5",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5",
    "Microsoft.AspNet.Authentication.Cookies": "1.0.0-beta5",
    "Microsoft.AspNet.Authentication.Facebook": "1.0.0-beta5",
    "Microsoft.AspNet.Authentication.Google": "1.0.0-beta5",
    "Microsoft.AspNet.Authentication.MicrosoftAccount": "1.0.0-beta5",
    "Microsoft.AspNet.Authentication.Twitter": "1.0.0-beta5",
    "Microsoft.AspNet.Diagnostics": "1.0.0-beta5",
    "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-beta5",
    "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta5",
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta5",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta5",
    "Microsoft.AspNet.StaticFiles": "1.0.0-beta5",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta5",
    "Microsoft.Framework.Configuration.Abstractions": "1.0.0-beta5",
    "Microsoft.Framework.Configuration.Json": "1.0.0-beta5",
    "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta5",
    "Microsoft.Framework.Logging": "1.0.0-beta5",
    "Microsoft.Framework.Logging.Console": "1.0.0-beta5",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta5"
  },

  "commands": {
    "web": "Microsoft.AspNet.Hosting --config hosting.ini",
    "ef": "EntityFramework.Commands"
  },

  "frameworks": {
    "dnx451": { },
    "dnxcore50": { }
  },

  "exclude": [
    "wwwroot",
    "node_modules",
    "bower_components"
  ],
  "publishExclude": [
    "node_modules",
    "bower_components",
    "**.xproj",
    "**.user",
    "**.vspscc"
  ],
  "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
  }
}

Comment: If you could add your `project.json`, it would help us.
Answer: I'm under the impression that you have a version mismatch (older project with newer version of the framework).
First, make sure that you have the beta8 tooling installed. Then, go in your project properties and make sure to change the target runtime to beta8.
Finally, check your project.json to ensure that you are not left with pre-beta8 packages.
In your project.json, ensure to remove any reference to beta5 and replace them by beta8. Some packages were renamed and some were merged so you might not be able to replace everything.
If you are running with IIS and dependes on Microsoft.AspNet.Server.IIS, make sure to add app.RunIISPipeline(); on your Startup.cs/Configure() method.
Comment: And as mentioned, you have a whole bunch of old packages. Replace `beta5` by `beta8`. Please be aware that some packages were renamed and might not work.
Comment: I am not seeing any package to upgrade when i opened my Nuget package manager. All of my packages are uptodate.
Comment: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.DNX.PackageManager' or one of its dependencies. The system cannot find the file specified.
1>  File name: 'Microsoft.DNX.PackageManager'
Comment: Your `project.json` have dependencies like this: `"EntityFramework.SqlServer": "7.0.0-beta5",`. See this `beta5` there? That comes from the templates. Do a find/replace to get to the version you want to run.
Answer: This issue appears to have been fixed in a newer release of ASP.net, which is available here.
Based on this discussion from GitHub
Comment: Change to beta5 - click on any project->Properties->Application choose beta5. Using `dnvm use 1.0.0-beta5` won't help you. There were breaking changes between these two releases.
Comment: He's running `beta8`.
Comment: Yes. I am running beta 8.
Comment: I have changed to beta5. But getting the same error.

System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.DNX.PackageManager' or one of its dependencies. The system cannot find the file specified.
1>  File name: 'Microsoft.DNX.PackageManager'
Answer: You need to not only install beta 8, but also the tooling for visual studio. the download can be found here. Specifically, you need to download and install WebToolsExtensionsVS14.msi


Como dar espaço no texto do checkboxlist criado dimanicamente

Question: Estou tentando dar um espaço entre o quadradinho do checkboxlist e o texto, mas não esta dando certo, segui o código.

    <asp:Label ID="Label2"   Text="" runat="server"
        CssClass="col-sm-2 control-label" />

        <asp:CheckBoxList ID="cblEscolhaDaOpcao" runat="server"
             DataSourceID="SqlDataSource1" DataTextField="Opcao" RepeatColumns="5" Width="100%" CellSpacing="10" CellPadding="10" >
        </asp:CheckBoxList>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT [Opcao] FROM [ComandaOpcao]">
        </asp:SqlDataSource>

A imagen de como esta ficando
Answer: Seguindo a resposta no link aqui .
Você pode criar um Css
 .test tr input {
            margin-right: 30px;
        }

E acrescentar no seu checkboxlist através Do CssClass.
  <asp:CheckBoxList ID="cblEscolhaDaOpcao" runat="server" CssClass="test" DataValueField="Codigo" RepeatDirection="Horizontal"
                DataTextField="Opcao">
            </asp:CheckBoxList>

Veja funcionando aqui.

<!DOCTYPE html>

<title>

</title>

    <form method="post" action="WebForm1.aspx" id="form1">

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="CHHlRpgZ1fcj/nGoFbp8XKb51W/7QIo9OEkyUnRQPGftAqQjcjxKSvv9wYL02biZQiaWOAFQ0a/hvdBtgoK00aa8o3NF59Qug/Ox/aNTCkcc2KZTWOQEqFaZCGj50bJ/hEGoIgB8k0EnLKPZS/Gg2/yjwmGJo5Vgyvp2gf2/ymFF3MW9eytJ5k3ggbsiArpyZYsnjO7dbUAYGIgfhpXR2oS+gVIxzmpP8pS39Uo5V0H22FA0LWfApZNo+XLBvE0ARsCPRJJNDZUapqmQXpi0mFk3SkclEWlh3erqjE0qozZHfPbS9SchruSWabijDBbpDOv1tyUg5EAXrdaGFjhORCq0rQ60I+5SaEOv0HktK10=" />

 <input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="C687F31A" />
 <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="ZtOBjR7he7tjyKWqoZd6L6CXsZPQ0hXlc1cUw0GqirsmZeOfvrQhr/MiTdBzuJ4gBLjL2uRNEkmQWnDyPJ0B5DP9VKv8QzUyLJ3Cxu1yIbDI7FOPyXtyZ/tYepThLCtxM9Wg1+I0zhdkQHXuujEG+kepfqOY/bk++xdcJMlf4R4=" />

  <input id="cblEscolhaDaOpcao_0" type="checkbox" name="cblEscolhaDaOpcao$0" value="1" />Ademar	<input id="cblEscolhaDaOpcao_1" type="checkbox" name="cblEscolhaDaOpcao$1" value="2" />Rosana	<input id="cblEscolhaDaOpcao_2" type="checkbox" name="cblEscolhaDaOpcao$2" value="3" />Furukama

    </form>

Answer: Você pode criar uma classe no css para deixar da forma que deseja o checkBox.
Para o exemplo, adicionaremos uma classe no checkBoxList (CssClass="chkEscolhaOpcao") e utilizar css para modificar o estilo.
<asp:CheckBoxList ID="cblEscolhaDaOpcao" runat="server"
             DataSourceID="SqlDataSource1" DataTextField="Opcao" RepeatColumns="5" Width="100%" CssClass="chkEscolhaOpcao">
        </asp:CheckBoxList>

E em seu arquivo css você adiciona o estilo que desejar:
.chkEscolhaOpcao input
{
    margin-left: -20px;
}
.chkEscolhaOpcao td
{
    padding-left: 20px;
}


VTK missing wbemidl.h

Question: I think this is related to directx.  The build is on a windows platform.  For now, I used the -k option on make to keep going, and hoping the unbuilt libraries are not needed by opencv.
Error message:
<code>[ 54%] Building CXX object Rendering/OpenGL/CMakeFiles/vtkRenderingOpenGL.dir/vtkDirectXGPUInfoList.cxx.obj
C:\Software\VTK\VTK-6.3.0.rc1\Rendering\OpenGL\vtkDirectXGPUInfoList.cxx:27:21: fatal error: wbemidl.h: No such file or directory
 #include <wbemidl.h>
                     ^
compilation terminated.
</code>
Answer: IF you are using Windows 10, it supports OpenGL2, so while configuration in CMake just turn the variable of : VTL_Rendering_Backend on OpenGL2.

VTK missing wbemidl.h


Problemas com Input AngularJS

Question: Estou com um problema na minha aplicação.
Quando uso o ng-repeat do angularJS para criar uma tabela, e nessa tabela existe um input, e nesse campo input, vem preenchido com um valor.
Tem também um botão SALVAR, onde ele pega o valor do INPUT e manda como parâmetro.
Aí que está o problema. Se eu não clicar no Input para depois clicar no salvar, ele não envia nenhum valor.
Alguém tem uma idéia ?
HTML

          Código
          Descrição
          Quantidade

          {{ax.codigo}}
          {{ax.descricao}}
          <input class='form-control' type='number' ng-model='txtQuantidade' ng-value='ax.quantidade'>
          <button ng-click='Salvar(ax.codigo, txtQuantidade)' type='button' class='btn btn-primary btn-block'>Salvar</button>

JAVASCRIPT
angular.module('app-pedido', [])

.controller('ctl-pedido', function($scope, $http) {

  $scope.itens = [{
    codigo: '00002305',
    descricao: 'Módulo de Memória',
    quantidade: '10.00'
  }];

  $scope.Salvar = function(codigo, quantidade) {

  alert('O código do produto é ' + codigo + ' e a quantidade é ' + quantidade);

  };

});

Veja aqui o exemplo no jsfiddle.
Comment: Você está usando um form com post ou está enviado os dados via json?
Comment: Enviando os dados via JSON.

O problema é exatamente o que está acontecendo no jsfiddle.

O Valor só é passado no parâmetro caso eu "entre" no input. Aí Funciona.
Comment: Troque o tipo do input para text, retirei o ng-value, coloquei o ng-model referenciando a quantidade que está no ax: https://jsfiddle.net/1v0v5ns2/13/
Comment: Perfeito!

Você saberia explicar o por que o type number não funciona?
Comment: Vou pesquisar e coloco como resposta. Tem um mais detalhe, você pode editar a quantidade, e passar a lista toda como json que o angular passa os valores atualizados. Eu tenho uma lista parecida em um sistema, onde o usuário pode editar a quantidade de vários itens.
Comment: Vou tentar fazer dessa maneira que você me falou.

Eu sou iniciante com AngularJS, tenho um pouco de dificuldades, mas a sua ideia é no caso para alterar em lote, todos itens de uma só vez.

É isso né?
Comment: Não, você pode ter um lote e quer alterar apenas um.
Comment: @GuilhermeCatini o `type=number` funciona... se tu lhe deres um `number`: https://jsfiddle.net/1v0v5ns2/21/
Comment: A resposta ajudou a resolver o problema e pode sanar dúvidas similares de outros usuários? Caso positivo não esqueça de marcar como aceita. Pra fazer isso é só clicar no ✓ do lado esquerdo da mesma (abaixo do indicador de up e down votes).
Answer: No input da quantidade você precisa passar
ax.quantidade no ng-model
<input class='form-control' type='number' ng-model='ax.quantidade' ng-value='ax.quantidade'>

e na função click você tem que passar ax.quantidade, que no caso é o valor do objeto que esta sendo executado e gerado no for naquele momento.
<button ng-click='Salvar(ax.codigo, ax.quantidade)' type='button' class='btn btn-primary btn-block'>Salvar</button>

Da forma que esta feito você esta passando uma variavel txtQuantidade que não é inicializada com nenhum valor.
Veja seu exemplo funcionando.
https://jsfiddle.net/boLsq2ua/1/
Answer: Existe um problema com bind do Angular, quando o tipo do input é number. Pelo que pesquisei não existe uma resposta exata para o por que do problema.
Você pode contornar isso mudando o tipo do input para text, que foi o que eu fiz. O Exemplo está aqui: fiddle ou você pode criar uma diretiva para fazer o parse do número para int ou float conforme essa resposta https://stackoverflow.com/questions/17395188/angular-validate-input-type-number
Tem uma thread de discussão desse assunto em um fórum do Angular: https://groups.google.com/forum/#!msg/angular/Ecjx2fo8Qvk/x6iNlZrO_mwJ
Answer: O problema é que você está utilizando o ng-model para um valor temporário, quando na realidade deveria ser a propriedade que deve espelhar o valor do input:

angular
  .module('app-pedido', [])
  .controller('ctl-pedido', function($scope, $http) {

    $scope.itens = [{
      codigo: '00002305',
      descricao: 'Módulo de Memória',
      quantidade: '10.00'
    }];

    $scope.Salvar = function(item) {
      alert('O código do produto é ' + item.codigo + ' e a quantidade é ' + item.quantidade);
    };
  });

          Código
          Descrição
          Quantidade

          {{ax.codigo}}
          {{ax.descricao}}
          {{ax.quantidade}}
          <input class='form-control' type='number' ng-model='ax.quantidade'>
          <button ng-click='Salvar(ax)' type='button' class='btn btn-primary btn-block'>Salvar</button>

Answer: Não precisa trocar o tipo do seu input.
Troque o seu código de:

para:

Problemas com Input AngularJS


main files and module import errors

Question:
Hi, I've been stuck on this problem a while, and all other questions around this issue on this site haven't helped fix the issue.
In the main.py file, I'm trying to import the datastorer function which sits in the StoreData.py file.
I've created empty _init_.py files in the project root, DataStore
folder and also Calculations folder.
I'm importing using :
from project.DataStore.StoreData import datastorer

But always get the error

ModuleNotFoundError: No module named 'project.DataStore'.

I've tried adding
myDir = os.getcwd()
sys.path.append(myDir)

to the top of the file which wasn't successful.
I'm wondering if it's something to do with the name of the file main. Although I need to keep this as the file name. If anyone has any ideas this would be great thank you!
Comment: I mean it's weird that you place your main file deep into the hierarchy of the project and not on the top level but that's probably not the issue.
Comment: Does `import project` work?
Answer: If you add your current folder to python path, then all you imports should not refer to project so try
from DataStore.StoreData import datastorer

Comment: thanks for your answer. Ive tried your suggest but i still receive the error. How can i ensure that the current folder is added to python path? thanks
Comment: either you start python from the project root, either you add the project folder to the `PYTHONPATH` environment variable.
Answer: At the top of main.py you can add
import sys
from os.path import dirname
sys.path.append(dirname(dirname(dirname(__file__))))

main files and module import errors


Extending upper range on a brass instrument

Question: I'm looking for some input into techniques that I can use to extend my range on a Euphonium.
I'm able to get a top C reasonably reliably, but anything above that is just not there. What are common techniques for a brass player to extend their range?
Comment: related question: [How can I develop a high register on a brass instrument without creating tension?](https://music.stackexchange.com/questions/503/how-can-i-develop-a-high-register-on-a-brass-instrument-without-creating-tension/104283#104283)
Answer: Here are some things that I do to keep my upper range in shape and extend it:

Arpeggios:

starting from Bb and going down the scale (↑Bb D F Bb ↓F D Bb and so on)
starting from F and going up the scale (F Bb D F) with the top note held. Go up as far as you can, without using extreme mouthpiece pressure.

Held Notes: Start from a note in the middle of your comfortable range, and hold it for about 5 seconds, then do the same for the next note up on the chromatic scale. As before, only go up as far as you can without using extreme mouthpiece pressure

Hope that helps!


Correctness of a skewed cosine similarity graph

Question: I am currently implementing a word2vec model that uses the cosine similarity to determine the similarity between two vectors.
When plotting all the possible cosine similarities, I get the following graph:

The graph is pretty skewed towards the 'most similar value'. However, I am not sure if this is an ok thing, which can just be corrected by normalizing the data, or if this skewness indicates that something is terribly wrong with the model.
I am not an expert on the topic of natural language processing. Can you guys provide me with some intuition what if it is ok to normalize, or if this indicates if the model is terribly wrong? Any ideas and insights are appreciated.
Answer: In word2vec or doc2vec implementations most values of cosine similarity are between -0.2 and 0.2. All vectors are similar with a few number of other vectors and dissimilar with the most. This is more plausible than the inverse, that is your skewness towards most similar values. Most vectors cannot be similar, because this would say that in a text there is not evident semantic difference between words.


eb config and .ebextensions/ - .ebextensions/ not working

Question: It is my understanding that editing the config via eb config and via .ebextensions/ both do the same thing. Using eb config directly changes the config were using .ebextensions/ changes the config but is scripted, thus repeatable.
Is this correct?
Initially, I usesed ebconf to change
aws:elasticbeanstalk:container:python:
    NumProcesses: '1'
    NumThreads: '15'
    WSGIPath: application

to
aws:elasticbeanstalk:container:python:
    NumProcesses: '1'
    NumThreads: '15'
    WSGIPath: project.wsgi # <-- change

which worked and I was able to run my application.
I then decided I wanted to do all my changes thru .ebextensions/.  I reverted the change made with eb config  and created the file .ebextensions/02_python.config which contains:
option_settings:
   "aws:elasticbeanstalk:container:python":
     WSGIPath: project.wsgi
     NumProcesses: 3
     NumThreads: 20
   "aws:elasticbeanstalk:environment:proxy:staticfiles":
     "/static/": "static/"

after eb deploy  all the chages are reflected when I do eb config except the WSGIPath value is not changed thus my app is no longer working.
Why is .ebextensions/02_python.config  not overwriting that one value?
Answer: Here is what I did to fix this issue.
eb config
delete WSGIPath: application
save and wait for reload
eb deploy
save and wait for reload
eb config
verify the changes from the file are made!


How to set property asynchronously using useEffect for later use in function within a React component?

Question: So here is the scenario, I have a property which I need to initialize using useEffect. The problem is, this property is also used within a function within my component.
So I have a situation, where the property shows up as undefined when the function is later called in the component, this is because by the time the function is being initialized, the asyncronous call that sets it in useEffect has not being finished yet.
  let myprop;

  useEffect(() => {
    const setUp = async (): Promise<void> => {
      myprop = initFuncThatReturnsAPromise;
    };

    void setUp();
  });

  const process = () => {
   // uses myprop for example
   myprop.call()
  }

process function is attached to a click event later on in the component. Problem now is, when the click event is clicked and process is executed, myprop is undefined. That is because it takes a while for the async function in useEffect to resolve and sets its value.
Any ideas on how to go around this?
Answer: Simply call the function conditionally, so that it is only called once the function exists:
const process = () => {
   // uses myprop for example
   myprop && myprop.call()
  }

Comment: unfortunately does not work. The myprop is always undefefined.


Installing couchbase in ubuntu 12.04

Question: I havent been able to start my newly installed couchbase-server_2.0.1. I've spent more that 2 hours trying to get couchbase-server work in my local machine.
By the way i'm using Ubuntu 12.04. I tried removing it using this command dpkg -r couch-server and even removing it using my Synaptic Package Manager then deleted couchbase folder located at /opt/ then reinstall it again. But same result always appear to me saying * Failed to start couchbase-server: timed out
Oh by the way I checked my RAM size and hard-drive capacity, im good in that side.
Any of you guys encountered this problem? This is taking a lot of my time. T__T
Comment: Where are you seeing this error? In your logs? Would you be willing to send your log file to Couchbase for us to take a look at? This sounds like a simple error, and should be easily overcome. Diagnosing it right now isn't strictly possible, as it could be a Firewall problem etc, but your log file should clear everything up for us.
Comment: Which raises an interesting point, @WonderingCoder, you should edit your question to include some bits of logfiles.
Answer: A couple of important things when installing CouchBase 2

Swappiness must be between 0 and 10... I run at 0
Ulimit -n must be bumped a bit. I run our servers at 16384

Between those 2 you should get a working server. I also would not run CouchBase alongside any other software

Installing couchbase in ubuntu 12.04


Disabling HTTPS in Axis2 web service

Question: I have created an Axis2 web service from Netbeans and deployed it successfully in Tomcat 6 on my web server.
When I use for instance SoapUI or Taverna to consume the web service, the server offers both HTTP and HTTPS methods to invoke it. However, using the HTTPS method renders a 404 error. (Probably because there is a server admin panel running on port 8443, but that doesn't matter right now.)
The problem is that my web service clients default to using the HTTPS service. I figured the simplest thing I could do to get the basic service to work, would be to disable the HTTPS endpoint, as the HTTP version runs flawlessly and I don't need the added security. But now I've spent hours on finding out how to do that, without success. The WSDL returned by Axis2 contains entries for HttpsSoap11Endpoint but the WSDL that's bundled in my .AAR file after the build does not.
Does anybody know how to make Axis2 offer just HTTP endpoints?
Comment: Try commenting out the https transport receiver in your axis2.xml
Comment: @karoberts - can you answer this question so it can be marked as "answered"?
Answer: In axis2.xml, comment out the https transport receiver to disable the HTTPS endpoint.

Disabling HTTPS in Axis2 web service


jQuery wont load

Question: Jquery wont load. I'm a noob, but have persisted, trawled this site & tried many things, permission settings, reloading java on my system & various syntax tweaks, but no joy. About to give up. Here's how it stands...
Using jquery on my hard drive, current version jquery-1.7.1 (also tried v1.7.1.min).
I have tried to use the following plugins - scrollTo-1.4.2-min, jqDock.min & jqDock, jtruncate (current) & jtruncate.pack. None work. I'm using IE8 and Chrome to check on local.
Debugging says...

(jquery-1.7.1.js) invalid character Line 1 (NB: line 1 is just the
  beginning of the credit info greyed out text  /*! )
  (jquery.jtruncate.js) jQuery is undefined Line 1 (NB: line 1 is
  (function(jQuery){  )   (my page name) Object doesnt support this
  property or method Code 0 Line 17 Char 5 (NB: line 17 is  $('').jTruncate({  )

My head code, (after meta's, UTF8 and title)...
$(document).ready(function(){
        $('
').jTruncate({
            length: 200,
            minTrail: 0,
            moreText: "[more]",
            lessText: "[less]",
            ellipsisText: "(truncated)",
            moreAni: "fast",
            lessAni: 2000
        });
    });

Then theres some java generated by Dreamweaver, (Rollover image/swap image guff), then page specific CSS  (see below) i also have site wide external css sheet.
    #statement {
        position:absolute;
        left:285px;
        right: 190px;
        top:130px;
        width: 607px;
        height: 321px;
    }

Then html body.
Can anyone help?  Cress
Comment: Can you show us your `` tags? Also, Java and JavaScript are two very different things.
Comment: Show your full source or create a simplified example HTML page (that you've tested) and show us that.
Comment: Cory, I have posted the full  section on other question page.
Comment: Sosukodo, I'm sorry, I'm not sure what to post for you, (I'm embaressed to say). The whole html to /html or specific elements? I also have an external css page, and the jquery's linked. Please find me on the other question page & i will delete this duplicate one. (a foolish noob mistake)
Comment: possible duplicate of [jQuery wont load](http://stackoverflow.com/questions/8625415/jquery-wont-load)
Answer: http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
$(document).ready(function(){
        $('body').append('
');
        $('#statement').css({
            length: 200,
            minTrail: 0,
            moreText: "[more]",
            lessText: "[less]",
            ellipsisText: "(truncated)",
            moreAni: "fast",
            lessAni: 2000
        });
    });

Comment: So I should be using jQuery v 1.4.2 and not v 1.7.1? I thought the most up to date version would be best?

jQuery wont load


Atualizador de uma aplicação web asp.net mvc

Question: eu estava aqui pensando em uma estrutura para atualização automática dos meus sistemas web em clientes, daí pensei em utilizar o ClickOnce com algumas gambetas(adaptações técnicas).
Não deu certo, ele funciona apenas para aplicações Windows-based.
Pensei em algo como um webservice no task scheduler pra verificar se a ultima versão do sistema é a mesma do servidor de publicação, se não, faz o download dela e atualiza.
O que acham? Alguém tem uma ideia/alternativa para uma solução?
Answer: Você já ouviu falar no framework Quartz .NET?
O Quartz .NET é um framework agendador open-source baseado no .NET. Parece ser uma ótima ferramenta. Nunca utilizei, mas segue alguns tutoriais de implementação.
Dê uma olhada, talvez isso te ajude!
Comment: De fato, parece ser uma boa ferramenta, mas no demais, digamos q poderia cumprir uma parte da solução que imaginei, o fato de substituir o task scheduler do windows.