How to choose the test statistic for permutation test?

Question: Is the purpose of permutation test to test the null that several groups of samples come from the same distribution?
I found its steps are

The steps in a permutation-based computation of the significance level
of a test statistic are as follows:
i) Choose a test statistic, eg. a t-score for a comparison of two groups,
ii) Compute the test statistic for the gene of interest,
iii) Permute the labels on samples at random, and re-compute the test statistic for the rearranged labels; repeat for a large number
(perhaps 1,000) permutations, and finally,
iv) Compute the fraction of cases in which the test statistics from iii) exceed the real test statistic from ii).

What kinds of test statistic should one choose in the first step?
The example uses the t-score, which measures the difference between two groups. But it seems to me that any statistic will work, not necessarily measuring the difference between two groups. Is it correct?
Answer: Often there are several statistics that will all result in the same p-value/result.  For example in a 2 sample case the difference of the 2 means, the mean of group A, and the sum of the values in group A will all result in the same p-value (this is because given the data values and sample sizes you can calculate the 1st 2 given only the 3rd).  I would expect the t statistic to be similar to any of the above, but may not be exactly the same (due to the dividing by standard deviation(s)).  There are other statistics that could be very different in the results, possibly the difference of the 2 medians, or the ratio of the 2 variances.  These other statistics will be affected differently by the permutation process.
Your choice should be based on a combination of what is most interesting based on the science and question being asked (sometimes medians might be of more interest, other times means would be) and what will give you power to detect a difference in reasonable/meaningful alternatives.  You can test this later by simulating data from cases that you think likely or interesting and watching how the statistics perform.
Comment: Yes, Tim: you can perform a permutation test on literally any statistic. Part of being a good statistician is knowing how to choose a statistic that actually measures the effect of interest. A harder part is knowing how to choose a statistic that will do a good job of identifying differences when they do exist and of failing to identify "significant" differences when no differences (of any meaningful size) are present. If you make up some arbitrary statistic you can always do a permutation test and get a p-value, but the meaningfulness of this procedure may be questionable.
Comment: @Tim, it depends on the statistic (and what you mean by measuring the difference).  The sum of values in group A is not directly measuring a difference, but works.  The ratio of variances might or might not be considered a difference and would probably not tell you much if the 2 distributions are just shifted in their centers (but identical variance and shape) but could be very meaningful in other cases.  The maximum value in group A would probably not tell you much, even the difference in the 2 maximums is probably not a good choice most of the time.
Comment: @Tim, the null hypothesis for a permutation test is that the distributions are identical, but there are many ways in which they can be non-identical, some more interesting than others, and the choice of test statistic will have more or less power for different types of non-identical.  This post (http://tolstoy.newcastle.edu.au/R/e4/help/08/04/8485.html) and the others in the thread and the paper referenced may be of interest.
Comment: Thanks, Greg! If the test statistic is not measuring difference between two groups, then does it still work technically?
Comment: @Greg: Thanks! Is the purpose of permutation test only to test the null that several groups of samples come from the same distribution?
Comment: @GregSnow: Thanks! I read your reply there, but still not quite sure about the following quesiton. If the test statistic is chosen to be the difference between the sample means of two groups, will permutation test be able to test the null that the two groups have equal mean (allowing the two groups have different variances)?
Comment: I posted a new question [here](http://stats.stackexchange.com/questions/60129/does-permutaton-test-change-the-null-hypothesis-of-the-original-test)
Answer: You choose a test statistic that measures what you're interested in/has the properties you need.
If you want to compare means, you base it on differences of means; if you want a robust comparison of location, you measure something else; if you want to compare standard deviations, you use a statistic that does that; if you want to compare the whole distribution you use a statistic that compares distributions (such as a k-sample version of the Kolmogorov-Smirnov test, for an example).


$X $~ $exp (0.5)$ and $Y$ ~ $exp (1)$. How can I calculate such probability?

Question: $X$ ~ $exp (0.5)$ and $Y$ ~ $exp (1)$.
X is the waiting time for the bus and Y is the waiting time for the taxi. Meaning half a bus is expected to arrive every 1 hour and 1 taxi is expected to arrive every 1 hour.
It is know that in $\frac{1}{3}$ of the days I take the taxi and in $\frac{2}{3}$ I take the bus. What is the probability that in a random day I took the bus, if it is known that I waited less than $1.2$ hours overall?
I first calculated $P(X < 1.2)$ but now I am not sure how to continue. How can I calculate the probability that.overall I waited less than $1.2$ hours? If I have that then I think I can get the solution
Comment: If I understand the question correctly, you're to compute $\Pr(X<Y|X<1.2)$.
Comment: Why? Can you explain please?
Comment: You take the bus if it arrives first (i.e. $X<Y$). And it's given that you wait less than 1.2 hours.
Comment: @yurnero : but $X < 1.2$ is not the same event than "waiting less than 1.2 hours". I would rather calculate $P( X < Y | \min (X,Y) < 1.2 )$
Answer: I think you are on the right track: the probability $P(X<Y|\min\{X,Y\}<1.2)$ is sought.
Set $A=\{\min\{X,Y\}<1.2\}$. By independence,
$$P(A)=P(X<1.2,Y<1.2)=P(X<1.2)P(Y<1.2).$$
Further, by the Law of Total Probability (disintegration),
$$P(\{X<Y\}\cap A)=\int_0^{1.2} P(X<y,X<1.2)dF_Y(y)=\int_0^{1.2} P(X<y)dF_Y(y),
$$
where $F_Y(y)$ is the c.d.f. of $Y$. At this point, explicit calculation of $$P(X<Y|A)=\frac{P(\{X<Y\}\cap A)}{P(A)}$$ is readily available.
Comment: $\min\{X,Y\}<1.2$ does not mean both are less than 1.2. Rather it means both cannot be greater. $$\mathsf P(\min\{X,Y\}<1.2) = 1-\mathsf P(X\geqslant 1.2)\mathsf P(X\geqslant 1.2)$$
Comment: Likewise. $$\begin{align}\mathsf P(X<Y\cap\min\{X,Y\}<1.2)&=\mathsf P(X<Y, X<1.2)\\&=\int_0^{1.2} \int_x^\infty f_X(x)\,f_Y(y)\,\mathrm d y\,\mathrm d x\\&=\int_0^{1.2} f_X(x)\,(1-F_Y(x))\,\mathrm d x\end{align}$$


is it possible to declare an user group for the remote user in aliases.drushrc.php

Question: I have a different user group for apache on my remote server clould i specify a group for drush sync like remote-user user adds the user or in some similar way
?
Answer: No; in unix, the group ownership is attached to the user.  Use usermod -a -G to add the desired group permanently to your remote user.  See man usermod for more information.


Simplifying modified Bessel function of the first kind

Question: The modified Bessel function of the first kind shows up in the normalizing constant of a lot of random variables (e.g. the normal product distribution, the noncentral chi-square distribution, the Skellam distribution, and the von Mises distribution). This is its formula (NB: this is false...see answer below):
$$
J_k(x) = \sum_{m=0}^{\infty} \frac{(-1)^m}{m!\Gamma(m+k+1)}\left(\frac{x}{2}\right)^{2m+k}
$$
How can we simplify this thing? Because I am interested in Skellam distributions in particular, I am interested in the case where $k$ is a possibly-negative integer, and $x$ is positive.
This thing appears to depend on evaluations of the Gamma function at negative values, which can take on the value complex infinity. However, the wiki page for the Skellam distribution mentions that the Bessel function with a negative integer $k$ will be equal to the Bessel function with the absolute value of that integer as a subscript. Why is this?
Answer: Actually, that formula above is not for the modified Bessel function of the first kind, it is for the (non-modified) Bessel function of the first kind! Furthermore, the Encyclopedia of Mathematics has an entry on this (non-modified) Bessel functions, and points out that, for $n \in \mathbb{N}$ and $z \in \mathbb{C}$
$$
J_{-n}(z) = (-1)^nJ_n(z) \tag{1}
$$
even though that the formula typically given is not technically correct:

...the formulas in (1) are not "strictly-speaking" well-defined
  because the $\Gamma$ function has poles in all negative integers.
  However, given the Laurent series of $\Gamma$ at such poles and the
  fact that the function appears in the denominators of fractions, the
  formula in (1) can be reinterpreted...

The correct formula is
$$
I_n(x) = i^{-n} J_{n}(ix) \tag{2}
$$
for $n \in \mathbb{N}$ and $x \in \mathbb{R}$, and it doesn't have that alternating sign situation.
Using (1) and (2), and assuming $n \ge 0$ for the time being without loss of generality,
\begin{align*}
I_{-n}(x) &= i^n J_{-n}(ix) \\
&= (-i)^n J_n(ix) \\
&= (i)^{-n} J_n(ix) \\
&= I_n(x).
\end{align*}
This first clicked for me when I read an answer on another stackexchange cite, which can be found by clicking on this.


Two congruence systems with a parameter - answer verification

Question: Given two systems of congruences with one common parameter $A$ I need to find all values of $A$ for which both systems have the same solution sets.
The systems are:
$$x\equiv5\bmod6\\x\equiv A\bmod35$$and$$x\equiv A\bmod10\\x\equiv 14\bmod21$$
I solved it by first finding x in both systems, by CRT and then since the answers were both $\bmod 210$ I equated both solutions with that modulus and solved for $A$.
From the first system I got $x\equiv36A+35\bmod210$, and from the second one $x\equiv21A-70\bmod210$. Equating the $x$'s I got $A\equiv3\bmod6$. Is it correct? And what would I have to do if the moduli weren't equal? Would finding the LCA and multiplying both solutions be correct?
Comment: For $A=3$, the expressions $36A+35$ and $21A-70$ are not congruent modulo $210$ . $A\equiv 7\mod 14$ seems to be correct.
Comment: @Peter Thanks, I double-checked it again and now I got your answer.
Comment: The solutions of the systems are correct
Comment: The case where the moduli are not equal : If they are coprime, you can apply CRT again, have to think about the remaining case
Answer: There is an error somewhere. It is simpler to split into prime moduli using CRT:
$\qquad \begin{align}
x\equiv\, \color{#c00}1\!\!\!\pmod 2,\ &\ 2\!\!\!\pmod 3,\ A\!\!\!\pmod 5,\ \color{#0a0}A\!\!\!\pmod 7\\
x\equiv \color{#c00}A\!\!\!\pmod 2,\ &\ 2\!\!\!\pmod 3,\ A\!\!\!\pmod 5,\ \ \color{#0a0}0\!\!\!\pmod 7
\end{align}$
By CRT these are equivalent  $\iff \color{#c00}A\equiv \color{#c00}1\pmod 2,\ \color{#0a0}A\equiv \color{#0a0}0\pmod 7\,$
Solving we find  $\bmod 2\!:\,\ 1\equiv A\equiv 7k\equiv k\,$ so $\, A = 7k = 7(1\!+\!2n) = 7\!+\!14n$
Comment: @Joald Yes, because  by CRT the split systems are equivalent to the originals, and the two completely split systems are equivalent iff they have the same prime moduli and same remainders for each prime, again by CRT. Think about that carefully to be sure you understand how it follows from CRT.
Comment: Does this method always find every possible solution, and if so, why?


Two non-isomorphic modules that are isomorphic groups

Question: Can you give me a concrete example of two modules over a ring $R$ that are not isomorphic , but that are isomorphic as abelian groups.
I know that this question was posted here before, but the answer given was not a concrete example and I would like to see one.
Comment: They aren't isomorphic as $\Bbb{R}$-vector spaces, i.e. modules, since a module over a field is a vector space...
Comment: @A.P. http://math.stackexchange.com/questions/245158/isomorphic-abelian-groups-which-are-not-isomorphic-r-modules
Comment: Could you post a link to the question you mentioned, please? Also, it would be helpful if you could specify what you mean by "concrete" example...
Comment: I mean an example of modules
Comment: Andrew's answer from that question seems very concrete to me...
Comment: @A.P. But I never had dual numbers over a field
Comment: Ok, then what is wrong with Mariano's answer? He says that "$\Bbb{R}$ is an infinite dimensional $\Bbb{Q}$-vector space, so a direct sum of finitely many copies (or countabl[y] many) of $\Bbb{R}$ is isomorphic to $\Bbb{R}$ as a $\Bbb{Q}$-vector space, and therefore as an abelian group." Surely you've seen the fields of real and rational numbers in your studies?
Comment: @A.P. But why arent they isomorphic as modules?
Comment: Do you know what the trivial $R$-module over the group $G$ is? Then let $(R,G)$ be your favourite nontrivial module. The two have isomorphic underlying groups but are not isomorphic as modules.
Comment: @TonyStrong, I just added another answer to the question you linked to.
Answer: Let $R=KG$ with $K$ a field (with char $K \ne 2$) and $G$ cyclic of order two, and let $M_1$ and $M_2$ be the trivial and nontrivial $1$-dimensional (over $K$) $KG$-modules. So, in $M_2$, $G$ acts by multiplying by $-1$.
Comment: Can you also explain why they arent isomorphic as modules, but they are as abelian groups?
Comment: This feels *a lot* like a joke... :)
Comment: @A.P. why does this feel like a joke?
Comment: Because in the comments the OP said that he's never seen dual numbers, and in your answer you are using modules over a group algebra.


Why does the natural filtration induce a brownian motion

Question: I am reading up on the brownian motion right now and there is sometthing claimed in my textbook that I don't understand.
Let $(B_t)_t$ be a Brownian motion with respect to some filter. Now define the natural filtration of $(B_t)_t$ as $\mathcal{F}_t = \sigma (B_s : 0 \leq s \leq t)$ for $t \geq 0$. Then $(B_t)_t$ is also a Brownian motion with respect to $(\mathcal{F}_t)_t$.
I think the only property that needs checking is that for $0 \leq s \leq t$ the increment $B_t-B_s$ is independent of $\mathcal{F}_s$. But why is this true? Since there is no proof I think this should be trivial, but I can't see how.
Answer: The proof depends mainly on properties of multivariate normal distributions.
If $t_1 <t_2<...<t_k \leq s$ then $B_t-B_s,B_{t_1},B_{t_2},...,B_{t_k}$ have a multivariate normal distribution. Since then covariance of $B_t-B_s$ with the other variables are $0$ it follows that $B_t-B_s$ is independent of $\{B_{t_1},B_{t_2},...,B_{t_k}\}$ and this being true for all choices of $t_i$'s it follows that $B_t-B_s$ is independent of $\mathcal F_s$.


How to move on to the next profile page in views after flagging a profile within the view?

Question: I created a view that current user can use to search/view user profiles. The view lists user profiles and shows one at a time. A profile page can be either flagged "Like" or "Pass" (dating website style). I want the next profile to load after the current user flags the profile they are viewing.
Comment: "Write some code" is technically an answer to this question. What research have you done?
Answer: You can add a is/is not flagged filter to the view.  If you don't see this option, you need to add your flag as a relationship to the view to get the filter to appear.
So, if you have configured the view to only show unflagged users, then if you're using the AJAX flag widget, I'm pretty sure it will automatically refresh the view and jump to the next person.
If not, you will have to write code to get it to refresh after each flag action.
Comment: The method actually works. I just didn't do it properly. I needed to add three flag relationships to select each flag, then add three filters and select each of the flag relationship I added. Thanks again for the help.
Comment: Thank you, I did exactly this yesterday and it worked for my flag "Like". However, I have three flags on the profile "Like", "Pass", or "Abuse" and I want the same thing to happen when the profile is flagged "Pass" or "Abuse". I added two additional flag relationships to the view since you can only select one flag in a relationship, but it didn't work for "Pass" and "Abuse". The profile does not get removed from the list when "Pass" or "abuse" flag is used. Been researching and I haven't found a solution so far.
Comment: @Dee The fact that there are multiple flags needs to be in the question :). You can probably handle that by adding an OR condition group and adding all three flag filters to that condition group.


How do I draw ghost notes in ABC notation?

Question: Fairly straightforward question. I can't seem to find it in the standard or the docs. Perhaps it's just a matter of terminology.
Basically, what I'm looking for is this:

Or, more precisely, the ghost notes as written down for drums - a note head in parentheses.
Source:
Wikipedia,
Image
Answer: According to section 4.19 Annotations of the ABC Standard, you can place parentheses around a note with the following code:
"<(" ">)" C
For example,
X:0
M:none
K:none
"<("">)"C2

Comment: Oh, thank you! I have used this at some point but could not find the example. I'm actually preparing some demos for the common drumset notation, using abcjs.


some http packets not reaching host

Question: we are experiencing a very strange issue with http traffic between 2 machines on the same network: when sending an HTTP request there are some packets not reaching the other host as you can see from the tcpdump. Does anybody have an idea as to what could cause such a problem and what tests can we do to troubleshoot it?
Thank you in advance.
server A (x.x.x.67):
10:52:54.766961 IP x.x.x.67.46526 > x.x.x.51.http: Flags [S], seq 3933450573, win 29200, options [mss 1460,sackOK,TS val 1799470837 ecr 0,nop,wscale 7], length 0
10:52:54.767169 IP x.x.x.51.http > x.x.x.67.46526: Flags [S.], seq 2443943736, ack 3933450574, win 14480, options [mss 1460,sackOK,TS val 2928651146 ecr 1799470837,nop,wscale 7], length 0
10:52:54.767185 IP x.x.x.67.46526 > x.x.x.51.http: Flags [.], ack 1, win 229, options [nop,nop,TS val 1799470838 ecr 2928651146], length 0
10:52:54.767310 IP x.x.x.67.46526 > x.x.x.51.http: Flags [P.], seq 1:242, ack 1, win 229, options [nop,nop,TS val 1799470838 ecr 2928651146], length 241
10:52:54.967964 IP x.x.x.67.46526 > x.x.x.51.http: Flags [P.], seq 1:242, ack 1, win 229, options [nop,nop,TS val 1799471039 ecr 2928651146], length 241
10:52:55.168969 IP x.x.x.67.46526 > x.x.x.51.http: Flags [P.], seq 1:242, ack 1, win 229, options [nop,nop,TS val 1799471240 ecr 2928651146], length 241
10:52:55.571973 IP x.x.x.67.46526 > x.x.x.51.http: Flags [P.], seq 1:242, ack 1, win 229, options [nop,nop,TS val 1799471643 ecr 2928651146], length 241
10:52:55.948432 IP x.x.x.51.http > x.x.x.67.46526: Flags [S.], seq 2443943736, ack 3933450574, win 14480, options [mss 1460,sackOK,TS val 2928652328 ecr 1799470837,nop,wscale 7], length 0
10:52:55.948455 IP x.x.x.67.46526 > x.x.x.51.http: Flags [.], ack 1, win 229, options [nop,nop,TS val 1799472019 ecr 2928651146], length 0
10:52:56.376977 IP x.x.x.67.46526 > x.x.x.51.http: Flags [P.], seq 1:242, ack 1, win 229, options [nop,nop,TS val 1799472448 ecr 2928651146], length 241
10:52:57.948432 IP x.x.x.51.http > x.x.x.67.46526: Flags [S.], seq 2443943736, ack 3933450574, win 14480, options [mss 1460,sackOK,TS val 2928654328 ecr 1799470837,nop,wscale 7], length 0
10:52:57.948451 IP x.x.x.67.46526 > x.x.x.51.http: Flags [.], ack 1, win 229, options [nop,nop,TS val 1799474019 ecr 2928651146], length 0
10:52:57.988966 IP x.x.x.67.46526 > x.x.x.51.http: Flags [P.], seq 1:242, ack 1, win 229, options [nop,nop,TS val 1799474060 ecr 2928651146], length 241
10:52:59.780422 ARP, Request who-has x.x.x.67 tell x.x.x.51, length 46
10:52:59.780437 ARP, Reply x.x.x.67 is-at x:x:x:x:x:1f, length 28
10:53:01.208971 IP x.x.x.67.46526 > x.x.x.51.http: Flags [P.], seq 1:242, ack 1, win 229, options [nop,nop,TS val 1799477280 ecr 2928651146], length 241
10:53:01.948448 IP x.x.x.51.http > x.x.x.67.46526: Flags [S.], seq 2443943736, ack 3933450574, win 14480, options [mss 1460,sackOK,TS val 2928658328 ecr 1799470837,nop,wscale 7], length 0
10:53:01.948459 IP x.x.x.67.46526 > x.x.x.51.http: Flags [.], ack 1, win 229, options [nop,nop,TS val 1799478019 ecr 2928651146], length 0
10:53:07.657010 IP x.x.x.67.46526 > x.x.x.51.http: Flags [P.], seq 1:242, ack 1, win 229, options [nop,nop,TS val 1799483728 ecr 2928651146], length 241
10:53:07.657235 IP x.x.x.51.http > x.x.x.67.46526: Flags [.], ack 242, win 122, options [nop,nop,TS val 2928664036 ecr 1799483728], length 0
10:53:07.785710 IP x.x.x.51.http > x.x.x.67.46526: Flags [.], seq 1:1449, ack 242, win 122, options [nop,nop,TS val 2928664165 ecr 1799483728], length 1448
10:53:07.785722 IP x.x.x.67.46526 > x.x.x.51.http: Flags [.], ack 1449, win 251, options [nop,nop,TS val 1799483856 ecr 2928664165], length 0
10:53:07.785884 IP x.x.x.51.http > x.x.x.67.46526: Flags [P.], seq 1449:2105, ack 242, win 122, options [nop,nop,TS val 2928664165 ecr 1799483856], length 656
10:53:07.785891 IP x.x.x.67.46526 > x.x.x.51.http: Flags [.], ack 2105, win 274, options [nop,nop,TS val 1799483856 ecr 2928664165], length 0
10:53:07.785977 IP x.x.x.67.46526 > x.x.x.51.http: Flags [F.], seq 242, ack 2105, win 274, options [nop,nop,TS val 1799483857 ecr 2928664165], length 0
10:53:07.791437 IP x.x.x.51.http > x.x.x.67.46526: Flags [F.], seq 2105, ack 243, win 122, options [nop,nop,TS val 2928664171 ecr 1799483857], length 0
10:53:07.791447 IP x.x.x.67.46526 > x.x.x.51.http: Flags [.], ack 2106, win 274, options [nop,nop,TS val 1799483862 ecr 2928664171], length 0

server B (x.x.x.51):
10:52:54.769644 IP x.x.x.67.46526 > x.x.x.51.http: Flags [S], seq 3933450573, win 29200, options [mss 1460,sackOK,TS val 1799470837 ecr 0,nop,wscale 7], length 0
10:52:54.769666 IP x.x.x.51.http > x.x.x.67.46526: Flags [S.], seq 2443943736, ack 3933450574, win 14480, options [mss 1460,sackOK,TS val 2928651146 ecr 1799470837,nop,wscale 7], length 0
10:52:55.950929 IP x.x.x.51.http > x.x.x.67.46526: Flags [S.], seq 2443943736, ack 3933450574, win 14480, options [mss 1460,sackOK,TS val 2928652328 ecr 1799470837,nop,wscale 7], length 0
10:52:57.950927 IP x.x.x.51.http > x.x.x.67.46526: Flags [S.], seq 2443943736, ack 3933450574, win 14480, options [mss 1460,sackOK,TS val 2928654328 ecr 1799470837,nop,wscale 7], length 0
10:52:59.782918 ARP, Request who-has x.x.x.67 tell x.x.x.51, length 28
10:52:59.783093 ARP, Reply x.x.x.67 is-at x:x:x:x:x:1f, length 46
10:53:01.950939 IP x.x.x.51.http > x.x.x.67.46526: Flags [S.], seq 2443943736, ack 3933450574, win 14480, options [mss 1460,sackOK,TS val 2928658328 ecr 1799470837,nop,wscale 7], length 0
10:53:07.659702 IP x.x.x.67.46526 > x.x.x.51.http: Flags [P.], seq 1:242, ack 1, win 229, options [nop,nop,TS val 1799483728 ecr 2928651146], length 241
10:53:07.659726 IP x.x.x.51.http > x.x.x.67.46526: Flags [.], ack 242, win 122, options [nop,nop,TS val 2928664036 ecr 1799483728], length 0
10:53:07.788181 IP x.x.x.51.http > x.x.x.67.46526: Flags [.], seq 1:1449, ack 242, win 122, options [nop,nop,TS val 2928664165 ecr 1799483728], length 1448
10:53:07.788374 IP x.x.x.67.46526 > x.x.x.51.http: Flags [.], ack 1449, win 251, options [nop,nop,TS val 1799483856 ecr 2928664165], length 0
10:53:07.788381 IP x.x.x.51.http > x.x.x.67.46526: Flags [P.], seq 1449:2105, ack 242, win 122, options [nop,nop,TS val 2928664165 ecr 1799483856], length 656
10:53:07.788536 IP x.x.x.67.46526 > x.x.x.51.http: Flags [.], ack 2105, win 274, options [nop,nop,TS val 1799483856 ecr 2928664165], length 0
10:53:07.788614 IP x.x.x.67.46526 > x.x.x.51.http: Flags [F.], seq 242, ack 2105, win 274, options [nop,nop,TS val 1799483857 ecr 2928664165], length 0
10:53:07.793955 IP x.x.x.51.http > x.x.x.67.46526: Flags [F.], seq 2105, ack 243, win 122, options [nop,nop,TS val 2928664171 ecr 1799483857], length 0
10:53:07.794094 IP x.x.x.67.46526 > x.x.x.51.http: Flags [.], ack 2106, win 274, options [nop,nop,TS val 1799483862 ecr 2928664171], length 0

Comment: What about `ifconfig` error counters?
Answer: It can be a MTU-related problem.
To test, try lowering your MTU on both servers issuing the command ifconfig <ifname> mtu 580
This should be only viewed as a workaround, though. If that solves the problem, restore the original MTU (issuing ifconfig <ifname> mtu 1500 and check with your firewall admin / ISP why larger packet are dropped.
Comment: hi, thank you for the input. I tried to lower the mtu on both machines and run the request again but the problem still remains.

some http packets not reaching host


Como posso usar a nova API de datas do Java 8?

Question: Gostaria de saber como compilo no meu Gradle Build para ficar disponível a nova API de datas do java 8 no meu android studio
Comment: Vê se ajuda: http://stackoverflow.com/a/21212790/2570426
Comment: Amigo, a pergunta como formulada atualmente está extremamente vaga, por gentileza [leia como fazer uma pergunta adequada](http://pt.stackoverflow.com/help/how-to-ask) e forneça mais detalhes a cerca do seu projeto, o que você já fez e qual seu nível de conhecimento a respeito. Sem isso, o máximo que vão poder te fornecer é um *negativo* e talvez, alguns links.
Comment: Cara, a pergunta é bem simples e direta. Atualmente eu uso o estilo de datas Date e Calendar no android studio, e quero apenas o 'compile' para ficar disponivel a nova API de datas do Java 8. Simples
Comment: Ack Lay, o que eu quero é exatamente saber como configuro meu gradle para ser compativel
Answer: Edição 2020/06/01
Com o Android Studio 4.0 e Android Gradle plugin 4.0.0 o suporte para Java 8 foi estendido, permitindo usar mais Api's sem requer um nível de API mínimo.
Para habilitar o suporte a essas APIs é necessário incluir, no build.gradle, o seguinte:
android {
  defaultConfig {
    // Required when setting minSdkVersion to 20 or lower
    multiDexEnabled true
  }

  compileOptions {
    // Flag to enable support for the new language APIs
    coreLibraryDesugaringEnabled true
    // Sets Java compatibility to Java 8
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

dependencies {
  coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.5'
}

Lista de Api's suportadas.

Edição 2019/04/27
A java.time está disponível a partir da APi 26.
Requere compileSdkVersion >= 26 e minSdkVersion >= 26

Edição 2017/11/10
Se estiver a usar o Android Studio 3.0 configure o seu build.gradle da seguinte forma:
android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

Para mais informações veja Use Java 8 Language Features.

O Android não suporta todas as características do Java 8 e a maior parte das que suporta só podem ser usadas no desenvolvimento de aplicação para Android 7(API 24).
Características suportadas:(em qualquer API level)

Default and static interface methods
Lambda expressions
Repeatable annotations
Method References
Type Annotations

Reflexão e APIs relacionadas à linguagem:(API level 24 ou superior)

java.lang.FunctionalInterface
java.lang.annotation.Repeatable
java.lang.reflect.Method.isDefault()

APIs utilitárias:(API level 24 ou superior)

java.util.function
java.util.stream

Como pode verificar a API de datas do Java 8 não está incluída nas APIs suportadas e portanto não a pode usar.
Se no entanto quiser utilizar os outros recursos do Java 8 configure o seu build.gradle da seguinte forma:
android {
  ...
  defaultConfig {
    ...
    jackOptions {
      enabled true
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

Answer: Acho que nenhuma das respostas atende ao OP, dado que ele tem interesse na JSR 310, que é a nova API para trabalhar com datas sem ter que se estressar lidar com as classes Date e Calendar do Java.
Acredito que usar a compatibilidade do Java 8 dada pelo finado Jack não fornece a JSR 310.
Minha sugestão é ir para suas versões portadas, ou seja, usar o Joda Time ou o ThreeTen ABP, sendo que eu tenho recomendado mais a segunda opção.
Segue a documentação da Three Ten ABP e a documentação da Joda Time
Você poderá usar facilmente adicionando a dependëncia do Gradle:
dependencies {
    compile 'net.danlew:android.joda:2.9.7'
}

ou
dependencies {
    compile 'com.jakewharton.threetenabp:threetenabp:1.0.5'
}

Comment: Muito Obrigado! Era realmente isso :D
Answer: Para ativar os recursos de linguagem do Java 8 e o Jack para seu projeto, insira o seguinte código abaixo no arquivo build.gradle de nível do módulo. O sourceCompatibility e targetCompatibility. Veja como deve ficar:
android {
  ...
  defaultConfig {
    ...
    jackOptions {
      enabled true
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

Veja mais detalhes para uso de recursos de linguagem do Java 8 na documentação.
Nota: Só é possível usar os recursos do Java 8 no Android Studio 2.1 ou superior.


Plone4 with Nginx - Links are opening in a new page

Question: I have a Plone4 and Nginx working on the same server (CentOS6).
Nginx is working fast but all links on the Plone site received a target="_blank" attribute.
All the links are opening in a new window when using Nginx.
I open the same Plone site using the Zope webserver or via apache and the problem disapear.
I tried different configurations but I cannot get the correct links.
How can I solve this?
My current Nginx configuration is:
add_header X-Frame-Options "SAMEORIGIN";
add_header Strict-Transport-Security "max-age=15768000; includeSubDomains";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
#add_header Content-Security-Policy "default-src 'self'; img-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'";
add_header Content-Security-Policy-Report-Only "default-src 'self'; img-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'";

upstream plone {
    server 127.0.0.1:8080;
}

server {
    listen 80;
    server_name mywebsite.com;
    rewrite ^/(.*) http://www.mywebsite.com/$1 permanent;
}

server {
    listen 80;
    server_name www.mywebsite.com;
    access_log /var/log/nginx/mywebsite.com.access.log;
    error_log /var/log/nginx/mywebsite.com.error.log;

    location / {
        #proxy_pass http://plone/VirtualHostBase/http/mywebsite.com:80/mywebsite/VirtualHostRoot/;
        rewrite ^/(.*)$ /VirtualHostBase/http/mywebsite.com:80/mywebsite/VirtualHostRoot/$1 break;
        proxy_pass http://127.0.0.1:8080/;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Comment: I understood that, but the case still IS that nginx does _not_ add any such attributes to the HTML code, unless you enable content modification modules and add specific rules for it to do that. It simply gets HTML code from Plone, and sends it to clients.
Comment: nginx does nothing to the page contents. It is something in your Plone that is adding those `target=_blank` attributes to your links.
Comment: Thanks for your answer Tero, but it only happens when the site is viewed via Nginx. If I open the same site using apache or Plone  webserver it works fine. :(
Answer: It could have somthing to to with your urls.
Plone open external urls in new window if enabled.
Check your rewrite rule:
rewrite ^/(.*)$ /VirtualHostBase/http/mywebsite.com:80/mywebsite/VirtualHostRoot/$1 break;

i think it shopuld be:
rewrite ^/(.*)$ /VirtualHostBase/http/www.mywebsite.com:80/mywebsite/VirtualHostRoot/$1 break;

Comment: I don't know why but in fact Nginx just added the "target" attribute due to the wrong code.  I forgot to add the www in the domain and it makes sense.  Thank you MrTango you are the best!  :)))
Comment: Thats not the nginx, Plone does that. Plone has a Javascript, which looks for URL's different to current. And your nginx config was not complete, so that Plone was thinking, that every link is an external link and add a target="_blank" to it.


How many sequences of lenght 2n, made of n "+1"s and n "-1"s and such that every partial summation of the first k terms is nonnegative, are there?

Question: What's the number of sequences
$$(u_{1},...,u_{2n})$$
with $u_{i}=+1,-1$, such that:
$$\sum_{j=1}^{2n} u_{j}=0\quad\hbox{and}\quad \sum_{j=1}^{k} u_{j}\geq 0$$
I realized that $u_{1}=+1$ and $u_{2n}=-1$, but I don't know how to proceed...
Answer: The sequences so defined are Dyck words of lenght 2n and it has been proved (by Désiré André in 1887) that they are in number of $$C_n=\frac{1}{n+1}{2n\choose n} = \frac{(2n)!}{(n+1)!\,n!},$$
the nth Catalan number.
Comment: I didn't know the answer: the deleted one of a user here, who suggested me to check for Catalan numbers, was quite useful.
Comment: So you actually know the answer, but yet you asked.  If you simply googled it, you would find a proof very easily.  For example, http://mathcircle.berkeley.edu/BMC6/pdf0607/catalan.pdf.


Suppose that $f(x,y) \leq f(y,x)$ for all $(x,y)\in\textbf{R}^{2}$. Show that $f(x,y) = f(y,x)$ for all $(x,y)\in\textbf{R}^2$

Question: The question is: Suppose that $f(x,y) \leq f(y,x)$ for all $(x,y)$ in $\textbf{R}^{2}$. Show that $f(x,y) = f(y,x)$ for all $(x,y)\in\textbf{R}^{2}$.
I tried searching this question, but all the things I found were about convex functions. We did not learn about that, or partial derivatives yet. The section this is in only encompasses limits of functions of two variables. I am wondering if the professor want us to use the squeeze theorem somehow to show it. Any explanation is greatly appreciated.
Comment: Welcome to Mathematics Stack Exchange.  $f(x,y)\le f(y,x)\le f(x,y)$ means $f(x,y)=f(y,x)$
Comment: What happens if you interchange the symbols $x$ and $y$?
Comment: Applying the rule with, say, $x = 1$ and $y = 2$ gives us $f(1, 2) \le f(2, 1)$. If we apply it again with $x = 2$ and $y = 1$, then $f(2, 1) \le f(1, 2)$. Combined, this yields $f(1, 2) = f(2, 1)$. Note how there isn't anything special about $1$ and $2$.
Comment: If it's true for all $(x,y)\in \mathbb R^2$ then it is true for any $(x,y)\in \mathbb R^2$.  And if $(x,y)\in \mathbb R^2$ then $(y,x)\in \mathbb R^2$.  So it is true for any and all $(y,x)$ as well.  So we always have $f(x,y) \le f(y,x)$ but we also have $f(y,x) \le f(y,x)$ because if $(x,y) \in \mathbb R^2$ then $(y,x)\in \mathbb R^2$.
Answer: If $f(x,y) \leq f(y,x)$ for all $(x,y)$ in $\textbf{R}^{2},$
then taking $(x,y)=(a,b)$ we have $f(a,b)\le f(b,a),$
and taking $(x,y)=(b,a)$ we have $f(b,a)\le f(a,b)$.
So for all $a,b\in \textbf R, $ we have $f(a,b)\le f(b,a)\le f(a,b)$.
Now if $f(a,b)<f(b,a)$,
then we would have $f(a,b)<f(a,b),$ which is absurd.
So it must be that $f(a,b)=f(b,a)$ for all $a,b\in \mathbf R.$
Answer: The thing is if something is true for all $(x,y)$ then it is true if we simply swap the positions of $x$ and $y$ and it will be true for $(y,x)$ as well.
If it helps you can put a second pair of variables in.  If it's true for any $x=x', y=y'$ then $f(x',y') \le f(y',x')$.  But then it is also true for $x=y'$ and $y=x'$ so $f(y',x') \le f(y',x')$.
But you shouldn't have to do that.
If $f(x,y) \le f(y,x)$ for all $x,y$ then $f(y,x) \le f(x,y)$ as well.
So $f(x,y) \le f(y,x) $ and $f(y,x) \le f(x,y)$ for all $x,y$ so $f(y,x) =f(x,y)$ for all $x, y$.


jQuery UI - prevent Shake effect being fires multiple times

Question: just added some shake effect when user submit form on the inputs that not being full.
But when user press many times on submit button the shake effect fired many times.
How can I prevent it from being fired more than one time?
stop() - not workings.
clearQueue() - stop it even if it moves from it's first place in the page.
This is what I came with:
$(this).effect("shake");

Thanks :)
Answer: if you can use an extra variables you can use a flag:
first_submit = true

if(first_submit){
  first_submit = false
  $(this).effect("shake");
}

Answer: You could create a variable to set the effect is active (running). When your submit call is intercepted by a callback you verify if it's true, if yes you return. Preventing from another call.
In the effect callback (success) you set the variable false, for example. That's the cycle.
I have added an extension for the effect to callback it's success, look here: What is the true way of adding callback functionality to custom JQuery Animation?
Something like:

// Your new control
var active = false;

// Extending callback functionality to the animation
$.fn.shake = function ( times, distance, duration, callback ) {
    return this.css({ position: 'relative' }).each( function () {
        for ( var i = 0, t = duration / times; i < times; i+= 1 ) {
            $( this ).
                animate({ left: -distance }, t / 3 ).
                animate({ left:  distance }, t / 3 ).
                animate({ left:         0 }, t / 4 );
        }

        $( this ).show( callback );
    });
};

// DOM load
$(document).ready(function(){

  // Triggering form the event
  $('#form_ID').submit({function(){

    if(active == true)
      return false;

    // trigger your event..
    shake(5, 10, 500, function () {
        $('#your_component_ID').removeClass( 'shaking' );
    });
  });
});

I guess you could take a look in this post too: jQuery prevent multiple clicks until animation is done


Where to see the result of hook_menu()

Question: What is the purpose of hook_menu(), if I can create menus from the administration pages?
function onthisdate_menu() {
  $items = array();

  $items['blog'] = array(
    'title' => 'blogs',
    'description' => 'Listing of blogs.',
    'page callback' => 'blog_page',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  $items['blog/feed'] = array(
    'title' => 'RSS feed',
    'page callback' => 'blog_feed',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

so now where do I see the result of this function in the admin panel or in the site where the module is rendering?
Comment: are the keys of the arrays an url to add to the menu url in the admin panel?
Comment: looks like yes :)
Answer: hook_menu() is the method used by modules to add their own menu items. Most of the menu items you see on Drupal are added by modules with that hook.
The user interface allows you to add extra menu items that are not added by modules.
If you are asking the difference between creating a module that adds menu items with hook_menu(), and adding menu items with the user interface, hook_menu() allows to do things that are not possible with the user interface. For example, the menu that is visible when you hover the gear icon visible for a block is created with menu items added with  hook_menu(). (It requires the Contextual links module, which is a Drupal core module.)

The tabs that you see, for example, on a node page, are created with hook_menu(), or hook_menu_alter(). You could not create them with the user interface.

What you can create with the user interface are links that go:

In a menu block

In the Menu links

In the Secondary links
Answer: it depend on the type. if it is MENU_CALLBACK, then it would not be displayed anywhere; it would be just an internal link.
On the other hand, if it is MENU_NORMAL_ITEM, it would be displayed in the navigation menu, in the appropriate place depending on the path; for example, if the path is admin/config/regional/language/configure, it would end up as tab for the Languages page.
See also the documentation page for hook_menu().
Answer: Basically, the hook_menu() is a way to legitimize a URL within your site. For example you, might need to set up a URL for your AJAX where you'd process data, such as /my-application/get-ajax-data. You do that with hook_menu - the key for $items array is the path you want to define.
The name of the hook may certainly be misleading, as the result might not necessarily be a menu item. But this is how you tell Drupal "Hey, this URL is authorized, no fear to go there." Of course - as it shows in the code you provided - there's the whole access control over it.

Where to see the result of hook_menu()


tkinter - passar argumento para a função

Question: Tenho o seguinte código:
class Tela:
    def __init__(self, master=None):
        self.fontePadrao = ("Arial", "10")
        master = Toplevel(self.root)
        self.primeiroContainer = Frame(master)
        self.primeiroContainer["pady"] = 10
        self.primeiroContainer["padx"] = 30
        self.primeiroContainer.pack()

        self.segundoContainer = Frame(master)
        self.segundoContainer["pady"] = 10
        self.segundoContainer.pack()

        self.titulo = Label(self.primeiroContainer, text="Client")
        self.titulo["font"] = ("Arial", "10", "bold")
        self.titulo.pack()

        self.btnMessage = Button(self.segundoContainer)
        self.btnMessage.pack(side=LEFT)
        self.btnMessage["text"] = "imprimir mensagem"
        self.btnMessage["font"] = ("Calibri", "10")
        self.btnMessage["width"] = 15
        self.btnMessage["command"] = self.printMessage("Olá!")
        self.btnMessage.pack()

    def printMessage(message):
        print(message)

Mas não consigo passar o argumento para a função... como devo fazer?
Comment: Qual função você se refere?
Comment: Me refiro a função printMessage()
Comment: Ela é um método, por isso ela não deveria receber `self` como primeiro parâmetro, assim como fez em `__init__`?
Comment: Ops, eu vi isso agora também, e corrigi. Mas o meu problema aqui é que da forma como está, quando o programa executa ele já chama essa função. Mas quero que ela seja chamada apenas quando eu clicar no botão. Sem passar os parametros e deixando uma mensagem chumbada la, ele funciona. ai na hora de chamlar la pelo botão, eu coloca apenas printMessage, sem os parênteses.
Answer: Você fez
self.btnMessage["command"] = self.printMessage("Olá!")

Que basicamente está atribuindo o retorno da função self.printMessage como comando. Como ela não possui retorno, será atribuído o valor None. Porém, é esperado que você passe como comando um objeto chamável e a ideia é que quando esse objeto for chamado a mensagem seja exibida.
Para tal, você pode utilizar a função functools.partial que cria um novo objeto chamável e que você consegue definir os valores dos parâmetros:
from functools import partial

...
self.printMessage = partial(self.printMessage, "Olá!")

Assim, o retorno de partial(self.printMessage, "Olá!") será um objeto chamável que quando chamado executará a função self.printMessage passando a string "Olá!" como parâmetro.
Answer: Consegui resolver o problema.
colocando um lambda na linha
self.btnMessage["command"] = lambda: self.printMessage("Olá!")


Fundamental unit of the quadratic integer ring $\mathbb{Z}[\sqrt{n}]$

Question: I looked in other questions but I didn't find any answers regarding quadratic integer rings. Apologies if I missed it.
Given the ring $\mathbb{Z}[\sqrt{n}]$ where $n$ is a square-free positive integer, I would like to find the fundamental unit (i.e. some $a + b\sqrt{n}$ such that $\langle a + b\sqrt{n}\rangle = \mathbb{Z}[\sqrt{n}]^\times$, the units of $\mathbb{Z}[\sqrt{n}]$). I do know if I take the smallest $y$ such that $ny^2$ is of the form $x^2 \pm 1$, I get a unit, $x + y\sqrt{n}$. After all, we have $ny^2 = x^2 \pm 1$, so $ny^2 - x^2 = \pm 1$, meaning that $N(x + y\sqrt{n}) = x^2 - ny^2 = \mp 1$ ($N$ is just a standard Euclidean function). Since this particular Euclidean function is also multiplicative we know that any power of $x + y\sqrt{n}$ is also a unit. However, this is where I get stuck. Is this $x + y\sqrt{n}$ indeed a fundamental unit? If so, how do I show it can generate all units? If not, how do I find the actual fundamental unit?
Comment: See [here](http://math.stackexchange.com/questions/1220602/checking-a-fundamental-unit-of-a-real-quadratic-field) on MSE, for $n=2$. For the algorithm in general, see [here](http://www.numbertheory.org/php/unit.html).
Comment: By the way, try $n=9199$ in the algorithm. This is from Milne's lecture notes in algebraic number theory.
Comment: Thanks very much for those links. My lack of knowledge shows, as I assumed that the method and/or result to find it for $\mathbb{Z}[\sqrt{n}]$ would differ (however slightly) from finding the solution for $\mathbb{Q}[\sqrt{n}]$. Both those links are very illuminating.
Comment: Note that $\mathbb{Z}[\sqrt n]$ is only the ring of integers of a real quadratic field when $n\equiv_41$.
Answer: A very practical way to obtain the fundamental unit of a real quadratic field is as follows:
for $\Bbb Q(\sqrt d)$ we have
 $$a_n+b_n\sqrt d=(a_1+b_1\sqrt d)^n\Rightarrow b_{n+1}=a_1b_n+b_1a_n$$
This implies that the sequence $\{b_n\}$ is strictely increasing because $a_1,b_1,a_n,b_n$ are positive. Hence we can see at the sequence $d,2^2d,3^2d,4^2d,....$ and stop at the first term for which $db^2$ is such that $a^2-db^2=\pm1$ for some integer $a$. In this case the $a$ and $b$ are the searched $a_1$ and $b_1$ of the fundamental unit. This method as far as I know is due to Pierre Samuel.
Examples.- (1) For $\Bbb Q(\sqrt6)$ we have $6\cdot1=6;\space6\cdot2^2=24=5^2-1$ then the fundamental unit of $\Bbb Q(\sqrt6)$ is $5+2\sqrt6$.
(2) For $\Bbb Q(\sqrt7)$ we have $7\cdot3^2=63=8^2-1$ so the f. u. is $8+3\sqrt7$
Comment: But how do we know that all units have this form? Maybe there is a unit that is not a power of the unit we have found (I mean I know that this is not the case, but I don't know how to prove it)
Comment: @kubo The unit $a_1+b_1\sqrt d$ is called **fundamental** because it is a generator of the group of all the units when it has rank $1$. Look at **Dirichlet's unit theorem**.
Comment: How does this extend precisely to cases where $d \equiv 1$ mod $4$? For example, if we apply the algorithm above to $d = 5$, we get the unit $2 + \sqrt{5}$, but the fundamental unit is $\frac{1 + \sqrt{5}}{2}$, right?
Comment: @Anakhand: for $d=5$ the f. u. is $9-4\sqrt5$. Try to solve the equation $x^2-5y^2=1$ (or $-1$)and look at the answer in Wolfram.
Comment: @Piquito $(1/2)^2 - (\sqrt{5}/2)^2 = 1/4 - 5/4 = -1$, so $(1 + \sqrt{5})/2$ satisfies the equation but is not generated by $9 - 4\sqrt{5}$. As far as I understand, $9 - 4\sqrt{5}$ is the fundamental unit of $\mathbb{Z}[\sqrt{5}]$, but not of $\mathbb{Q}(\sqrt{5})$, because the ring of algebraic integers here is $\mathbb{Z}[\frac{1+\sqrt{5}}{2}]$, not $\mathbb{Z}[\sqrt{5}]$. In fact $\mathbb{Z}[\sqrt{5}]^\times$ is of index 3 in $\mathbb{Z}[\frac{1+\sqrt{5}}{2}]^\times$. Am I missing something?
Comment: Sorry, in fact, $9 - 4\sqrt{5}$ is not even the fundamental unit in $\mathbb{Z}[\sqrt{5}]$, because $9 - 4\sqrt{5} = (2 - \sqrt{5})^2$ and $2 - \sqrt{5}$ is a unit: $(2 - \sqrt{5})(-(2 + \sqrt{5})) = 1$. In fact, applying your alogirhm above gives $2 + \sqrt{5}$ as the f.u.
Comment: @Anakhand: No problem, dear friend.
Answer: In the case of a real quadratic field, the fundamental unit is the smallest unit of the form $ x + y \sqrt{d} $ such that $ x \geq 0 $ and $ y \geq 1 $. To see this, note that if $ x + y \sqrt{d} > 1 $ is a unit, we have that $ x^2 - dy^2 = \pm 1 $. Assume that $ x $ and $ y $ had different signs, then we would have
$$ x + y \sqrt{d} = \frac{\pm 1}{x - y \sqrt{d}} $$
and $ |x - y \sqrt{d}| \geq 1 $ since $ x $ and $ -y $ have the same sign.  This is a contradiction, therefore $ x $ and $ y $ are both nonnegative in $ x + y \sqrt{d} $. Since the fundamental unit is the smallest unit greater than $ 1 $, it follows that we may simply look at units of the form $ x + y \sqrt{d} $ where $ x, y $ are nonnegative, which reduces the problem to a necessarily finite brute force search.
While Dirichlet's unit theorem necessarily implies that the above found unit must be the fundamental unit, there is a more elementary proof of this fact. Assume that $ \varepsilon $ is the smallest unit greater than $ 1 $, and $ x $ is any unit greater than $ 1 $. We want to show that $ x $ is a power of $ \varepsilon $. Since the sequence $ a_n = \varepsilon^n $ diverges, there is a greatest integer $ n $ such that $ a_n = \varepsilon^n \leq x $. Then, $ x/\varepsilon^n $ is a unit $ \geq 1 $, but it is less than $ \varepsilon $ since $ x < \varepsilon^{n+1} $. By the definition of $ \varepsilon $, the only unit in the interval $ [1, \varepsilon) $ is $ 1 $, so it follows that $ x = \varepsilon^n $.
A more sophisticated algorithm to find the fundamental unit involves continued fractions, see these lecture notes for further information.
Comment: I just want to say that as somebody who's still working on fully grasping the Dirichlet unit theorem I really appreciate your simple proof!
Answer: It certainly has been discussed on MSE how to find a fundamental unit for the unit group of the ring of integers of a real quadratic number field $\mathbb{Q}(\sqrt{n})$. A nice survey, how to use continued fractions, and a table with examples for squarefree $n\le 21$ is given here.
Remark: The ring of integers in $\mathbb{Q}(\sqrt{n})$ is not always $\mathbb{Z}(\sqrt{n})$. This is only true for $n\equiv 2,3\bmod 4$. For the remaining case $n\equiv 1 \bmod 4$ (note that $n$ is squarefree), it is slightly different. An example here, with $n=141$ is discussed here on MSE. The result is as follows: since $\sqrt{141}=[11,\overline{1,6,1,22}]$, we have that $95+8\sqrt{141}$ is a fundamental unit!
Comment: I had assumed that the ring of integers would always be trivial. Thanks for pointing out that it isn't!
Comment: Sorry, that's an absolutely terrible way of wording it. I was referring to the fact that the ring is only $\mathbb{Z}[\sqrt{n}]$ for $n \equiv 2, 3 \mod 4$, not trivial in the normal sense. In my head I just called that trivial. My bad!
Comment: No problem, I understood it now.


Why is there an A natural in E major key

Question: If you look at the following score you can that it is E major but that the A notes are natural.  Why?  You get points if you can name from what piece the music comes from.
Also, if G is automatically sharped in E major then why does the author write a sharp sign next to the G below:
Comment: Isn't this piece in C# minor rather than E major?
Comment: Is this a joke? You're giving out bonus points for people to track down the Moonlight Sonata to read bar 18 where G natural was used making sensible the courtesy accidental G# in bar 19. Hint: if this is a serious question, don't try playing guessing games about the piece of music.
Comment: I wasn't going to down vote until I saw you selected an answer than doesn't even answer the question. Down voting to maintain some sense of quality here.
Answer: This is Beethoven op.27 No.2, commonly called the 'Moonlight Sonata'.   To answer your question we need to show a bit more context.
Here's your first example, (in another edition where the editor actually decides NOT to use a cautionary A natural).  But the reason he might have done so is the A sharp in the preceding bar.

Here's the second one.  The cautionary A natural in the 5th bar treble is because of the A sharp two bars previously. The G sharp in the 4th bar bass is because of the G natural in the preceding bar.

Neither are strictly necessary.  Both might be considered helpful.  As mentioned, the editor of my version only thought one of them was worth putting in.  I can see why.  He's treating the melody and the accompanying triplets as separate voices.  He feels a a cautionary accidental is rated only when the preceding one is in the same voice.
Oh, and it's in C# minor, not E major.
Answer: It's in C♯ minor rather than E major. The author probably didn't put in the accidentals asked about. It was more likely the type setter. As Laurence says, there are versions without those accidentals.
As so many other 'unexplainable' accidentals, these are cautionary or courtesy accidentals which are there to remind  players that a previous changed note has now in fact returned to the one in the key signature. The barline after any accidental will automatically cancel that accidental in any case, but sometimes it's felt that an extra reminder won't go amiss. They're often put in parentheses, which does make more sense. It's as if someone's saying 'yes, I know you're aware, but here's a little reminder anyway'.
Comment: @logic1976  There are 3 "standard" minors: natural,  melodic, and harmonic.  The harmonic puts the 7th back into major position, but by tradition that is only indicated with accidentals, not in the key sig.  The melodic is different going up or going down, so it has to use accidentals.
Comment: What's the difference between c sharp minor and e major?
Comment: While the number of sharps in the key signature is the same, the tonics are different, usually different notes are played, and the whole sonorities and harmonies are not the same.


Mathematical notation in Discrete Mathematics

Question:
The sum of the first $n$ natural numbers, starting at $1$, is $$\frac{n(n + 1)(2n + 1)}{6}.$$

Would this translate to...
For any $n$ a natural number, starting at $1$, the sum of the first $n$ natural numbers implies the equation?
Is it OK to assume that it's for all $n$? Or would that be wrong?
Answer: "Yes", except that the formula given is the sum of the squares of the natural numbers, from 1 to n.
Comment: Where does it say square?
Comment: It doesn't. But that's what that formula corresponds to. As written, it is wrong.  If "squares of the" is inserted between "the" and "first", it would be a correct statement.
Comment: It doesn't, but it *should*.
Comment: It doesn't mean n = 5, then 5+4+3+2+1 = 15?
Comment: It does, but: $\dfrac{5(5+1)(2\cdot 5+1)}{6}=55 = 1^2+2^2+3^2+4^2+5^2$
Comment: If n=5, then $1^2+2^2+3^2+4^2+5^2 = 5*(5+1)*(2*5+1)/6 = 55$
Comment: Ah. But in this case, please correct me if i'm wrong, it's saying the sum of the first n natural numbers implies the the sum of squares? Which is obviously false. So would it be right to disprove this?
Comment: There is a mistake in the statement of the formula.  Whoever write it forgot to put in "square".  That;'s really all there is to it.
Comment: No... It was written like that LOL. For sure it's not wrong. So this equation obviously is not correct, meaning I should disprove it right?
Comment: Well, as written you can disprove it with a counterexample. Your n=5 calculation is sufficient to do that.  n=2 is even simpler and also provides a counterexample.
Comment: Is it good enough to disprove this by providing a counter example?
Comment: Thank you sir! I hope you have a great day.
Comment: A counterexample is sufficient to disprove it.
Answer: Incorrect.   It should be the sum for the squares of the first $n$ non-zero natural numbers equals that.
$${\sum_{k=1}^n k =\dfrac{n(n+1)}{2!}\\\bbox[1ex, border:pink solid 1pt]{\sum_{k=1}^n k^2 =\dfrac{n(n+1)(2n+1)}{3!}}\\\sum_{k=1}^n k^3 =\dfrac{6n^2(n+1)^2}{4!}}$$
Answer: Where did you read that? But more importantly: have you tried to derive the equation yourself?
The sum of the first two natural numbers is 3. The sum of the first three natural numbers is 6. The sum of the first four natural numbers is 10. The sum of the first five natural numbers is 15. Hmm, that looks like the triangular numbers.
If you look these up in the OEIS, you will verify that $$\binom{n + 1}{2} = \frac{n^2 + n}{2} = \sum_{i = 1}^n i.$$
None of those look like the formula you copied. Compute $$\frac{n(n + 1)(2n + 1)}{6} = \frac{2n^3 + 3n^2 + n}{6}$$ for a few $n$, say $0 < n < 8$ and look that up in the OEIS: the square pyramidal numbers should be the very first result, and indeed we see that $$\frac{n(n + 1)(2n + 1)}{6} = \sum_{i = 1}^n i^2.$$ That superscript 2 makes a big difference in the summation — does that count as a pun?

In both summations above you can substitute $i = 0$ and that won't change the result.
Comment: What are you showing here? I'm confused.
Comment: What are you confused by? The sigma notation? This explains that: http://www.columbia.edu/itc/sipa/math/summation.html


Finding piecewise function of $f(x) = \big||x − 1| − 1\big|$?

Question: I am having some difficulty with this problem where I need to put it into a piecewise function, $f(x) = \big||x − 1| − 1\big|$
I separated it into $x-1, -x+1, x-1-1, -x+1+1$
But the answer on the sheet for the piece wise looks like this:
$$−x , x ≤ 0;\quad
x , 0 < x ≤ 1;\quad
2 − x , 1 < x ≤ 2;\quad
x − 2 , x > 2$$
I don't know how we got $0$ for the function because I thought solving for $x$ would be $x = 1$, not $0$. Can someone help me out solving this problem? Thanks!
Comment: What do you mean by "we got $0$
 for the function" and by "solving for $x$"? And how did you "separate it into $x-1, -x+1, x-1-1, -x+1+1$? (and for which interval for $x$ for each of these 4 expressions?
Comment: Recall that $|x|$ is$$\begin{cases}-x,&x\le0\\x,&x>0.\end{cases}$$ Therefore, $\big\lvert\lvert x-1\rvert-1\big\rvert$ equals $$\begin{cases}-\big(\lvert x-1\rvert-1\big),&\lvert x-1\rvert-1\le0\\\lvert x-1\rvert-1,&\lvert x-1\rvert-1>0.\end{cases}$$Can you see how to continue? EDIT: Anne Bauval's approach may be simpler.
Comment: Or more simply, from "inside": $$f(x)=\begin{cases}|(x-1)-1|,&x\ge1\\|(1-x)-1|,&x\le1.\end{cases}$$ Anyway, please read [Quick beginner guide for asking a well-received question](https://math.meta.stackexchange.com/questions/35391/quick-beginner-guide-for-asking-a-well-received-question) and [avoid "no clue" questions](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question/27933#27933).
Comment: I don't think the answer sheet is right either.  $f(2) = 0$ for instance.
Comment: It might be simpler to start looking at $x \mapsto ||x|-1|$.
Answer: We may write $f(x)$ as $f(x)=g(g(x))$ where $g(x)=|x-1|$. Some observations: If $x\geq1$, $g(x)=x-1$, and if $x<1$, $g(x)=1-x$. Therefore:
$$g(x)=\begin{cases}x-1 & x\geq 1 \\ 1-x & x<1\end{cases}$$
Similarly
$$f(x)=g(g(x))=\begin{cases}g(x)-1 & g(x)\geq 1 \\ 1-g(x) & g(x)<1\end{cases}$$
Some other observations: note $g(x)\geq 1$ when $x\geq 2$ or when $x\leq 0$. Therefore
$$||x-1|-1|=f(x)=g(g(x))=\begin{cases}|x-1|-1 & x\geq 2~\text{or}~x\leq 0 \\ 1-|x-1| & x\in(0,2)\end{cases}$$
We break up the absolute values further:
$$||x-1|-1|=\begin{cases}(x-1)-1 & x\geq 2 \\ (1-x)-1 & x\leq 0 \\ 1-(1-x) & x\in (0,1) \\ 1-(x-1) & x\in[1,2) \end{cases}$$
Simplifying:
$$\boxed{||x-1|-1|=\begin{cases}x-2 & x\geq 2 \\ -x & x\leq 0 \\ x & x\in (0,1) \\ 2-x & x\in [1,2)\end{cases}}$$


making the navigation menu bold

Question: I know this seems to be a stupid question but I have a problem with my navigation menu - I can`t find a way to get the text in the navigation menu bold. I tried and tried to find this out by using firebug but without success.
I`m using wordpress theme "hueman". The website is www.traumbad-muenchen.de.
Thanks so much guyes for help
Answer: This should do the trick. Add this to your CSS to bold the links in the navigation.
<code>.nav > li {
    font-weight: bold;
}
</code>
Comment: If you believe this was the correct answer, please select the "Checkmark" icon next to the answer.

making the navigation menu bold


Isomorphism between localizations of graded ring $S_{(P)} \cong [S_{(f)}]_{PS_f \cap S_{(f)}}$

Question: I know that if $S$ is a graded ring, and $f$ is a homogeneous element of positive degree, then there is a bijection between the homogeneous prime ideals of the localization $S_f$ and the prime ideals of $S_{(f)}$, the subring of $S_f$ comprising the homogeneous elements of degree $0$ such as from this MSE question. How can I prove that this bijection gives rise to an isomorphism of the following rings: for a homogenous prime ideal $P$ of $S$ with $f \notin P$, there is an isomorphism
$$S_{(P)} \cong [S_{(f)}]_{P S_f \cap S_{(f)}}.$$
Is this true? If yes, what is this isomorphism?
In other words, how do I lift the bijection between prime ideals mentioned above, to elements in the prime ideals related by this bijection. Here $S_{(P)}$ is the subring of degree $0$ elements of the localization $S_{P}$ like always.
Comment: See also [Stacks 00JR](https://stacks.math.columbia.edu/tag/00JR) which proves the result you seek without any extra hypotheses but leaves much of the verification to the reader.
Answer: I suspect you may need that $S$ is generated in degree 1, but perhaps I'm missing a way to fix the following argument.
Since $P$ is a homogeneous prime and $S$ is generated in degree 1, there is an element $\lambda$ of degree one such that $\lambda\not\in P$.
Let $\phi : S_{(P)}\to [S_{(f)}]_{PS_f\cap S_{(f)}}$ be defined by $$\phi\left(\frac{s}{r}\right)=\frac{s\lambda^k/f^n}{r\lambda^k/f^n},$$
where $n$ is large enough that $n\deg f \ge \deg s$ and $k$ is such that $\deg s + k = n \deg f$. To see that this is well defined, observe that if
$\frac{s}{r} = \frac{s'}{r'}$, then there is $h\not\in P$ such that $h(r's-rs')=0$, and for appropriate choices of $\ell,j,k,n,m,o$, we have
$$\frac{h\lambda^\ell}{f^o}\left(\frac{r'\lambda^j}{f^m}\frac{s\lambda^k}{f^n}-\frac{s'\lambda^j}{f^m}\frac{r\lambda^k}{f^n}\right)=\frac{\lambda^{\ell+j+k}}{f^{o+m+n}}(h(r's-s'r))=0.$$
Thus $\phi(s/r)=\phi(s'/r')$.
To see that $\phi$ is the desired isomorphism, note $PS_f$ is the set of elements $a$ of $S_f$ such that $af^n\in P$ for some $n$. Thus if $s/f^m\not\in PS_f$ with $s\in S_{m\deg f}$, and if $r\in S_{n\deg f}$, and if $\ell=\max\{n,m\}$ we can define the inverse by
$$\psi\left(\frac{r/f^n}{s/f^m}\right)=\frac{rf^{\ell-n}}{sf^{\ell-m}},$$
which works since we know $sf^{\ell-m}\not\in P$, since $s/f^m \not\in PS_f$, and
both numerator and denominator have degree $\ell \deg f$.
It shouldn't be hard to verify that $\psi$ is also well defined and $\phi$ and $\psi$ are inverses.
Comment: Thanks for the answer @jgon. I believe the extra hypothesis is not necessary, but I am not able to prove it otherwise. So I will wait a couple more days to see if I get any more answers before accepting your excellent answer.
Answer: Here I believe is a proof without assuming S is generated in degree 1.
For $P\subset S$ homogenous with $f\notin P$ let $\varphi(P):=PS_f\cap S_{(f)}$. Define
$$\psi: \Big(S_{(f)}\Big)_{\varphi(P)}\to S_{(P)}$$ by $\frac{a/f^n}{b/f^m}\mapsto \frac{af^m}{bf^n}$.
To see that $\psi$ is injective suppose $\frac{af^m}{bf^n}=0$ in $S_{(P)}$. Then $\frac{af^m}{bf^n}=0$ in $S_{P}$ so there is an $h\notin P$ such that $haf^m=0$. We may assume $h$ is homogeneous because if it's not we replace it by one of its nonzero homogeneous components. But then $\frac{h^{deg(f)}f^m}{f^{deg(h)+m}}\notin \varphi(P)$ and
$$\frac{h^{deg(f)}f^m}{f^{deg(h)+m}}\cdot \frac{a}{f^n}=0$$
in $S_{(f)}$. Therefore $\frac{a/f^n}{b/f^m}=0$ in $(S_{(f)})_{\varphi(P)}$ and $\psi$ is injective.
To se that $\psi$ is surjective let $\frac{x}{y}\in S_{(P)}$ and note that $deg(x)=deg(y)$ and $y\notin P$. Then
$$\frac{x}{y}=\frac{x\cdot y^{deg(f)-1}}{y^{deg(f)}}=\psi\Big(\frac{x\cdot y^{deg(f)-1}/f^{deg(x)}}{y^{deg(f)}/f^{deg(x)}}\Big).$$


Holomorphic tangent vector field determines a infinitesimal holomorphic equivalence?

Question: Let $X$ be a complex compact manifold. I want to understand the holomorphic tangent vector field on $X$. I know a smooth vector field can define an infinitesimal diffeomorphism of $X$ (more precisely, a one-parameter diffeomorphism group). Similarly, if we consider a holomorphic tangent vector field, will it determine to a infinitesimal holomorphic equivalence of $X$ (a one-parameter holomorphic equivalence group)?
Answer: Yes, the flow will give a 1-parameter group of biholomorphisms. See chapter 3 of S. KOBAYASHI, Transformations Groups in Differential Geometry.


Input layer in Neural Network with different vocabulary size

Question: I want to build a Neural Network where each neuron in the input layer will have different size. For instance, x1 = [0 1 0], x2 = [13 4 5 1 9 0], x3 = 7...
Would it be possible to train this model? What should I change from a normal size neural network? Would it be better fill with zeros to the maximum size?
Comment: Take a look at recurrent neural networks, they handle variable sized inputs naturally.
Comment: RNN are suitable for sequences, but my samples are independent. In addition, it is good for the community knowing if a simple NN could handle variable sized inputs. Thanks
Comment: this question is badly specified. you don't specify what the inputs mean- does 4 in x2 correspond to 1 in x1 ( ie same dimension)... and the vector mapping is not unique to neural networks its common to most ML models (not RNN)
Answer: Mathematically, if the inputs are filled with zeros to the maximum size, weights in these variables are discarded. This is the same as having inputs with different sizes of variables.


Erro em formulário django

Question: estou tentando rodar um formulario em django mas ele volta esse erro
form = TopicoForm()

raise ValueError('ModelForm has no model class specified.')

esse é o meu models
class Topico(models.Model):

    titulo = models.CharField('Título', max_length=100)
    mensagem = models.TextField('Mensagem')
    avatar = models.ImageField(upload_to='core/images', verbose_name='Imagem', blank=True, null=True)
    id_usuario = models.ForeignKey(Usuario)
    id_assunto = models.ForeignKey(Assunto)

    def __str__(self):
        return self.titulo

o form
class TopicoForm(forms.ModelForm):

    class meta:
        model = Topico
        fields = '__all__'

e a views
def novo_post(request):
    if request.POST:
        form = TopicoForm(request.POST)
        if form.is_valid:
            form.save()

    else:
        form = TopicoForm()
    contexto = {
        "form": form
    }
    return render(request, "novo_post.html", contexto)

Answer: O erro ocorreu porque você escreveu meta em vez de Meta, o correto seria:
class TopicoForm(forms.ModelForm):

    class Meta:
        model = Topico
        fields = '__all__'

Erro em formulário django


put less values to a bigger 2d array

Question: I have a 2D array that I initialize like this: int[][] mat = new int [10][10]. Then I'm asking the user how many rows and cols he want. For example he insert row=3, col=4.
How can I work with this size ([3][4]) so I won't see all the zeros? I just want to insert 12 values to an 100 values array.
int[][] mat = new int[10][10];
int row, col;

do {
    System.out.println("enter rows: ");
    row = s.nextInt();
    if (row > 10) {
        System.out.println("value should be between 1-10, try again ");
    }
} while (row > 10);

do {
    System.out.println("enter cols: ");
    col = s.nextInt();
    if (col > 10) {
        System.out.println("value should be between 1-10, try again ");
    }
} while (col > 10);

mat[10][10] = mat[10 - 10 + row][10 - 10 + col];
System.out.println("enter: " + row * col + " values");
for (int i = 0; i < mat.length; i++) {
    for (int j = 0; j < mat[i].length; j++) {
        mat[i][j] = s.nextInt();
    }
}

Answer: What about postponing the creation of the matrix:
int row, col;

do{
    System.out.println("enter rows: ");
    row = s.nextInt();
    if (row > 10){
        System.out.println("valuse should be between 1-10, try again ");
    }

}while(row > 10);

do{
    System.out.println("enter cols: ");
    col = s.nextInt();
    if (col > 10){
        System.out.println("valuse should be between 1-10, try again ");
    }

}while(col > 10);
int[][] mat = new int[rows][cols];//create matrix here

Note that by postponing the creation of the matrix, you can allow more than 10 rows or columns. If a person would enter 100 and your program doesn't refuse this, a matrix with 100 rows/columns can be created.
You should also check that the input is greater than (or equal to) zero. Have you ever seen a matrix with -5 rows?
And this statement makes no sense at all:
mat[10][10] = mat[10-10+row][10-10+col];

It won't do any harm, since it is guaranteed that the bounds are correct, but it is useless since the values are initialized on 0.
And a small spelling fix: It's "values"; not "valuse" as well as "zeros" (instead of "zerows", unless you want to sound like a pirate of course ;).

put less values to a bigger 2d array


The number of even and odd natural numbers

Question: Person A: The number of even and odd natural numbers is equal, because they alternate each time.
Person B: There are far more even natural numbers. If you double an odd number, it's even. If you double an even number, it's still even.
How do I best explain to a person with only base mathematical knowledge the truth of the matter?
Comment: Only 1/3 of all numbers are even. Take the asymptotic limit: 1,3,2,5,7,4,9,11,6, 13,15,8, ...
Comment: Doubling introduces evenness and is therefore a failed attempt to classify this property.  One way to approach this is to take an increasing interval from the natural numbers and count the even and odd members.
Comment: Person C: There are far more odd numbers because every even number arises from adding 1 to an odd number. This "logic" as as false as that "doubles logic"
Comment: I'd explain that *infinite*  is not a number, but a different, abstract, beast that *sometimes* can be be compared to a number, but most of times it has its own rules.
Comment: Thanks to all who contributed in comments or answers.
Answer: "There are more" is not well-defined for infinite sets. I think the real answer is that the question isn't meaningful. (The existence of an injective map is well-defined, but you can debate whether that means 'there are at most as many'.)
You may dispute the latter argument by pointing that "If you take a natural number and add its successor to it, the result is always odd". There are infinitely many functions $f : \mathbb N \times \mathbb N \rightarrow \mathbb N$ that always produce odd or always produce even numbers.
Comment: Thanks. It is helpful for *me*. I did not convince the person I was speaking with - but it did end the discussion.
Comment: Would you have a suggestion how to best explain the issues of "infinity" to a person with mathemtaical knowledge of a ~9th grader?
Comment: Good question. I think what I would do is emphasize 'infinite' as a property rather than a thing. The natural numbers are defined as "0 is a NN, and for each NN, the successor is another NN". This defines a set, and all we can do is study properties of this set, which turn out to often be unintuitive. If the person says that 'there are more' should be a meaningful property, just ask them how they would define it. Dk if that's helpful.
Answer: The second argument only shows that in the "double naturals", there are far more even numbers than odd ones. The argument says nothing about the naturals themselves.

Modern theory says that there are as many even as odd naturals, because you can associate every even number to an odd one and conversely (add or subtract $1$).
But it also says that there are as many naturals as there are even ones (multiply and divide by $2$) ! And there are as many primes as there are naturals.
Comment: No, the theory does not say "as many", is says "have the same cardinality/there is bijection".
Comment: @Anixx: I expected this comment.


Confused about order in probability

Question:
A committee consists of five Mexicans, two Asians, three African Americans, and two Caucasians. A subcommittee of 4* is chosen at random. What is the probability that all the ethnic groups are represented on the subcommittee?

Note: original posting said 5 but I meant 4. Also, I know, the race thing is weird, but it was in my book.
It seems to me like the answer should be
$$\frac{\frac{5*2*3*2}{4!}}{\binom{12}{4}}$$
because we want both the numerator and the denominator to be unordered selection.
Alternatively, we would say that it is
$$\frac{5*2*3*2}{12*11*10*9}$$
However, something in my reasoning is incorrect as the solution is just
$$\frac{5*2*3*2}{\binom{12}{4}}$$
I am dreadfully confused.
source: http://www.math.illinois.edu/~psdey/stat20SU07/Solutions2_2007.pdf
Comment: One good way to get unconfused is to look closely at a simpler version of the question.  You might be able to make quick work of writing down all the possible ways of picking one Mexican and one Asian in a committee of size $2$ from a group of two Mexicans and one Asian, for instance. You should easily discover why your formula gives a value that's too small.
Answer: There are $\binom{12}{5}$ possible committees.
Committees of $5$ that include at least one member from each group necessarily have just one group having two members on the committee, all other groups have just one. So, the number of such committees is
$$\binom{5}{2}\cdot 2\cdot 3\cdot 2 + 5\cdot \binom{2}{2}\cdot 3\cdot 2
+ 5\cdot 2 \cdot \binom{3}{2}\cdot 2 + 5\cdot 2 \cdot 3
\cdot \binom{2}{2}$$
Comment: Sorry that is not what I am asking, please read the edit
Comment: @user2879934 I posted it before reading the edited version of your question (you made the edit while I was writing my answer.)
Comment: no problem, it was my bad
Answer: If we think of seating the people in 4 seats and insist that the first seat be occupied by a Mexican, the second by an Asian, the third by an African American and the fourth by a Caucasian, then the chance of this is: 5/12 x 2/11 x 3/10 x 2/9. In the problem you have set we don't care which person sits in which seat so long as one of each is present. There are 4! ways of re-arranging the people in the seats, so the answer to your question is 4! times the product I just gave, which once you re-arrange it is the same as the answer given in the book.
Comment: this is a much clearer way to think about it
Answer: The numerator is the number of ways to choose $4$ people from $12$ people such that exactly one person is chosen from each ethnic group.  The numerator is thus ${5 \choose 1} {2 \choose 1}{3 \choose 2}{2 \choose 2}$.  The denominator is clearly ${12 \choose 4}$.
Alternatively, you could assume that the subcommittee  has a name for each of the positions - say president, vice president, secretary and treasurer. Then, the numerator would be ${5 \choose 1} {2 \choose 1}{3 \choose 2}{2 \choose 2} 4!$ because once the 4 people are chosen so that each ethnic group is represented, they can be placed in various positions in $4!$ ways. For the same reason, the denominator is ${12 \choose 4} 4!$.  The $4!$'s cancel out and we get the same probability.

Confused about order in probability


Extract integers from file hidden between random characters

Question: <code>#include <fstream>
#include <vector>
#include <string>

struct values {
    int a,b,c,d;
};

int main() {
    std::ifstream myfile("myfile.txt");
    std::vector<values> vect;

    // Format of text file is:
    // sdasjkdh234sldaksdj23asd125as24dfs
    // asdac5234sdf435ljk...35wsd63jj
    // asdad234sdf35gg567dfg554ddd

}
</code>
I need to create a vector from a file where each line contains four integers hidden between random characters, and put them into a vector of structs where each integer is mapped to the four fields in the struct values. The file has no whitespaces.
What is the easiest way to do this?
Comment: Replace any non numerical character with a space and use `std::istream::operator<<()` ?
Comment: Read file line by line and match integers with regular expression.
Comment: Read a block of data from the file into memory, the parse the memory. Repeat.
Comment: The **easiest** method is to read one character at a time from the input file.  If the character `isdigit()` then save it, otherwise repeat.  This may not be the most efficient.  Also search stack overflow for "c++ why EOF is bad".
Answer: <code>std::string line;

while(getline(cin, line))
{
    auto s = std::remove_if(line.begin(), line.end(), [](auto& c) { return !isdigit(c); });
    line.erase(s, line.end());
    vect.push_back(std::stoi(line));
}
</code>
Comment: care to add some explanation ?
Comment: Isn't there a coding standard rule that says if the code says exactly what it's doing you shouldn't comment them?


how to use ldapsearch for sort attributes filter

Question: I would like to know how to use ldapsearch filter for sort mail by gid number. I tried several command and I don't get what I expected. I got all the entry without sorting or nothing.
Answer: Use -S parameter (in your case, -S gid) in ldapsearch command. From the ldapsearch man page:

-S attribute
      Sort the entries returned based on attribute. The default is not to sort entries returned. If attribute is a zero-length string (""),
  the entries are sorted by the components of their Distinguished Name.
  See ldap_sort(3) for more details. Note that ldapsearch normally
  prints out entries as it receives them. The use of the -S option
  defeats this behavior, causing all entries to be retrieved, then
  sorted, then printed.


Load the same .obj file by using Open3D and Trimesh respectively leading to different number of vertices

Question: To read the mesh file xxxxx.obj
I use Open3D and Trimesh module respectively by these codes:
import open3d as o3d
import trimesh

mesh = o3d.io.read_triangle_mesh(meshfile)
print(mesh)
mesh_ = trimesh.load_mesh(meshfile)
print(mesh_)

output is
TriangleMesh with 224946 points and 74996 triangles.
<trimesh.Trimesh(vertices.shape=(37486, 3), faces.shape=(74996, 3))>

It seems open3d got 224946 points while Trimesh got 37486 points, what cause this problem?
I print out both their vertices and triangles
____mesh_vert____:
 [[-0.77349651 -0.17361518 -0.5339487 ]
 [-0.77405303 -0.17450994 -0.52660068]
 [-0.77472924 -0.17558702 -0.51311542]
 ...
 [ 0.85712222  0.03432839  0.45968683]
 [ 0.8533449   0.04001502  0.4399732 ]
 [ 0.85333683  0.04001284  0.44043044]]
____mesh_vertices____:
 [[-0.77714473 -0.16696896 -0.52666056]
 [-0.77481598 -0.16823091 -0.53799069]
 [-0.77349651 -0.17361517 -0.53394872]
 ...
 [ 0.85654795  0.03840274  0.44923028]
 [ 0.85598844  0.03371801  0.43383372]
 [ 0.85334492  0.04001502  0.43997321]]
____mesh_triangles____:
 [[     0      1      2]
 [     3      4      5]
 [     6      7      8]
 ...
 [224937 224938 224939]
 [224940 224941 224942]
 [224943 224944 224945]]
____mesh_faces____:
 [[    8     7     0]
 [    0     1     8]
 [    9     8     1]
 ...
 [37465 37466 37485]
 [37484 37485 37482]
 [37482 37481 37484]]

What cause the differences?
Comment: Can you share the obj file? How many vertices and faces are there if opened with meshlab?
Answer: I'm investigating a similar issue right now. The vert count I get when opening with trimesh is larger than when opening with Houdini. It seems to be odd behaviour trimesh has with uvs.
I found the number of lines starting with "v " in the obj file equaled the number of vertices Houdini loaded.
I found the number of lines starting with "vt " in the obj file equaled the number of vertices trimesh loaded.
It seems trimesh creates additional vertices to store the data for these extra "vt " lines, which I understand store UV data.
This is pretty bad because simply opening said obj file and saving it back out, without any modifications, using trimesh will change the vertex count for the mesh in DCCs. The extra vertices is created for the "vt " lines became additional "v " lines, in my testing.


Confidence interval over multiple Poisson distributions

Question: There are five different periods (one following each other) of unequal lengths where one specific event is happening such that it follows Poisson distributions (e.g. meteorite falls). It is always the same type of event, just the expected average time between event is changing from time to time. In reality there are many more such periods.
The data look like this:

in the 1st period (100 hours) the average interval for event is 500 hours
in the 2nd period ( 80 hours) the average interval for event is 700 hours
in the 3rd period (130 hours) the average interval for event is 300 hours
in the 4th period ( 50 hours) the average interval for event is 800 hours
in the 5th period (400 hours) the average interval for event is 900 hours

Lambda:

1st period lambda: (1/500)*100 = 0.200
2nd period lambda: (1/700)*80  = 0.114
3rd period lambda: (1/300)*130 = 0.433
4th period lambda: (1/800)*50  = 0.062
5th period lambda: (1/900)*400 = 0.444

Is there a way to estimate how many events happened and what is the confidence interval for the estimate?
I understood from How to calculate a confidence level for a Poisson distribution? and here: http://ms.mcmaster.ca/peter/s743/poissonalpha.html that I can use (x is number of events):

( qchisq(0.025, 2*x)/2, qchisq(0.975, 2*(x+1))/2 )

or maybe some other method that will be more suitable for low lambda.
I don't understand how I can add all the five distributions together to say how many events were expected.
Comment: A confidence interval is constructed from data, but you don't mention data at all.  It sounds like you just want to compute the distribution of the total number of events.  Is that correct?  If not, could you describe the data you have?  It's also curious that you know what the Poisson intensities are.  Do you truly know them or are you estimating them from some data?  If so, what data?
Comment: @whuber You are correct. I want to know the expected distribution of the total number of events across these 5 periods. This exercise comes from mining of cryptocurrencies. When you mine, you do know how much time on average it will take you to find a coin given computational resources you have. At discrete non-fixed intervals (typically few weeks) the difficulty of mining will change and will alter your average time you expect to mine a coin. I am trying to aggregate the expectations over more periods of difficulty, add CI and eventually compare with reality.
Answer: Because (a) the number of events in any $T$ hour period with a rate of one event every $H$ hours follows a Poisson distribution with parameter $T/H$ and (b) the number of independent Poisson random variables of rates $\mu_1,\mu_2,\ldots,\mu_n$ in non-overlapping intervals is a Poisson random variable of rate $\mu=\mu_1+\mu_2+\cdots+\mu_n,$ any question about the probability distribution of the number of events is readily answered.  Let's write $F$ for this distribution function and (therefore) $F^{-1}$ for its quantile function.
For instance,

The expected number of events is $\mu.$
The variance of the expectation is $\mu$ and so its standard deviation is $\sqrt{\mu}.$
For any tolerance level $q$ between $0$ and $100%,$ choose nonnegative values $\alpha_l$ and $\alpha_u$ totaling $1-q.$  Then with at least probability $q$ the number of events will be between  $F_{l} =F^{-1}(\alpha_l)$ and $F_{u}=F^{-1}(1-\alpha_u).$  The actual probability is $F(F_{u}) - F(F_{l}-1).$

Often one chooses a "symmetrical" interval in the sense that $\alpha_l=\alpha_u = (1-q)/2.$
To see how simple this is, let's use the data in the question as an example.

The time intervals are $100,80,130,50,400$ minutes and the rates are the reciprocals of $500,700,300,800,900$ hours, whence $$\mu = \frac{100}{500} + \frac{80}{700} + \cdots + \frac{400}{900} = 1.2545\ldots\,.$$
The standard deviation is $\sqrt{1.2545\ldots} \approx 1.12.$ You can use this immediately (using only mental arithmetic) to bound the chances of large numbers of events. For instance, Cantelli's Inequality implies the chance of $5$ or more events, which is $(5-1.2545)/1.12 \approx 3.3$ standard deviations beyond the mean, cannot exceed $1/(1+3.3^2) \approx 1/12 \approx 8\%.$
If, say, you wanted a $q=95\%$ symmetric interval in which the number of events is likely to fall, set $\alpha_l=\alpha_u=2.5\%$ and locate the $0.025$ and $0.975$ quantiles of the Poisson$(1.2545)$ distribution at $0$ and $4,$ respectively.  The actual chance that the number of events will be between $0$ and $4$ inclusive is $99.1\%.$

To perform the calculations in the example I used the following commands in the statistical calculator R.
#
# Specify the problem.
#
intervals <- c(100, 80, 130, 50, 400)
averages <- c(500, 700, 300, 800, 900)
q <- 0.95
#
# Compute some properties of the distribution of the total number of events.
#
mu <- sum(intervals / averages)                    # Expected number
alpha.u <- alpha.l <- (1 - q)/2                    # Upper and lower tolerances
tl <- qpois(c(Lower=alpha.l, Upper=1-alpha.u), mu) # Limits
coverage <- diff(ppois(tl + c(-1,0), mu))          # Probability within limits
names(coverage) <- "Coverage"
#
# Display the answers.
#
(tl) # The limits
(signif(c(Expected=mu, SD=sqrt(mu), `Nominal coverage`=q, coverage), 3))

Comment: Please see the calculation in the example: it computes the chance that a Poisson variable with mean $1.25$ lies between the lower and upper limit, inclusive, by computing the chance it is less than or equal to the upper limit (via `ppois`) and subtracting (via `diff`) the chance it is *strictly* less than the lower limit.
Comment: I got lost in the last sentence. Expected value is 1.2545 with 95% symmetric interval `<0;4>`. How should I understand that actual chance is 99.1%?


R geom_bar and geom_line labels for grouped bars

Question: I want to plot a grouped barchart with labels, but they only appear as stacked bar labels.
I am using the following libraries:
library(dplyr)
library(ggplot2)
library(scales)

In the following the dataframes I am using:
df1 <- data.frame(month = c("2017-10-01", "2017-10-01", "2017-10-01", "2017-11-01", "2017-11-01", "2017-11-01",
                            "2017-12-01", "2017-12-01", "2017-12-01", "2018-01-01", "2018-01-01", "2018-01-01",
                            "2018-02-01", "2018-02-01", "2018-02-01", "2018-03-01", "2018-03-01", "2018-03-01"),
                 source = c("a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c"),
                 value1 = c(sample (c(1000L:4000L),18, replace = FALSE)),
                 stringsAsFactors = FALSE
                 )

df1$month <- as.Date(as.character(df1$month, format = "%Y%m$d"))
df1$month <- as.Date(format(df1$month, "%Y-%m-01"))
df1 <- arrange(df1, month)

df2:
df2 <- data.frame(month = c("2017-10-01", "2017-11-01", "2017-12-01", "2018-01-01", "2018-02-01", "2018-03-01"),
                  value2 = c(sample (c(5000000L:6000000L),6, replace = FALSE)),
                  stringsAsFactors = FALSE
                  )
df2$month <- as.Date(as.character(df2$month, format = "%Y%m$d"))
df2$month <- as.Date(format(df2$month, "%Y-%m-01"))
df2 <- arrange(df2, month)

and the code for the chart:
ggplot() +
  geom_bar(data = df1, aes(month, value1*5000000/5000, fill = source), stat="identity", position = "dodge") +
  geom_point(data = df2, aes(month, value2), color = "blue")+
  geom_line(data = df2, aes(month, value2), group = 1, color = "blue") +
  labs(x = "month", y="value2 (line)") +
  scale_y_continuous(sec.axis = sec_axis(~.*5000/5000000, name = "value1 (bars)"),
                     labels= format_format(big.mark = ".", decimal.mark = ",", scientific = FALSE)) +
  scale_x_date(labels = date_format("%Y-%b"),
               breaks = seq(from = min(df2$month), to = max(df2$month), by = "month")) +
  scale_fill_manual(values= c("darkseagreen4","darkseagreen", "darkseagreen3", "darkseagreen2")) +
  geom_text(aes(label=df1$value1, x = df1$month, y = df1$value1*6000000/5000, group = df1$source), position = position_dodge(1.5), vjust = 1.5, size = 3) +
  geom_text(aes(label=df2$value2, x = df2$month, y = df2$value2), vjust = 1.5, size = 3, color = "grey47") +
  theme_light()

Does anybody know, what I have to change to get the labels in the right position (for grouped bars)?
Answer: Use position = position_dodge() in both geom_text() and geom_bar() with the same numerical parameter passed to position_dodge(). E.g.:
ggplot() +
  geom_bar(data = df1, aes(month, value1*5000000/5000, fill = source), stat="identity", position = position_dodge(25)) +
  geom_point(data = df2, aes(month, value2), color = "blue")+
  geom_line(data = df2, aes(month, value2), group = 1, color = "blue") +
  labs(x = "month", y="value2 (line)") +
  scale_y_continuous(sec.axis = sec_axis(~.*5000/5000000, name = "value1 (bars)"),
                     labels= format_format(big.mark = ".", decimal.mark = ",", scientific = FALSE)) +
  scale_x_date(labels = date_format("%Y-%b"),
               breaks = seq(from = min(df2$month), to = max(df2$month), by = "month")) +
  scale_fill_manual(values= c("darkseagreen4","darkseagreen", "darkseagreen3", "darkseagreen2")) +
  geom_text(aes(label=df1$value1, x = df1$month, y = df1$value1*6000000/5000, group = df1$source), position = position_dodge(25), vjust = 1.5, size = 3) +
  geom_text(aes(label=df2$value2, x = df2$month, y = df2$value2), vjust = 1.5, size = 3, color = "grey47") +
  theme_light()

Comment: Unfortunately, the labels are still displayed for a stacked bar and not for a grouped bars....
Comment: I see labels for grouped bars (added chart image above). If this is not what you want, can you be more specific?
Comment: Sorry, I had a typo in my code - this is exactly what I was looking for. Thank you!


GDC D2 Compile: undefined reference to `_Unwind_SjLj_XYZ'

Question: I  just downloaded GDC (gcc-4.5.2-tdm-1-gdc-r575-20110723.zip) to use with MinGW-w32, and upon trying to compile/link a file, I got these errors:
<code>C:\crossdev\gdc\v2\build\mingw32\libphobos/../../../gcc-4.5.2/libphobos/gcc/deh.d:167: undefined reference to `_Unwind_SjLj_RaiseException'
c:/mingw-w32/bin/../lib/gcc/mingw32/4.5.2/../../..\libgphobos2.a(deh.o): In function `D3gcc3deh17parse_lsda_headerFPS3gcc14unwind_generic15_Unwind_ContextPhPS3gcc3deh16lsda_header_infoZPh':
C:\crossdev\gdc\v2\build\mingw32\libphobos/../../../gcc-4.5.2/libphobos/gcc/deh.d:546: undefined reference to `_Unwind_GetRegionStart'
c:/mingw-w32/bin/../lib/gcc/mingw32/4.5.2/../../..\libgphobos2.a(deh.o): In function `D3gcc3deh15personalityImplFiT3gcc14unwind_generic14_Unwind_ActionbPS3gcc14unwind_generic17_Unwind_ExceptionPS3gcc14unwind_generic15_Unwind_ContextZk':
C:\crossdev\gdc\v2\build\mingw32\libphobos/../../../gcc-4.5.2/libphobos/gcc/deh.d:294: undefined reference to `_Unwind_GetLanguageSpecificData'
C:\crossdev\gdc\v2\build\mingw32\libphobos/../../../gcc-4.5.2/libphobos/gcc/deh.d:308: undefined reference to `_Unwind_GetIP'
C:\crossdev\gdc\v2\build\mingw32\libphobos/../../../gcc-4.5.2/libphobos/gcc/deh.d:516: undefined reference to `_Unwind_SetGR'
C:\crossdev\gdc\v2\build\mingw32\libphobos/../../../gcc-4.5.2/libphobos/gcc/deh.d:521: undefined reference to `_Unwind_SetGR'
C:\crossdev\gdc\v2\build\mingw32\libphobos/../../../gcc-4.5.2/libphobos/gcc/deh.d:523: undefined reference to `_Unwind_SetIP'
c:/mingw-w32/bin/../lib/gcc/mingw32/4.5.2/../../..\libgphobos2.a(stdio.o): In function `D3std5stdio4File5closeMFZv':
C:\crossdev\gdc\v2\build\mingw32\libphobos/../../../gcc-4.5.2/libphobos/std/stdio.d:441: undefined reference to `_Unwind_SjLj_Register'
C:\crossdev\gdc\v2\build\mingw32\libphobos/../../../gcc-4.5.2/libphobos/std/stdio.d:454: undefined reference to `_Unwind_SjLj_Unregister'
C:\crossdev\gdc\v2\build\mingw32\libphobos/../../../gcc-4.5.2/libphobos/std/stdio.d:446: undefined reference to `_Unwind_SjLj_Unregister'
C:\crossdev\gdc\v2\build\mingw32\libphobos/../../../gcc-4.5.2/libphobos/std/stdio.d:454: undefined reference to `_Unwind_SjLj_Resume'
...
</code>
How do I fix this?
Comment: Did you use the TDM MinGW? http://tdm-gcc.tdragon.net/
Comment: @Trass3r: No I don't believe so. That might explain it I guess?
Comment: I think so. The prebuilt gdc packages are tailored for the TDM gcc version (as the zip filename suggests).
Answer: Mehrdad, it looks like TDM's GDC package is built with --enable-sjlj-exceptions flag, but your GCC is the official MinGW, and it is probably not build with (obsolete) SJLJ exception handling. There is a "normal" GDC package available on the Internet, I suggest you try that one.


Alert Component doesn't re-fire second time

Question: I've created an Alert component to be able to send alerts from all components in a ReactJS app, passing it through a Context.Provider. The messages, are stored in a state, and the state function is passed as the value for the Context.Provider.
However, if I try to use it once it works, but the second time it doesn't. Any ideas?
Alert.js
import React, { useEffect, useState } from "react";
import styled from "styled-components";

const StyledDiv = styled.div`
  width: 100%;
  height: 30px;
  font-size: 1.2em;
  text-align: center;
  background: tomato;
`;

const Alert = ({ message }) => {
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    if (message) {
      setVisible(true);
      setTimeout(() => {
        setVisible(false);
      }, 5000);
    }
  },[message]);
  if (visible) {
    return ;
  } else return null;
};
export default Alert;

App.js
import React, { useState, createContext } from "react";
import Alert from "./components/alert/Alert";
export const AlertContext = createContext();
function App() {
  const [alert, setAlert] = useState();
  return (
    <>
      <Alert message={alert} />
      <AlertContext.Provider value={setAlert}>
       COMPONENTS HERE
      </AlertContext.Provider>
   </>
  );
}
export default App;

Comment: where do you update the message props?
Comment: I use a useConext(Context.Provider) on my child components to work it.
Comment: weird, the useEffect should be triggered everytime the message is updated.
Comment: btw, how do you update the message? is that a string?
Comment: I use it mostly for error messaging, throught catch(e => setAlert(e.message)).
Comment: did you try console inside the useEffect when you update the message?
Comment: Yes I tried that, mounts once, then unmounts, then doesn't mount again.
Comment: you should check the useEffect, remove the dependency and try console.log(message) to see what happens when it is triggered.
Answer: just put the message as a param in your useEffect:
useEffect(() => {
    if (message) {
      setVisible(true);
      setTimeout(() => {
      setVisible(false);
    }, 5000);
   }
}, [ message ]);

That way it will actr everytime the message changes.
Comment: Tried it, it won't re-render. I actually tried this before.
Answer: useEffect takes two arguments. The first is a function, the second is an array. The function fires any time an element in the array changes.
useEffect(() => {
    if (message) {
      setVisible(true);
      setTimeout(() => {
        setVisible(false);
      }, 5000);
    }
  }, [ messsage ]);

Comment: I know what you mean, this is what I did at first. Still won't work unfortunately.
Answer: Maybe this is happening because you don't clear the setTimeout. Try something like this
  useEffect(() => {
    let timer = null;
    if (message) {
      setVisible(true);
      timer = setTimeout(() => {
         setVisible(false);
      }, 5000);
    }

    return () => clearTimeout(timer);
  }, [message]);

Comment: Thanks for reminding me to cleanup after the useEffect! But still it won't work.
Comment: hmm ok. If you try to log the message inside useEffect, can you see it the second time?
Comment: I tried looking into it like this. It just fires first time, then unmounts. then doesn't mount again.
Comment: is the error the same when you expect to see the message again or is a different error? If the error message is the same, you will not see the alert again, since the message is the same. What about if you set the message as null inside the timeout?
Answer: The issue was that the state in the App.js was not updating, so I sent it as a prop to the Alert component to update it there.
Alert.js
import React, { useEffect } from "react";
import styled from "styled-components";

const StyledDiv = styled.div`
  width: 100%;
  height: 30px;
  font-size: 1.2em;
  text-align: center;
  background: tomato;
`;

const Alert = ({ setAlert, message }) => {
  useEffect(() => {
    if (message) {
      let timer = setTimeout(() => {
        setAlert(null);
      }, 5000);
      return () => clearTimeout(timer);
    }
  }, [message]);
  if (message) {
    return ;
  } else return null;
};
export default Alert;

App.js
import React, { useState, createContext } from "react";
import Alert from "./components/alert/Alert";
export const AlertContext = createContext();
function App() {
  const [alert, setAlert] = useState();
  return (
    <>
      <Alert setAlert={setAlert} message={alert} />
      <AlertContext.Provider value={setAlert}>
       COMPONENTS HERE
      </AlertContext.Provider>
   </>
  );
}
export default App;

Everyone that helped. Thanks a lot, your input was invaluable.


Restore files from certain increments using Duplicity

Question: Given the following backup sets ...
Found primary backup chain with matching signature chain:
-------------------------
Chain start time: Tue Jun 21 11:27:26 2011
Chain end time: Tue Jun 21 11:27:59 2011
Number of contained backup sets: 2
Total number of contained volumes: 2
Type of backup set:                            Time:      Num volumes:
     Full         Tue Jun 21 11:27:26 2011                 1
     Incremental         Tue Jun 21 11:27:59 2011                 1

If i run the following command, it works (1308655646 was converted from Tue Jun 21 11:27:26 2011):
duplicity --no-encryption --restore-time 1308655646 --file-to-restore ORIG_FILE \
file:///storage/test/ restored-file.txt

However, if I run the following command, it restores the from the latest set.
duplicity --no-encryption --restore-time 2011-06-21T11:27:26 --file-to-restore \
ORIG_FILE file:///storage/test/ restored-file.txt

What am I doing wrong w/ the time? I prefer the second option only because I don't want to have to do the conversion manually.
Also, I noticed the filenames have a different timestamp...
duplicity-inc.20110621T172520Z.to.20110621T172537Z.manifest
duplicity-full.20110621T172520Z.vol1.difftar.gz

Answer: 1308655646 seconds since the epoch is 2011-06-21 11:27:26 UTC. 2011-06-21T11:27:26 is 11:27:26 in your timezone. I'll venture the guess that you live in the western hemisphere, so the date you specified was still in the future, and duplicity gave you the latest backup. Pass 2011-06-21T11:27:26Zor2011-06-21T11:27:26+00:00` to indicate a UTC date.
(I've just checked, and duplicity's time report uses the local time. Did you run it with a different timezone setting?)
Comment: yes, i've tried it with `2011-06-21T11:27:26-05:00` but I thought duplicity would use the default timezone if you don't specify a timezone.
Comment: Ok, I got it working. I was using the wrong timezone. I forgot we were in daylight savings time.