Probability of a claim being rejected or accepted using binomial distribution

Question: I am self-learning statistics. I was going through Probability and Statistics For Engineering and the Sciences by Jay L. Devore and stumbled upon the following example:

An electronics manufacturer claims that at most 10% of its power supply units need service during the warranty period. To investigate this claim, technicians at a testing laboratory purchase 20 units and subject each one to accelerated testing to simulate use during the warranty period. Let $p$ denote the probability that a power supply unit needs repair during the period (the proportion of all such units that need repair). The laboratory technicians must decide whether the data resulting from the experiment supports the claim that $p \leq 0.10$. Let X denote the number among the 20 sampled that need repair, so $X \sim \text{Bin}(20, p)$.

The explanation given is as follows:

Reject the claim that $p \leq 0.10$ in favor of the conclusion that $p>.10$ if $x \geq 5$ (where $x$ is the observed value of $X$), and consider the claim plausible if $x \leq 4$.
The probability that the claim is rejected when $p=0.10$ (an incorrect conclusion) is
  $P(X \geq 5 \text{ when } p=0.10) = 1-B(4; 20,0.1) = 1-0.957 = 0.043$
The probability that the claim is not rejected when p = .20 (a different type of incorrect conclusion) is
  $P(X \leq 4 \text{ when } p=0.2) =B(4; 20,0.2) =.630$
The first probability is rather small, but the second is intolerably large. When
  $p=0.20$ , so that the manufacturer has grossly understated the percentage of units
  that need service, and the stated decision rule is used, 63% of all samples will result
  in the manufacturer's claim being judged plausible!

I am not being able to understand how the solution connects to the given problem. Also what does the last paragraph mean?

Why has $x$ been taken as 5 to reject the claim, shouldn't it be $x=2$ since if more than 2 out of 20 components fail then the claim fails?
Why has a value of $p=0.2$ been used in the second case?

Could someone please explain it clearly?
Comment: Since this is a self-study question, please add the `self-study` tag to your post
Comment: We do treat self-study questions  differently, so as @marquis said, please add the `[self-study]` tag but also read its
[wiki page](http://stats.stackexchange.com/tags/self-study/info) so you can see what our policy is. You've been quite specific about what your issues are, rather than asking for a complete solution to the problem, which is in line with the spirit of the site - thanks.
Comment: I've tried typesetting your question a bit more neatly. Please feel free to revert any changes if I have accidentally damaged anything during the formatting. Could you clarify whether by "Devore's" you mean *Probability and Statistics For Engineering and the Sciences* by Jay L. Devore?
Comment: Yes,sir I am referring to the same book
Comment: I would model the observations using the Binomial distribution and express the unknown parameter to it as a posterior. The unknown parameter of interest can be modeled using the Beta distribution. Finally, the two parameters for the Beta distribution can be treated as hyper priors, just put flat or near flat (with Exponential?) distribution. With PyMC in Python, this can be computed pretty easily. The data is needed though.
Answer: You have to take a look at likelihood of the problem.
In this case is
$$
L={20\choose X}\, p^X \left(1-p\right)^{(20-X)}
$$
So you can calculate the p-value of the problem depending on the value X and accept or reject the hypothesis. If $p=0.1$ and X=5 means the likelihood is 0.0319214. Then you have to reject the hypothesis. If X=4 the likelihood is 0.0897788, you have to accept the hypothesis.
If $p=0.2$ we have for X=5  L=0.17456, so we can't reject the hypothesis. Why $p=0.2$? because if we don't know the real value of $p$ we have to estimate it from the likelihood maximizing it  with
$$
\frac{d L}{d p}=0\rightarrow p=\frac{X}{20}
$$
That lead us $p=0.2$ in the case X=4. I hope this help.
Comment: But in the book they have not introduced p-values and hypothesis testing yet, so I think that the logic applied to solve the problem is somewhat different from what you are suggesting. This problem has been presented in the binomial distribution chapter
Comment: Sir,could you please explain how are you inferring from the value of likelihood whether to accept or reject the hypothesis.
Comment: The value of the likelihood is the p-value. By convention must be rejected if less then 0.05.
Comment: For what I understand from the text, the idea is that there is a quite important difference between the likelihood of X>=5 and X<=4 for p=0.1, so the most simple answer is the best: p>0.1. This way of explain statistical concepts at the beginning of a beginner course is quite normal. Keep patience and everything will become rigorous with the flowing of the chapters.
Answer:
Why has x been taken as 5 to reject the claim, shouldn't it be x=2
  since if more than 2 out of 20 components fail then the claim fails?

No, you're confusing a sample proportion with a population proportion.
If you toss a coin twenty times and it comes up heads only nine times is that really inconsistent with the true probability being $\frac12$, or could something at least as far from a sample proportion of $\frac12$ easily happen with a fair coin?
To be able to say that the proportion of heads was actually different from $\frac12$ you'd want something that wouldn't be easily explained by ordinary chance (random variation) operating on a fair coin. So for example, if you had say only very few heads or very many heads come up -- so few or so many that you would be quite unlikely to see something at least that far away from 50-50 with a fair coin, then you might conclude that the proportion of heads was not consistent with $\frac12$.
Similarly in this problem, in order to say that the proportion of units needing repair is not consistent with the true probability ($p$) being no more than $0.1$, you'd look at what happens when $p$ is right on the border (since that has the best chance to produce high numbers of repairs) and if there were too many repairs in the sample to be reasonably consistent with random chance operating on the case with $p= 0.1$ then they would conclude that $p$ was bigger than $0.1$.
[If $x$ is large then either (a) $p$ is not bigger than $0.1$ but a rare event occurred - after all there's still some chance you could see at least as many repairs; or (b) $p$ is bigger than $0.1$ and a less-surprising event occurred. As you push $x$ larger, the "$p$ could still be $0.1$" explanation becomes untenable and you're led to conclude that the null isn't a reasonable explanation. You choose where you will draw the line ahead of time in such a way that the probability you'll reject when the null hypothesis ($p\leq 0.1$) is small while keeping in mind that the smaller you make it, the more the risk of the other kind of error increases.]
They've chosen to make their rule to reject the hypothesis "reject if $x$ is at least $5$" which (as they explain) makes the probability of rejecting when $p$ really is $0.1$ about 4.3%. (This is the type I error rate at $p=0.1$. This highest probability you will reject the hypothesis when it's actually true is called the significance level.)

Why has a value of p=0.2
  been used in the second case?

It's just a convenient example value; they could have chosen some other value that was larger than 0.1 and calculated the probability of that kind of error (failing to reject when $p$ is actually larger than $0.1$, which is called type II error). It's interesting to look at a case that is substantially larger because then you can't really say "well, it's pretty close"; they chose a value that was clearly larger than $0.1$ for which the probability of failing to reject the null hypothesis was quite high. They could have chosen say $0.25$ or $0.15$, but $0.101$ would probably not be especially interesting to consider, especially if you're only calculating this probability at one value of $p$ that's larger than $0.1$.
Alternatively they could have looked at a sequence of values (e.g. $p=0.15,0.20,0.25,0.3$) and seen how likely they would be to fail to pick up that $p$ was too large for each one (this is actually a good thing to do, but in this case it wasn't done because they're trying to keep it simple -- the method is the same, it's just the numbers that change)
Comment: That matches my rough understanding of the solution. Thank you, for the explanation.


Reducing exponents mod n

Question: Say I have
5^(52) mod 22
How do I reduce this?
I know if 22 was a prime number, then I could simply I could simply reduce 5^(22) * 5^(22) * 5^(8) which would become 5^(8) mod 22 but that doesn't work in this case.
Answer: $\begin{eqnarray}{\bf Hint} &&{\rm mod}\ 11\!:\  5^{10}\equiv 1\ \ \rm by\ \ Fermat's\ \ little\  Theorem\\
&&{\rm mod}\ 2\!:\ \ \ 5^{10}\equiv 1\ \ {\rm by}\ \ 5\equiv 1\\
\Rightarrow&&{\rm mod}\ 22\!:\ \color{#c00}{5^{10}\equiv 1}\,\Rightarrow\,\,5^{52} = 5^2 \color{#c00}{(5^{10})}^5 \equiv 25\color{#c00}{(1)}^5\equiv 3\end{eqnarray}$
Answer: Hint: $5^2 \equiv 3$, and $3^3 \equiv 5$, which means $5^{6}\equiv 5$.
Comment: Ok, so if I determine that 5^2 is congruent to 3 then can I just say 5^52 is congruent to 3 without determining that 5^6 is congruent to 5 because 5^52 = 5^2 * 5^2.....5^2
Comment: @user2827048 You can only say $5^{52} \equiv 3^{26}$ given that $5^2\equiv 3$.
Comment: Ok, here's how I solved it using what you described: 5^52 is really just (5^2)^26 making it 3^26. 3^26 can be rewritten as 3^21 and 3^5 reducing to (3^3)^7 * 3^3 * 3^2. This then becomes 5^7 * 5 * 3^2. This is 5^8 * 3*2. This can be rewritten as (5^2)^4 * 3^2 which is 3^4 * 3^2. This is 3^6. which is 3^3 * 3^3. This is 5 * 5 which is 25. 25 mod 22 is 3.

Reducing exponents mod n


What is the best way to host node.js app on Windows?

Question: I have a RESTful API implemented on nodejs which I have to host on Windows. Now app is just simple RESTful service, maybe in future I will implement the backoffice for it to manage users, display statistic etc. So for now app is just an API, but maybe in future it will be extended to serve few pages with dynamic content, I am not going to provide access to the static content (except regular content for web apps: favicon, images, css, js files etc).
After research I see few options to host my app on Windows:

Use windows service to run the node server.
Use IIS and IISNode module as a front server.
Use Nginx on Windows as a front server (I didn't work with Nginx, but it seems that it can be used to host node and can be used on Windows).

My questions:

As I understood it is better to use some front server. This approach has a lot of benefits: you can manage app state, logs, domain names etc. What are the benefits of using windows service to host the app?
How to choose between IIS and Nginx. Is it wise to use Nginx on Windows, does it have some advantages?
Answer: IISNode has a number of benefits which are outlined on the project page. https://github.com/tjanczuk/iisnode/wiki
I would lean that direction primarily because if you have to host it on Windows, that indicates there is someone who knows how to manage Windows servers and that would typically include IIS. If you set up your own Windows service, you become responsible for scalability and recovering the process if it crashes.


Serializar List JSON em FLutter

Question: Tenho uma aplicação em Fluter, e possuo um Json de retorno com List.
Queria serializar a Lista para exibi-la em certo momento, porém não encontrei como fazer isso.
Um exemplo do meu código:
class ResultLogin {
 final String token;
 final List<ZLoginResultSchema>schemas;

  ResultLogin({this.token, this.schemas});

  ResultLogin.fromJson(Map<String, dynamic> json):
    token      = json['token'],
    schemas    = new List.from( json['schemas']);

Map<String, dynamic> toJson() =>
  {
    'token':    token,
    'schemas':  schemas,
  };
}

Minha Classe ZLoginResultSchema:
class ZLoginResultSchema  {
 final String name;
 final String fullname;

 ZLoginResultSchema({this.name, this.fullname});

 ZLoginResultSchema.fromJson(Map<String, dynamic> json):
    name    = json['name'],
    fullname = json['fullname'];

 Map<String, dynamic> toJson() =>
  {
    'name': name,
    'fullname': fullname,
  };
 }

No ResultLogin.fromJson o token funciona, porém a lista de schemas não, como serializar uma lista de Json?
Comment: Coloque também o código da sua classe `ZLoginResultSchema`.
Comment: Adicionei o código, desculpe havia esquecido.
Comment: Se a resposta resolveu seu problema marque-a como aceita. :)
Answer: Note que você está tentando mandar o Dart serializar/deserializar uma lista com um objeto personalizado ZLoginResultSchema, sem que a linguagem tenha a menor ideia de como fazer isso, afinal esse é um objeto personalizado que você criou. Caso fosse uma lista de String, até funcionaria.
Você tem que utilizar o método fromJson da classe ZLoginResultSchemapara que o Dart entenda como ele deve passar o json para um objeto. Então a classe ResultLogin ficaria:
class ResultLogin {
  final String token;
  final List<ZLoginResultSchema> schemas;

  ResultLogin({this.token, this.schemas});

  factory ResultLogin.fromJson(Map<String, dynamic> json) {
    var list = json['schemas'] as List;
    List<ZLoginResultSchema> schemas =
        list.map((z) => ZLoginResultSchema.fromJson(z));

    return ResultLogin(token: json['token'], schemas: schemas);
  }

  Map<String, dynamic> toJson() => {
        'token': token,
        'schemas': schemas,
      };
}

Agora note no método fromJson a necessidade de ter que transformar o Map do json para uma List e converter um a um com o ZLoginResultSchema.fromJson(z). Não é nem um pouco prático, certo?
Por isso não é recomendável fazer essa transformação do json de forma manual como você está fazendo. Para isso existem ferramentas como a lib json_serializable que utiliza o build_runner para gerar esses códigos de conversão automática do json, além de ter outras diversas funcionalidades que facilitam e muito nossa vida.
Recomendo que você utilize ela, para mais detalhes.
Answer: O seu objeto pode ficar da seguinte forma:
class ResultLogin {
 final String token;
 final List<ZLoginResultSchema>schemas;

  ResultLogin({this.token, this.schemas});

  ResultLogin.fromJson(Map<String, dynamic> json) {
    token = json['token'],
    if (json['schemas'] != null) {
     this.schemas = List<ZLoginResultSchema>();
     json['schemas'].forEach((obj) {
      schemas.add(ZLoginResultSchema.fromJson(obj));
     });
    }
  }

  Map<String, dynamic> toJson() {
   final Map<String, dynamic> data = new Map<String, dynamic>();
   data['token'] = this.token;
   data['schemas'] = this.schemas.toJson();
   return data;
  }
}

Ao utilizar o ForEach estaremos pegando cada item da lista e convertendo o seu Map para um objeto e depois adicionando-o a lista.
Caso você possua a estrutura do JSON, preferencialmente tendo ele preenchido utilize o JSON to Dart.

Serializar List JSON em FLutter


analysis for different kinds of in vivo experiments with multiple groups (ANOVA vs. t-test)

Question: Many in vivo experiments with mice involve four groups. For example, in oncology models often there are two treatments (one experimental and one standard of care) that are given alone, jointly, and then compared to a vehicle control. The standard analysis for this type of experiment appears to be a two-way ANOVA test.
However, in my case the experimental design is quite different and with it the hypothesis to be tested. I also have four groups of mice with two independent factors. Here, one is a treatment that induces a disease state while the other is the mutational status of a gene. My hypothesis, based on a variety of additional data points, is that the mutation in the gene will suppresses the disease.
It was suggested to me that, as above, I should perform a two-way ANOVA to analyze the data. However, I believe that in this case the untreated animals are merely a control to show that my disease-causing intervention is working as expected. In fact, the only comparison I am interested in is between the wild type and mutation group of mice that were treated to induce the disease. Furthermore, my hypothesis is that the gene will suppress the disease (and not merely affect it in an unknown direction).
So my contention is that the 'correct' test in this case would be a simple one-tailed student's t-test between the wild type and mutant group of mice on the disease-inducing treatment.
Answer: If I understand correctly, you have two groups (control and treatment) and they are independent. So this makes a two-samples independent t-test appropriate.
Note that if your dependent variable is:

quantitative: you can indeed compare the two groups with:

a Student t-test if normality is respected in both groups and variances are equal between groups,
a Welch t-test if normality is respected in both groups but variances are unequal or
a Wilcoxon test if normality is not respected, no matter if variances are equal or not. See more details about the different versions of the t-test.

binary: you would need to perform a Chi-square test for independence, since you have two qualitative variables. See how to do so in R or by hand.

Regarding the direction of the test when your dependent variable is quantitative, if you want to test whether the mean in the treatment group is lower than in the control group, you can indeed test:

$H_0: \mu_c = \mu_t$
$H_1: \mu_c > \mu_t$

When your dependent variable is qualitative, in order to test for the "direction" you could compute the odds ratio. The odds ratio, in addition to testing if there is a significant association between the two variables (which can be found thanks to the Chi-square test for independence), allows you to quantify this association.
Hope this helps.
Regards,
Antoine
Comment: Thank you, Antoine. I believe this answers my question. However, just to clarify: I have in total four groups coming from two independent variables (disease-inducing intervention and genetic background). But the two groups without the disease-inducing) are merely there as a baseline to show that the experimental intervention is working well to induce the disease. My hypothesis is exclusively focused on whether or not the genetic background affects the disease--hence the proposed two-group approach for analysis.


Is there any easy way to find the positive integer solutions $(x,y,z)$ from this linear equation?

Question: The equation is like this:
$3^x -2^y = 19^z$
It seems that no way to find the solution except using trial and error.
I got only one solution:
$x=3, y=3, and z= 1$ by using trial and error.
But, when I use the software, I got the bad value:
http://www.wolframalpha.com/input/?i=3^x+-2^y+%3D+19^z
Is there any elegant way to get the solution(s) ?
Thanks
Comment: you should put some constraints on the variables else x = 2, y = 3 and z = 0 is also a solution.
Comment: Do the solutions need to be integers? If not, then you have a two-parameter family of solutions (say, indexed by $y$ and $z$): $(\log_3(2^y+19^z), y, z)$.
Comment: @Tom, yes the solution must be integer. Sorry, I forgot to add it. Thanks
Comment: Hmm... A bit sad that $3$ is a primitive root modulo $19$.
Comment: Now, how can I get the way to find the solution? or at least, is there any clue to solve this problem? Thanks
Answer: If $x$ or $z$ is even, there is one and only one solution, namely, $x=2, y=3, z=0$, if $x$ is odd and is divisible by $3$, there is one and
only one
solution namely, $x=3, y=3, z=1$
given; $3^x-2^y=19^z$.........$eqn 1$
we have, $-2^y \equiv 1 \pmod 3$ or $2^y \equiv 2 \pmod 3$ or $2^{y-1} \equiv 1 \pmod 3$ hence $y-1 \equiv 0 \pmod 2$ by Euler-Fermat theorem. So, y must be odd. If $y>1$ Eqn1 becomes $(-1)^x \equiv (-1)^z \pmod 4$, so that $y$ and $z$ have the same parity. If $x>1$, eqn1 becomes $-2^y \equiv 1 \pmod 9$ and hence, by Euler-Fermat theorem $y \equiv 0 \pmod 3$. $x, y, z>1$, let $x$ be even, then eqn1 becomes $(-1)^k-2^y \equiv 1 \pmod 5$ for $x=2k$, if $k$ is even, the given equation has no solution, if $k$ is odd, i.e $x \equiv 2 \pmod 4$ then $2^y \equiv 2 \pmod 5$ and by Euler-Fermat (E-F), $y \equiv 1 \pmod 4$, similarly, if $x$ is odd, there is no solution if $x \equiv 1 \pmod 4$. Working $\pmod 8$ and using Euler-Fermat, we find, if $z$ is even, then $z \equiv 0 \pmod 4$, if $z$ is odd then, $z \equiv 1 \pmod 4$. Now if $x=2m$, then $z=2n$ and the given equation is $3^{2m}-19^{2n}=2^y$ or $(3^m-19^n)(3^m+19^n)=2^y$, we must have $(3^m-19^n)=2^r$ and $(3^m+19^n)=2^{y-r}$ where $3^m=2^{r-1}+2^{y-r-1}$ and  $19^n=-2^{r-1}+2^{y-r-1}$ from which we must have $r-1=0$ since  $r<y-r$. The last equation becomes $19^n=-1+2^{y-2}$, now, since $4|z$ it follows that $2|n$, and hence, $19^n$ is a perfect square, hence $19^n \equiv 1 or 0 \pmod 4$ but for $y>3$, the last equation becomes $19^n \equiv -1 \pmod 4$ a contradiction. Hence, if $x$ or $z$ is even and $y>3$, there is no solution, for $y \leq 3$ solutions can be checked manually. We now turn to the case where $x$ is odd. If $x$ is odd and divisible by $3$, then since $3|y$, the left hand side of the given equation is factorizable and by considering the factors, following a method similar to the above, $\pmod 4$, shows there is no solution except the case presented above....NOTE; if $3|x$ then $3$ does not divide $z$ otherwise, since $3|y$, by Fermat Last Theorem there is no solution. If $3$ does not divide $x$ it may divide $z$ and similar to what is shown above, the analysis can be carried a step further by considering the factors of the right hand side of the equation $3^x=2^y+19^z$, in which case one finds, working in $\pmod 4$, there is no solution.


The axiom of regularity and the real numbers

Question: I'm having trouble understanding how there can be sufficiently many distinct elements for $\mathbb{R}$ to exist with its properties and yet still be a set.
(The <code>--verbose</code> explanation that follows includes all the bits that friends didn't understand immediately – just skip ahead once you got the idea of each section.)
1. sets are trees
Recall that sets are essentially just (weird) trees, and everything can be encoded as sets:
$\newcommand{\set}[1]{\{#1\}}$
$\newcommand{\sO}{\emptyset}$
$\newcommand{\sSO}{\set{\sO}}$
$\newcommand{\sSSO}{\set{\sO,\sSO}}$
$\newcommand{\sSSSO}{\set{\sO,\sSO,\sSSO}}$
$\newcommand{\sSSSSO}{\set{\sO,\sSO,\sSSO,\sSSSO}}$

This tree/set could represent $\set{\sO,\set{\sSSO},\sSSSSO}$ or $\set{\sO,\set{2},\set{0,1,2,3}}$ or $\set{\sO,\set{(0,0)}, 4}$ or … – doesn't really matter.  And the one on the left here…

…is really the same set as the one on the right, because the branches 2, 4, and 6 from the root are actually the same element.  (They just look different because they are shown with "duplicate elements", which don't matter – look at the "triangle" at the end of the left set's rightmost branch:  It depicts $\set{\sO,\sO}$, which is actually just $\set{\sO}$.  You can keep dissecting stuff manually to identify the actual elements and get rid of the "ghosts"… but you don't need to:)
2. bounded size from bounded depth
There's an easier way to show that the example set above can't be that big:  Look at the "depth" / rank of the tree – it limits the number of possible elements, and thereby the possible number of elements.  Here's all sets of depth at most $d$:

(…and so on, giving at most 1, 2, 4, 16, 65536, 20[…19725 other digits…]36, … elements.)
The example set in the previous image has depth three, which means that all its elements have depth at most two, so there are at most 4 different elements available for forming the set.  This means that the set on the left can't have the "claimed" size of 6, but can really contain at most 4 (distinct) elements. So we don't need to bother looking at the elements in detail to get an upper bound on the size, all we need to know is (a bound on) the depth.
3. the axiom of regularity / no infinite $\in$-chain
The axiom of regularity implies that no set has an infinite descending $\in$-chain (which is why $\in$-induction works).  And so bounding the size of the set by the rank / maximum depth should work for all sets, right?  That would give an upper bound of $2\uparrow\uparrow d$ elements for any set.
4. the set of real numbers
We also know that the real numbers are uncountable, i. e. the elements of $\mathbb{R}$ cannot be put into 1-to-1 correspondence with the elements of $\mathbb{N}$.
5. the problem
But if there cannot be infinite $\in$-chains, that means the depth is bounded, which bounds the number of possible distinct elements, which… keeps things countable?  But then where are all those elements of $\mathbb{R}$ coming from?
What's the trick that makes this work without blowing up (i. e. no infinite $\in$-chain from which you could derive nonsense) while still preventing the collapse to countability?
Comment: Regularity does *not* say that "there can be no infinite $\in$ chains", just no infinite *descending* chains. More importantly, it is **not** true that "there are no infinite chains" implies "depth is bounded." You could have chains of arbitraty, though finite, depth. To claim that depth is bounded would be like claiming that because each natural number is finite, it follows that the size of a natural number is uniformly bounded by some $M$... which is clearly false.
Comment: (That is, it is *not* true that you can "bound the size of the set by the rank/maximum depth"; there may be no maximum depth, just like there is no maximum natural number, even though each of them is finite)
Comment: An infinite $\in$-chain isn't really "nonsense"--if you reject the axiom of regularity, it's perfectly consistent with all the other axioms to have such sets, and doesn't have any affect on the vast majority of mathematics.
Comment: @EricWofsey Yes, of course there's all the co-inductive stuff / the anti-foundation axiom / … that give nice different settings. But that _plus_ the axiom of regularity would explode. (Unless you manage to keep them sufficiently apart in some way.)
Answer: A set does not have to have bounded depth!  Consider the set $S=\{\emptyset,\{\emptyset\},\{\{\emptyset\}\},\{\{\{\emptyset\}\}\},\dots\}$.  Each individual path down the tree of this set is finite, but there are infinitely many branches that split up at the first level and each has a different length, so there can still be infinitely many elements and unbounded depth.
Now note that we can take not just this set $S$ but any subset of it.  Since $S$ is infinite, there are uncountably many different subsets of $S$.  If we take the set $\mathcal{P}(S)$ of all subsets of $S$, we get an uncountable set.  This set still can be represented by a tree with no infinite branches, it just branches a lot in the first two levels!
Comment: Where you have "no infinite branches" near the end, do you mean "no infinite paths"? It seems like the root node and some of its direct children will still have an infinite number of children.
Comment: @aschepler Yes, the first level(s) will have _any_ number of children, but any particular path terminates.


How to find a point from a 2D triangle with two known points and an angle

Question: i have two points: (5, 10, 0) 'A' and (10, 10, 0) 'B', what is the third point of my triangle if 'B's interior angle is 45degrees? and it's 45degrees horizontal to the axis, not vertical.

*The third point lies in a plane PARALLEL on the x-z plane.
Comment: You mean it would be in the $xy$ plane then? You actually just need to visualise or draw a sketch.
Comment: This question is far too unclear to give an adequate answer.  Parallel (to what?) .... not parallel but "vertical" (vertical with respect to what?)  As has been very well advised:  by other users: "You actually just need to visualise or draw a sketch"....and "The best way to learn these types of problems is to learn basic trigonometry and then use a little 3D.  visualization."
Comment: Do you mean the third point lies in a plane parallel to $xz$-plane ?
Comment: yes, and i added side lengths too
Comment: @samjoe updated post
Comment: The third point is simply $(10-7\cos(45^{\circ}), 10, 7\sin(45^{\circ}))$
Comment: @samjoe okay is '10' in this equation drawn from point A? or B? and/or both? is this equation a standard equation? how does it work? what is it called?
Comment: $A$ and $B$ lie in $xy$ plane. The x-coordinate of $B$ is $10$. So $x$ coordinate of third point is $10-7\cos(45^{\circ})$. Actually we are taking projection of side with length $7$ on $AB$. Since it lies in a plane parallel to $xz$, the $y$ coordinate is same as the other two points, ie 10. The $z$ coord is the *height* of the triangle, $7\sin(45^{\circ})$
Comment: @samjoe last question, IF 45 was not parallel, but vertical instead, how do i get the new point?
Answer: IMHO, the question is ill-posed.
In general the third point $C$ can lie anywhere on a single naped right circular cone with $B$ as apex, (extended) line $AB$ as it's axis and generating angle = 45 degress.
Comment: not if i specify that it's horizontal
Comment: Even then, $C$ can lie anywhere on a straight line which make 45 degree angle with $AB$.
Comment: you are correct, i did not specify the side measurements, this should help now.
Comment: An answer that comments that a question is ill-posed should be a comment, not an answer
Answer: Looking at your edited figure, co-ordinates of $C$ would be $x = 10 - 7 \cos{45 ^\circ}$, $y = 10$ and $z =  7 \sin{45^\circ}$.
Comment: thank you, but why is 'cos' in x? and 'sin' in y? what if  45^ was vertical? where can i learn more about these equations? i need to know how to use them
Comment: Sorry, I missed your last point that $C$ lies in x-z plane. Edited the answer. The best way to learn these types of problems is to learn basic trigonometry and then use a little 3D visualization.


Check for user input in the console while running other code?

Question: Okay, I am new to c#, so I don't have a great understanding of how some stuff works, but I am running a discord bot and I am trying to take user input from the console without stopping the other tasks in the code. When I use something like console.Readline() it will wait for user input before running the rest of the code. Is there any way to have the rest of the code running while also checking for user input? I'm sorry if any of this doesn't make sense but feel free to ask me any questions I would appreciate any help.
Here is the working code:
class Program
{
    public static void Main(string[] args)
    => new Program().MainAsync().GetAwaiter().GetResult();

    private DiscordSocketClient _client;
    public async Task MainAsync()
    {
        _client = new DiscordSocketClient();
        _client.MessageReceived += CommandHandler;
        _client.Log += Log;

        var token = File.ReadAllText("token.txt");

        await _client.LoginAsync(TokenType.Bot, token);
        await _client.StartAsync();

        // Block this task until the program is closed.
        await Task.Delay(-1);
    }

    private Task Log(LogMessage msg)
    {
        Console.WriteLine(msg.ToString());
        return Task.CompletedTask;
    }

        public Task CommandHandler(SocketMessage message)
    {
        //variables
        string command = "";
        int lengthOfCommand = message.Content.Length;
        Random rnd = new Random();

        command = message.Content.Substring(0, lengthOfCommand).ToLower();

        string[] greetings = { "hello", "hey", "hi", "sup", };
        string[] greetingResponse = { $"Hello {message.Author.Mention}", $"Hey {message.Author.Mention}", $"Hi {message.Author.Mention}" };

        int greetingsIndex = rnd.Next(0, greetingResponse.Length);

        for (int i = 0; i < greetings.Length; i++) // greetings
        {
            if (command.Equals(greetings[i]))
            {
                message.Channel.SendMessageAsync($@"{greetingResponse[greetingsIndex]}");
            }
            else if (command.Contains($"{greetings[i]} "))
            {
                message.Channel.SendMessageAsync($@"{greetingResponse[greetingsIndex]}"); // goes through the string array and chooses a random response
            }
        }
}

Comment: @MichałTurczyn `Main` can be `async`.
Comment: You are giongg in the right direction - multithreading/asynchrony is the way to do it :) But you have some major mistakes: entry point of a program must have signature `public static void Main(string[] args)` (or you just run this async method from your main method which is OK). `File.ReadAllText` returns string, which doesn't expose `Token` property. Also I do not see declarationo of `TokenType` - is this a global variable?? Please return with working code and explicitly say what you have problem with. Now you are asking to write code for you.
Comment: Thanks for the responses! I added the running code to the post.
Answer: what you're looking for is threading
read more here
read more here
try this:
new Thread(() => {
    // things you want to do async
}).Start();


Find the Taylor expansion of $f(x-yh)$

Question:
Find the Taylor expansion of $f(x-yh)$.

The exercise don't say if $h$ and $y$ are variables too. I tried to do a Taylor series at $yh$
$$f(x)=f(x-y)+\frac{f'(x-yh)}{1!}(x-yh)+\frac{f''(x-yh)}{2!}(x-yh)^2...$$
But the answer says that Taylor expansion of $f(x-y)$ is
$$f(x-yh)=f(x)+hyf'(x)+\frac{1}{2}h^2y^2f''(x)+o(h^2)$$
Anyone can help me understand it?
Comment: Hm, I wanted to say its a textbook error, but it doesn't seem to be for any $x^n$.  Intriguing...
Comment: @SimpleArt This results is from a slide that I found in a course, but I don't know how to get it.
Answer: From the answer, it seems obvious that they expand $f(x-\epsilon)$ around $\epsilon=0$. So, $$f(x-\epsilon)=f(x)-\epsilon  f'(x)+\frac{1}{2} \epsilon ^2 f''(x)+O\left(\epsilon ^3\right)$$ and replaced later $\epsilon$ by $hy$.
Not only the $x^n$ are missing (just as Simple Art commented) by it seems that there are also sign errors.
Also, what they give cannot be $O\left(h^2\right)$ but $O\left(h^3\right)$ instead.
We can bet that, once more, the textbook contains typo's.

Find the Taylor expansion of $f(x-yh)$


weblogic AS: application deployed on a cluster with two managed servers

Question: I'm on Weblogic AS 10.3.5, I have two managed servers pointed to a cluster, so I have two url, one for the first managed server, the other one for the second.
I will deploy my application on the cluster, so will I reach it on both the url? will the application deployed and running on both the servers?
How does it work? Can you give me some references, please?
Is it clear?
Thanks a lot!
Comment: check this http://stackoverflow.com/questions/3883516/how-does-weblogic-clustering-work
Answer: First, you shouldn't be using WebLogic 10.3.5 anymore since it has reached the last stage of support called Sustained Support. Consider to upgrade at least to WebLogic 10.3.6.
Related to your question, I believe you are talking about a Web Application and how to access it. First you need to read about Load Balancing in a Cluster. For the web part (JSP and Servlets) basically you have to options: setup a Web Server (like Apache HTTP) to make use of the WebLogic Plug-in, that will then be connected to the WebLogic cluster. The other easier option is to simply use an LBR (load balance router hardware).
These are the "software" solutions you have for Load Balancing your web application in a clustered WebLogic:

WebLogic Server supports the following Web servers and associated
  proxy plug-ins:

WebLogic Server with the HttpClusterServlet
Netscape Enterprise Server with the Netscape (proxy) plug-in
Apache with the Apache Server (proxy) plug-in
Microsoft Internet Information Server with the Microsoft-IIS (proxy) plug-in

You can read more about this options at the Configure Proxy Plug-ins documentation page for WebLogic 10.3.6.
Comment: You need an adress to point to. A cluster does not have an address. It is a set of addresses. :-)
Comment: thank you, i'm going to read all the cool stuff you wrote :D So is there no way to contact directly the cluster and been switched to one of the managed servers... :( Thank you


Rule action to remove a product from the cart? (using the commerce module)

Question: I'm using the commerce module to show product in a site.
I need to create a rule on the event of Calculating the sell price of a product which should involve removing products from the cart in a given condition.
I see that there is an action to Add a product to the Cart. But how do I remove a product from the cart?
Should I use the Remove from list action?
Answer: Check what rszrama, the Drupal Commerce leader, says about this:

If you find and delete the line item, it should work just fine. You can do this with the "Delete entity" action. You could also just unset the price of the line item you want deleted during "Calculating the sell price of a product." That's what the "Unset the price of disabled products in the cart" default rule does, so you can refer to it for an example. Unsetting the price just involves setting the amount to NULL (i.e. no value, not 0).

http://drupal.org/node/1267156#comment-4937288
Comment: Thanks, I've trying for a long time.  The Delete Entity action worked perfect! :)
Answer: Another way of doing this is to follow RFay's great video on using a component and looping. This method can be combined with Commerce Rules Extra to build a lot of complex business workflows for your cart.


Easiest way to expose existing data in secondary database as entities?

Question: Given a "node-like" database table in an "external" or "secondary" database, what's the easiest way to expose them as entities?
Documentation for the entity module makes it seem easy for data stored in the local database, but I'm not sure how that can be translated to another db.
Comment: I assume you need proper fields so you can interact with the rest of Drupal?
Comment: I'll take what I can get :) If I can expose more data as fields, that's great.
Comment: Depending on where the external datasource is that might introduce a bit of a lag...could you just define or re-use an existing entity type and write something (e.g. a class for the migrate module) to sync entities on a schedule?
Comment: I'm currently looking at this video which promises to answer my question: http://blip.tv/drupalcondenver/drupalize-your-data-use-entities-6039543
Answer: Some googling has revealed that the easiest solution is

Declare a new entity
Create a new Controller class for it that knows how/where to apply data operations.
Declare all your metadata as properties as opposed to fields.

I hope I'll be able to expand on this answer once I actually try it out. :)


Programa parando de funcionar em C

Question: Olá, eu estou tendo um problema com um código meu em C. É um trabalho para faculdade e o código é simples, é um script pra receber dados (usuários e produtos), vender os produtos e listar os clientes existentes, eu fiz a parte de cadastro de usuário e produtos normalmente, porém na parte de pesquisar se um usuário já existe está dando um erro, ele simplesmente dá "o programa parou de responder".
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char nomeCliente[100][50];
int cpf[50][30];

char descricaoProduto[20][30];
int valorDeVenda[50];

int i;

int menu;

void cadastroClientes();
void cadastroProduto();
void venderProdutos();

int main()
{
    printf("1 - Cadastrar usuário");
    printf("\n2 - Cadastrar produto\n");
    printf("3 - Vender Produtos\n");
    printf("4-Relatorios\n");
    printf("\nOpção a ser acessada: ");
    scanf("%d", &menu);

    switch (menu)
    {
    case 1:
        cadastroClientes();
        break;
    case 2:
        cadastroProduto();
        break;
    case 3:
        venderProdutos();
        break;
    }
}

void cadastroClientes()
{
    static int linha;
    do
    {

        printf("\nNome: \n");
        scanf("%s", &nomeCliente[i]);
        printf("\n CPF: ");
        scanf("%s", &cpf);
        printf("\ndigite 1 para fazer outro cadastro ou outro valor para voltar ao menu ");
        scanf("%d", &menu);
        if (menu != 1)
        {
            main();
        }
        linha++;
    } while (menu == 1);
}

void cadastroProduto()
{
    do
    {
        printf("\n nome do produto: ");
        scanf("%s", &descricaoProduto);
        printf("\npreço de venda ");
        scanf("%s", &valorDeVenda);
        printf("\n digite 2 para fazer outro cadastro de produto ou outro número para voltar ao menu ");
        scanf("%d", &menu);
        if (menu != 2)
        {
            main();
        }
    } while (menu == 2);
}

void venderProdutos()
{

    char cliente;

    printf("digite o nome do cliente: ");
    scanf("%c", &cliente);

    for (i = 0; i < 100; i++)
    {
        if (strcmp(nomeCliente[i], cliente) == 0)
        {
            printf("encontrou");
        }
        else
        {
            printf("erro");
        }
    }
}

o erro está em algum lugar na função "venderProdutos()", especificamente no strcmp. eu testei a comparação entre o "nomeCliente, "a")" e deu certo, então creio que seja algum problema no índice ou algo assim.
Answer: Você declarou a variável cliente como tipo char.
Isso significa que ela irá armazenar um único caractere, sem sequer ser seguido por um null terminator, como as strings em C.
Tente declara-lo como um array de caracteres de tamanho 50 (mesmo tamanho que você está armazenando no nomeCliente) e então faça o scanf utilizando %s para ler uma string, ou utilize %49s para se certificar que a entrada não irá estourar o tamanho do seu array.
int venderProdutos()
{
    char cliente[50];

    printf("digite o nome do cliente: ");
    scanf("%49s", cliente);

    for (i = 0; i < 100; i++)
    {
        if (strcmp(nomeCliente[i], cliente) == 0)
        {
            printf("encontrou");
            return i;
        }
    }

    printf("erro");
    return -1;
}

Também seria bom receber quantos clientes você tem populado no array de nomeCliente na função, dessa forma você só percorreria esse número ao invés de percorrer todas as 100 posições, afinal, não sabemos nem se todas as 100 posições estão preenchidas.
Comment: muito obrigado mano, era isso mesmo
Comment: se puder me ajudar com outro probleminha que to enfrentando, agradeço...
eu tenho também que listar vários tipos de dados, eu to fazendo isso usando o seguinte trecho de código: "int i;

    for (i = 0; i < 100; i++)
    {
        printf("%s \n", nomeCliente[i]);
    }"

porém o "erro" tá que ele tá mostrando 100 resultados, que é o tamanho que coloquei ali, porém eu quero que seja mostrado apenas os clientes existentes, se houver só 1, só poderá mostrar 1 e assim por diante, do modo que fiz ele está mostrando sempre 100 resultados, e quando não há nenhum cliente ele mostra 100 (nulls)
Comment: agora que percebi que é isso mesmo que você tinha dito ali embaixo, porém mantenho a pergunta porque não sei bem como eu faria isso do jeito que você disse
Comment: C não mantém a contagem de quantos itens do array estão populados, você tem que declarar uma variável para manter essa contagem. Inclusive parece que você já declarou a variável `linha` (a qual você deveria inicializa-la com 0). Apena use ela como delimitador `for (i = 0; i < linha; i++)`

Programa parando de funcionar em C


Prove $\mathcal{R}:=\left\{\left(a,b\right)\mid a\le b\right\}$ is not symmetric

Question: Given a homogeneous binary relation $\mathcal{R}$ over a set $A$,and is defied as:
$$\mathcal{R}:=\left\{\left(a,b\right)\mid a\le b\right\}$$
Prove $\mathcal R$ is not symmetric.

I don't understand why $\mathcal R$ is not symmetric,indeed it's symmetric if :
$$\forall a,b \in A:a\le b \implies b\le a $$
Or in other words:
$$\forall a,b \in A$$ one of these are true:
$$a < b \implies b< a $$
$$a < b \implies b= a $$
$$a = b \implies b< a $$
$$a = b \implies b= a $$
As it's seen,the last one is true,and that's why I think the relation is symmetric.
Comment: $1\le 2$. So $2\le1$?
Answer:
$$\forall a,b \in A:a\le b \implies b\le a $$
Or in other words:
$$\forall a,b \in A$$ one of these are true:
$$a < b \implies b< a $$
$$a < b \implies b= a $$
$$a = b \implies b< a $$
$$a = b \implies b= a $$

You are wrong.
Your second statement is not equivalent to the first. The first statemtent says that for every pair $a,b\in $A, the statement $a\leq b\implies b\leq a$ is true. The statement $a\leq b\implies b\leq a$ is not the same as
$$(a < b \implies b< a) \lor (a < b \implies b= a)\lor (a = b \implies b< a) \lor(a = b \implies b= a) $$
and you can quite clearly show this by taking $a=1$, $b=2$.

More generally, your argument is based on assuming that, for any collection of logical statements $A, B, C$, the statement $$(A\lor C)\implies(B\lor C)$$ is equivalent to the statement
$$(A\implies B)\lor(A\implies C)\lor(C\implies B)\lor (C\implies C)$$
but this is not the case.

(for clarity, in your argument, $A$ was the statement $a<b$, $B$ was the statement $b<a$, and $C$ was the statement $a=b$)

In fact, if you wanted to write out the logical implication (not that I recommend it), then what you would need to consider is that $$(P\lor Q)\implies (R)$$ is equivalent to:
$$\begin{align}(P\lor Q)\implies R&\sim \neg (P\lor Q)\lor R\\&\sim (\neg P \land \neg Q)\lor R \equiv (\neg P\lor R)\land(\neg q \lor R)\\&\sim (P\implies R)\color{red}{\land}(Q\implies R)\end{align}$$
Note the highlighted $\land$ appearing in the statement which is nowhere in your argument.
Comment: @45465 Exactly. Your error was a purely logical one. If you consider my answer useful, also consider accepting it.
Comment: @45465 Oh, right! That was juist a typo on my part.
Comment: @45465 It's a little sloppy to say the statement is **always** false. It is actually **true** if $a=b$ (since the first statement of the conjunction becomes $F\implies T$, which is true, and the second becomes $T\implies T$, which is also true. But yeah, the idea is correct. The statement is not true for every pair $a,b$, and in particular, it is not true if $a<b$ is true. And even more particular, it is not true for $a=0, b=1$ (and this is enough to prove the original relation is not symmetric).
Comment: @45465 But then you need to also prove **why** the left side is not true in general. Remember, a statement $\forall x: P(x)$ can only ever be disproven by showing that the statement $\exists x: \neg P(x)$ is true.
Comment: @45465 I know. But you have to do that, otherwise the proof is incomplete. It's **best** to take a **particular** $a$ and $b$ just to hammer home the point.
Answer: Symmetry works like this: if $(a,b) \in \mathcal R$, then we always have $(b,a) \in \mathcal R$; is this always true in this case?
For a particular example, consider $(1,2)$, which is in $\mathcal R$ as $1 \le 2$. Then if $\mathcal R$ is symmetric, $(2,1) \in \mathcal R$, but does it meet the condition to be in $\mathcal R$?
Comment: Does $a < b$ ever imply $b = a$? Does $a=b$ ever imply $b < a$? This isn't something you should be handling by cases because all you do is confuse yourself: stick to the $\le$ relation and it'll be a lot easier.


Button to update SQL datagridview data incorrectly updates rows

Question: I am trying to update select rows of the datagrid/sql table with textbox values entered in by the user. The can be updated with the code below but the value entered into the first textbox, textBox1, is entered into every row/column. Imgur album for datagridview post update :
 private void button2_Click(object sender, EventArgs e)
    {
        SqlConnection connectiont = new SqlConnection("Data Source=DESKTOP-P3JSE1C;Initial Catalog=logins;Integrated Security=True");
            {
                connectiont.Open();
                SqlCommand update = new SqlCommand("UPDATE dbo.logins SET site = @site, username = @username, pword = @pword, email = @email", connectiont);
                    update.Parameters.AddWithValue("@site", textBox1.Text);
                    update.Parameters.AddWithValue("@username", textBox1.Text);
                    update.Parameters.AddWithValue("@pword", textBox1.Text);
                    update.Parameters.AddWithValue("@email", textBox1.Text);
                    update.ExecuteNonQuery();

  }

            clear();//method to clear textboxes on the form w/ datagridview

    }

Comment: You do not have a **WHERE** clause. Are you planning to update the whole table? - I hope not.
Comment: Also to add I hope this is just a sample when you used 'textBox1.Text' for everything cause unless you add an ID column or whatever then even with WHERE clause you'll still update everything with the value of 'textBox1.Text'
Comment: Possible duplicate of [UPDATE from SELECT using SQL Server](http://stackoverflow.com/questions/2334712/update-from-select-using-sql-server)
Answer: To update only particular rows, you have to specify some conditions to identify the row in the table(primary key will be the best option here). You can use WHERE clause to specify those conditions. Let me assume that you want to update user name password and other details for a particular site, so the condition here will be the value in the site column. in this case the query will be modified like the following:
SqlCommand update = new SqlCommand("UPDATE dbo.logins SET username = @username, pword = @pword, email = @email WHERE site = @site", connectiont);

update.Parameters.AddWithValue("@username", textBox1.Text);
update.Parameters.AddWithValue("@pword", textBox1.Text);
update.Parameters.AddWithValue("@email", textBox1.Text);
update.Parameters.AddWithValue("@site", textBox1.Text);

update.ExecuteNonQuery();

Now the code will update details for those rows in which the site coulms has the specified value. Keep in mind, saving password as plain text will not be a secured option, use proper encryption to make them secure.


How to import numpy to python IDLE 2.7 on windows?

Question: I have tried the following code on the python IDLE:

import pip
  pip.main(["install","numpy"])

and the output I got is :
Collecting numpy
  Could not fetch URL https://pypi.python.org/simple/numpy/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661) - skipping
[31m  Could not find a version that satisfies the requirement numpy (from versions: )[0m
[31mNo matching distribution found for numpy[0m
I also have tried to use the "pip install numpy" but still not leading to any result.
Comment: What does this have to do with Anaconda?
Answer: Take a look at the following post the user is having the same issues as you do:
Can't import Numpy in Python
And take a look over here:
pip issue installing almost any library
Answer: Try Downloading it Here it's suggested in Scientific Python Install Page


Convert selected files in directory into another format

Question: For all the files in the input directory ending with "hic", I want to convert them to cool format. A single file can be converted using:
hic2cool_convert(<infile>, <outfile>)

But I'm not sure how to write a for loop to convert all the relevant files.
indir = "./others/"
outdir = "output/"

for file in os.listdir(indir + "*hic"):
   with open(os.path.join(indir + "*hic", file), "r") as f: # open in readonly mode
      hic2cool_convert(f, outdir + "f")

Traceback:
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Input In [11], in <cell line: 1>()
----> 1 for file in os.listdir(indir + "*hic"):
      2    with open(os.path.join(indir + "*hic", file), "r") as f: # open in readonly mode
      3       hic2cool_convert(f, outdir + "f")

FileNotFoundError: [Errno 2] No such file or directory: './others/*hic'

Answer: I don't think os has implemented shell wildcards like '*hic'. I recommend using Path, which is a lot easier to use than the os functions and also implements wildcard-capable glob():
from pathlib import Path

for path in Path("others").glob("*hic"):
    with open(path) as f:
        pass # whatever you wanted to do

Comment: I tried `for path in Path(indir).glob("*hic"):
    with open(path) as f:
        hic2cool_convert(f, outdir + "f")` but it raised `TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper`
Comment: Pass in `path` instead, then. (Are you not familiar with how to deal with exceptions? Plenty of resources online like programming tutorials to teach you...)
Comment: I think the issue is with the ``. I'm trying to convert and store all the files in the `outdir`, such that `abc.hic` -> `abc.cool` or `def.hic` -> `def.cool`.
Comment: I'm using this software https://github.com/4dn-dcic/hic2cool
Answer: Base in your error the folder is not found / been created. You should check first the file path using python "exists" function.
import os.path

path = indir + "*hic"

if os.path.exists(indir + "*hic"):
  ... do stuff
else:
  os.mkdir(path)
  ... do stuff

Comment: The directory does exist
Comment: what file format you need ?
Comment: I want to convert `.hic` format to `.cool` format.
Comment: I'm using this software https://github.com/4dn-dcic/hic2cool
Comment: can you send the latest error given because I'm still confuse with the file not found. i want to see the output of conversion. because the documentation said it was

hic2cool convert
Comment: `---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Input In [24], in ()
----> 1 for file in os.listdir(indir + "*hic"):
      2    with open(os.path.join(indir + "*hic", file), "r") as f: # open in readonly mode
      3       hic2cool_convert(f, outdir + "f")

FileNotFoundError: [Errno 2] No such file or directory: './others/*hic'`
Comment: can you try basic conversion first without looping ? try basic like this if it works

hic2cool_convert('my_hic.hic', 'my_cool.cool', 0)


Possible to select...for update, do e-commerce transaction, and then call a MySQL stored procedure in PHP?

Question: I am currently building a PHP e-commerce website for my client. Its been going smoothly but I've hit a roadblock and was wondering if any MySQL/PHP experts can help me. Basically, the e-commerce site sells a product only once (meaning they only have one quantity in stock for each item), which means that once a customer checks out with that item it cannot be bought anymore.
So on checkout, I have to check to see if the product is still in stock. Assuming this will be a site with heavy traffic, there could be instances where two or more customers would try to checkout at the same time, thus both would be able to buy the product. So to prevent that, my plan is as follows:

Select...FOR UPDATE on the product, to lock the table row.
Do e-commerce transaction (Paypal, authorize.net, etc.)
If e-commerce transaction is successful, call a MySQL stored procedure (which also has a SQL transaction) to store order information, etc. OR ROLLBACK if failed

Is it possible to realize this plan? To perform the SELECT...FOR UPDATE, I would have to start a SQL transaction, but then I am also starting another one in Step 3 within the MySQL stored procedure. I am not sure what would happen. Also, would this plan lead to a deadlock scenario?
Sorry for the long question, but any help is appreciated!
Comment: Instead of a `select for update` I think an available column, as a `tinyint(1)`, which flags the item might be a better choice. If you use a `select for update`, it is not likely a deadlock would happen, but it is likely customer #2 who clicks the purchase button would be waiting for a long time (while the lock is held by customer #1), only to be told "sorry, we're out of stock."
Comment: I thought about the available column, but suppose two customers click on "Buy" at the same time, wouldn't the column return "Available" since both requests are read before its updated to "unavailable"?
Comment: Sorry if I was not clear, I should have said to use `select for update` with updating the available column. This way you will only lock while checking for availability, instead of locking for the whole process. Another option would be to, after the first check on the available column, when going to update, do something like `update tbl set available = 0 where id = 1 and available = 1`. If two people run the query at the same time only 1 should succeed. You could then check how many rows were affected by the update. If 0 rows affected, you got bumped.
Comment: Hey Nate, could you clarify what you mean by using select for update with updating the available column? If I do that first, wouldn't that give me the same problem in the first place since I have to make two transactions? And if I go with the second option, if the payment fails, I would have to do another update to set available back to 1...doesn't seem very efficient =/
Answer: I'd suggest your stored procedure ought not to have transaction control inside it. That seems to be the cause of your difficulty.
If other callers require the stored procedure like that, consider factoring out the 'works' to a new stored procedure.


How do I solve this mushroom-related arithmetic sequence problem?

Question:
I interpreted this as the side of the following arithmetic sequence starting at length 1 and increasing by $2$ every day.

$100 = 1 +(n-1)\cdot2$
$n = 99/2 +1$
$n = 50.5$

I then interpreted this as the field being full by the $51$st day from Monday. The question asks for the number of days until the field is covered including Wednesday. Therefore, I subtracted $2$ from $51$ to get $49$ days as my answer. Yet this obviously isn't an option, and the actual answer is $48$. Have I just interpreted the wording incorrectly, or is there a more fundamental mistake?
Comment: $48$ is the correct answer.
Comment: @HVxvejjw why not 49?
Comment: On the first day there are $2^2=4$ mushrooms and the area covered by them is $1  m^2$ . On the second day there are $4^2=16$ mushrooms and the area covered by them is $9  m^2$. On the third day there are $6^2=36$ mushroom and the area covered by them is $25  m^2$ . So it will be on the $50th$ day my land will be fully covered by mushrooms. However note that we have started counting from the third day and not the first or second day. So the correct answer is$48$.
Answer: The First Term of the A.P should be taken as $4$ and not $1$ as $1,4,6...$ doesn't have common difference.
$$100 = 4 + (n-1)2$$
$$48 = n-1$$
$$n = 49$$
Hence the field would take $49+1 = 50$ days to be covered , but since Two days have already passed , required number of days is 48.
Answer: Count the number of squares formed by the mushrooms. Then we have the sequence $$1, 9,25,\dots,$$ or in other words, the squares of the odd integers, namely $(2n-1)^2.$ This also gives the area covered by the mushrooms. Since the field measures $100×100,$ it would have been covered when we have $101×101$ squares formed by the mushrooms.
This occurs on the $k$th day, so that $2k-1=101,$ or when $$k=51.$$ Indeed, it is clear from this why the answer cannot be an even number.


How to calculate days difference between two NSDate objects in different time zones?

Question: I have two NSDate which are initiated from UTC dates.
Lets call them (A & B)
I know that the A represents a day in China and B represents a day in USA. (I know the time zones.) How can I calculate the difference in days between the two...?
I have been using the following method which is obviously incorrect.
class func daysDifferenceIn(firstDate: NSDate, firstTimeZone: String, secondDate: NSDate, secondTimeZone: String) -> Int {
    objc_sync_enter(self)

    let firstDateComponents = NSCalendar.CommonCalendar.componentsInTimeZone(NSTimeZone(name: firstTimeZone)!, fromDate: firstDate)
    let secondDateComponents = NSCalendar.CommonCalendar.componentsInTimeZone(NSTimeZone(name: secondTimeZone)!, fromDate: secondDate)
    NSCalendar.CommonCalendar.timeZone = NSTimeZone(name: firstTimeZone)!
    let firstCalDate = NSCalendar.CommonCalendar.dateFromComponents(firstDateComponents)
    NSCalendar.CommonCalendar.timeZone = NSTimeZone(name: secondTimeZone)!
    let secondCalDate = NSCalendar.CommonCalendar.dateFromComponents(secondDateComponents)
    objc_sync_exit(self)

    return firstCalDate!.numberOfDaysUntilDateTime(secondCalDate!)
}

func numberOfDaysUntilDateTime(toDateTime: NSDate, inTimeZone timeZone: NSTimeZone? = nil) -> Int {
    let calendar = NSCalendar.CommonCalendar
    if let timeZone = timeZone {
        calendar.timeZone = timeZone
    }

    var fromDate: NSDate?, toDate: NSDate?

    calendar.rangeOfUnit(.Day, startDate: &fromDate, interval: nil, forDate: self)
    calendar.rangeOfUnit(.Day, startDate: &toDate, interval: nil, forDate: toDateTime)

    let difference = calendar.components(.Day, fromDate: fromDate!, toDate: toDate!, options: [])

    return difference.day
}

I can manually subtract day components from firstDateComponents and secondDateComponents which I don't want to do as I have to look for edge cases of 31 and 28 and so on.
Any help is appreciated. Thanks.
UPDATE
First date is 2017-02-10 16:15:00 +0000
Second date is  2017-02-11 03:20:00 +0000 Both are UTC.
firstTimeZone   String  "Asia/Shanghai"
secondTimeZone  String  "America/Los_Angeles"
So the day difference is -1 Day. Basically I am implementing flight status and you can see the following link as the flight lands 1 day prior to take day. As it flies from West to East.
https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=ua+890
Also a description of Date components.
Printing description of firstDateComponents:
<NSDateComponents: 0x600000142310>
    Calendar: <CFCalendar 0x60000088b6d0 [0x10c5d3df0]>{identifier = 'gregorian'}
    TimeZone: Asia/Shanghai (GMT+8) offset 28800
    Era: 1
    Calendar Year: 2017
    Month: 2
    Leap month: no
    Day: 11
    Hour: 0
    Minute: 15
    Second: 0
    Nanosecond: 0
    Quarter: 0
    Year for Week of Year: 2017
    Week of Year: 6
    Week of Month: 2
    Weekday: 7
    Weekday Ordinal: 2
Printing description of secondDateComponents:
<NSDateComponents: 0x60000014b8f0>
    Calendar: <CFCalendar 0x60000049b620 [0x10c5d3df0]>{identifier = 'gregorian'}
    TimeZone: America/Los_Angeles (PST) offset -28800
    Era: 1
    Calendar Year: 2017
    Month: 2
    Leap month: no
    Day: 10
    Hour: 19
    Minute: 20
    Second: 0
    Nanosecond: 0
    Quarter: 0
    Year for Week of Year: 2017
    Week of Year: 6
    Week of Month: 2
    Weekday: 6
    Weekday Ordinal: 2

Comment: Related: [NSDate for the same local time as another NSDate in different time zones](http://stackoverflow.com/q/38282732)
Comment: What result would you expect if the two dates are on the same day in China but on different days in the US?
Comment: @MartinR You can see my update to the question.
Comment: @JoshCaswell: Indeed. Having read the question now multiple times, that seems be be what really wanted here.
Answer: This is an odd case. You're looking for the difference in calendar dates between two Dates when those dates are evaluated in a specific time zone.
I did some playing, and came up with code that works for dates that fall in the same year:
let date = Date()

guard let nycTimeZone = TimeZone(abbreviation: "EST"),
  let nzTimeZone = TimeZone(abbreviation: "NZDT") else {
    fatalError()
}
var nycCalendar = Calendar(identifier: .gregorian)
nycCalendar.timeZone = nycTimeZone
var nzCalendar = Calendar(identifier: .gregorian)
nzCalendar.timeZone = nzTimeZone

let now = Date()

let nycDayOfYear = nycCalendar.ordinality(of: .day, in: .year, for: now)

var nzDayOfYear = nzCalendar.ordinality(of: .day, in: .year, for: now)

I'm using New York and Aukland, NZ as my time zones because as of the time of this writing, those zones are on different dates.
As of now (~12:00 PM on Feb 11, 2017 in US Eastern Standard Time (UTC - 5) the code above gives
nycDayOfYear = 42

and
nzDayOfYear = 43

It would take some work to make that calculation work across year boundaries.
Curiously, the following code:
var nzDayOfEra = nzCalendar.ordinality(of: .day, in: .era, for: now)
let nycDayOfEra = nycCalendar.ordinality(of: .day, in: .era, for: now)

Gives the same value for both NZ and NYC. I'm not sure why.
EDIT:
Ok, I did some experimenting and got code that works. What I do is to convert both dates to month/day/year date components using a calendar set to the local time zone for each time. Then I use a method dateComponents(_:from:to:) to calculate the difference between those 2 DateComponents, in days:
import UIKit

let date = Date()

guard let nycTimeZone = TimeZone(abbreviation: "EST"),
  let nzTimeZone = TimeZone(abbreviation: "NZDT") else {
    fatalError()
}
var nycCalendar = Calendar(identifier: .gregorian)
nycCalendar.timeZone = nycTimeZone
var nzCalendar = Calendar(identifier: .gregorian)
nzCalendar.timeZone = nzTimeZone

let now = Date()

let nycDateComponents = nycCalendar.dateComponents([.month, .day, .year], from: now)
let nzDateComponents = nzCalendar.dateComponents([.month, .day, .year], from: now)

let difference = Calendar.current.dateComponents([.day],
  from: nycDateComponents,
    to: nzDateComponents)

let daysDifference = difference.days

As of this writing that gives a daysDifference of 1. Since we're using the  dateComponents(_:from:to:) function, it takes care of the math to calculate the number of days difference between the 2 month/day/year DateComponents.
Comment: It is helpful, but I am looking for more full proof answer. Thanks anyway.
Comment: See the edit to my answer. I added code that gives you the answer you need.
Comment: I also posted an answer and someone down voted without any comments. Your solution is also good. Do you see anything wrong with my answer in which I took hints from your code... ?
Comment: See my comment on your answer. I got wrong results trying to use era-based calculations.
Comment: What you are actually doing is taking two dates and getting the difference between them in respect to the local time zone. The first thing you did was to remove the time zone information... This is exactly the result you would get if you had two datetime strings (including the timezone) and parsed them to your local time zone and then got the number of days between them.
Comment: @sulthan, Why would calculating the number of days in the .era ordinal strip out the time zone information? I Would expect it to give answers that reflect the difference in time zones. If you use an `in:` value of `.year`, you get the desired result, at least when both dates fall in the same year in their local time zone. See the edit to my answer that provides a working solution to the problem.
Answer: A NSDate represents a moment in time. It has no time zone. Only string representations of dates have time zone information.
If you have the dates, just take the number of days between them. Don't worry about time zones.
Usually:
let difference = calendar.components(.Day, fromDate: self, toDate: toDate!, options: [])
return difference.day

should be enough.
Comment: Minor nitpicking: *"just take the number of days ... Don't worry about time zones"* *may* be misleading. The difference in days makes only sense with respect to a calendar and a time zone. That can of course be the default calendar and the local time zone.
Comment: @Sulthan you can look at my Update to the question.
Comment: "Only string representations of dates have time zone information." No, that's not exactly true. Consider converting an `NSDate` to `DateComponents`. The year/month/day/hour/minute values you get will be different depending on time zone. The expression of a Date object in a particular calendar depends on the time zone, regardless of wether that representation is numeric or string-based.
Comment: The OP is asking about an unusual problem: Figuring out the difference in calendar dates for 2 different locations on earth that are in different time zones. For example, right now it's Feb 13th in Aukland, NZ, but Feb 12th in New York City. The OP wants a result of 1 day difference in that case. He **WANTS** to worry about time zones.
Comment: @DuncanC I don't think that's an unusual problem. I think that's an impossible problem. While we could devise a solution, that solution would have too many edge cases.
Comment: @Sulthan, see the edit to my answer. I found fairly simple working code that lets the Calendar object deal with all the edge cases.
Answer: Have you tried using let interval = laterDate.timeIntervalSinceDate(earlierDate)? This will return the difference between the two dates in seconds.


Is it plausible to get a Cronbach's alpha of .85 with only two Likert-type items?

Question: I was reading an article that reported a Cronbach's alpha of .85 for a two-item scale. The scale was measuring self-perceived competence. Each item was on a 7-point Likert-type scale.
Intuitively, that seemed like quite a high Cronbach's alpha for a scale with only two items.

Is it plausible to get an alpha that high on a two-item psychological scale based on Likert-type items?
How through equations or simulations can I better understand what degree of consistency would be required between the items to achieve a reliability coefficient of .85 with only two 7-point items?
Answer: I'm a bit confused by your question. Maybe I miss something in it? Alpha of .85 isn't too high. They say test designed for individual diagnostics / decision making (such as clinical psychological test on result of which important decision about patient are made) alpha should be .90 or higher. The data below shows alpha .855 (and standardized alpha, that is, for standardazed variables, .858). The data look quite realistic, isn't it?
<code>1   1
2   1
2   3
3   3
3   3
4   2
4   3
5   7
5   4
5   7
5   6
5   4
5   4
6   6
6   6
6   5
6   3
6   5
6   5
7   6
</code>
As you know, alpha reflects the magnitude of mean inter-item covariance and variance, and standardized alpha - the magnitude of mean inter-item correlation. When there are only 2 items designed to correlate, it is plausible to expect correlation between them to be higher than the mean correlation between, say, 20 items designed to correlate. For the data above, r is .752 which gives st. alpha $\frac{2*.752}{1+(2-1)*.752}=.858$.
Comment: I agree that good scales should have alphas higher than .8 or .9. I was just surprised that a two-item scale would have such a high alpha. I knew that it was possible to get such a high alpha, but I was wondering what was the more plausible scenario: (a) the authors made an error, perhaps, dare I say, inspired by the need to meet the ".80 threshold of publishability"; or (b) the two items actually were sufficiently highly correlated to result in such an alpha. I think the data you show looks plausible given two very similar items, and therefore I'm inclined to trust the reported results.
Comment: Yeah. We see that 2-item construct can easily turn reliable. What about validity of such constructs? 2 items is usually regarded insufficient for any reputable scale.


How to limit the number of privatemsg?

Question: To avoid bulk private messaging by spammers in busy Drupal 6 community site, I'd like to limit the messages an authenticated user can send out in certain time span.
I saw Private Message Limits but it is still in dev since 2011 hence it may  not be ready for production. So I'm wondering what is the best way to apply the limit? Thanks
Answer: Privatemsg 6.x-2.x has a Limits submodule built in, either use that version or use try out the separate project for 6.x-1.x, you will have to find out yourself it is working well enough for you.

How to limit the number of privatemsg?


Como aumentar a largura do border-bottom?

Question:
Como aumentar o border-bottom até onde a seta aponta :

Código:

.container__transacoes > h3{
border-bottom: 1px solid #bbb; /*Ver como aumentar as bordas*/
padding-bottom: 10px;
margin: 30px 0px 10px;
margin-right: 190px;
}
.transacoes{
list-style-type: none;
padding: 0;
margin: 40px;
}
.transacoes li {
background-color: #fff;
box-shadow: var(--box-shadow);
color: #333;
display: flex;
justify-content: space-between;
position: relative;
padding: 10px;
margin: 10px 0;
}
.transacoes li.plus {
border-right: 5px solid #0EC206;
}

.transacoes li.minus {
border-right: 5px solid red;
}

Transações

Adicionar Transações

Comment: Não é só colocar `border-bottom: 10px solid #bbb; `? ou `border-bottom-width: 15px`? Você define o tamanho o em pixel, como desejar...
Comment: Eu meio que perguntei errado , não era para aumentar a largura , e sim o tamanho dele ate onde a seta está apontando , você pode me ajudar ?
Comment: Ok. Reabri a pergunta. Mas sugiro que edite o título, pra ficar mais descritivo.
Comment: Eu dei uma ajuda na edição. O que tem no `.container_transacoes`? Acho que pode ser a resposta pra descobrir porque não vai até o final. Sugiro que cole o trecho do CSS dessa div.
Comment: Alterei aqui ,,,
Answer: Cara não está indo até o final pq vc colocou um margin-right de 190px no H3

Da forma como está o H3 ocupa a linha inteira, menos a largura desse margin ai, basta remove-lo para ficar 100%

.container__transacoes > h3{
border-bottom: 1px solid #bbb; /*Ver como aumentar as bordas*/
padding-bottom: 10px;
margin: 30px 0px 10px;
/* margin-right: 190px; */
}
.transacoes{
list-style-type: none;
padding: 0;
margin: 40px;
}
.transacoes li {
background-color: #fff;
box-shadow: var(--box-shadow);
color: #333;
display: flex;
justify-content: space-between;
position: relative;
padding: 10px;
margin: 10px 0;
}
.transacoes li.plus {
border-right: 5px solid #0EC206;
}

.transacoes li.minus {
border-right: 5px solid red;
}

Transações

Adicionar Transações

Comment: Muito Obrigado Hugo :)   , Coloquei o Width:100% ae ficou tudo certo , fico triste em saber que sua resposta foi boa e ainda deram deslike nela , deveria ter no stackOverFlow um mecanismo que pode-se denunciar pessoas que deram deslike sem motivo nenhum
Comment: @ValdenirsonPEREIRA não tem problema, o voto negativo nada muda, fico feliz em ter ajudado, vc aceitou a resposta, e eu sei que ajudei com algo correto. Na verdade, eu lamento pelo cara ter votado negativo e achar que vai mudar alguma coisa haha. Eu vou sair daqui com 23pt e vc com o problema resolvido, e o que o Downvote representa? Nada :D, seria melhor ele ter tentado alguma resposta melhor ou feito um cometário construtivo, é um voto jogado no lixo...


How to tell if something happened in a data set which monitors a value over time

Question: I have a data set where a series of measurements are being taken each week. In general the data set shows a +/- 1mm change each week with a mean measurement staying at about 0mm. In plotting the data this week it appears that some noticeable movement has occurred at two points and looking back at the data set, it is also possible that movement occurred last week as well.
What is the best way of looking at this data set to see how likely it is that the movements that have been seen are real movements rather than just some effect caused by the natural tolerance in the readings.
Edit
Some more information on the data set. Measurements have been taken at 39 locations which should behave in a similar way although only some of the points may show signs of movement. At each point the readings have now been taken 10 times on a bi-weekly basis and up until the most recent set of readings the measurements were between -1mm and 1mm. The measurements can only be taken with mm accuracy so we only receive results to the nearest mm. The results for one of the points showing a movement is 0mm, 1mm, 0mm, -1mm, -1mm, 0mm, -1mm, -1mm, 1mm, 3mm. We are not looking for statistically significant information, just an indicator of what might have occurred. The reason is that if a measurement reaches 5mm in a subsequent week we have a problem and we'd like to be forewarned that this might occur.
Comment: Look at http://stats.stackexchange.com/questions/173/time-series-for-count-data-with-counts-20/ . It's not a duplicate, but the problem is similar at a first sight.
Answer: I think you need look at statistical control charts. The most common of which are cusum and Shewhart charts.
Basically, data arrives sequentially and is tested against a number of rules. For example,

Is the data far away from the cumulative mean - say 3 standard deviations
Has the data been increasing for the last few points.
Does the data alternate between positive and negative values.

In R you can use the qcc package.
For example,
<code>#Taken from the documentation
library(qcc)
data(orangejuice)
attach(orangejuice)
plot(qcc(D[trial], sizes=size[trial], type="p"))
</code>
Gives the following plot, with possible problem points highlighted in red.
control chart http://img805.imageshack.us/img805/5858/tmp.jpg
Answer: What kind of movement are we talking about?
You could of course fit a distribution over your data and see whether the new weeks fit in this distribution or are in the tail of it (which means it is likely something significant, real that you are observing)
However, more information from your side would be helpful. Maybe you could provide a part of the dataset?
Comment: We have done this in two different ways and it has proved very useful with the large movements this week lcearly being outside the histogram of typical results.


Eulerian Paths in a Complete Graph $K_5$

Question: As the title suggests, I'm simply looking for a method to compute the number of Eulerian Paths in the complete graph $K_5$, where all paths start from the same node. Since there are 5 nodes, all Eulerian paths must be Eulerian circuits as well.
Thanks.
Comment: what have you tried so far?
Comment: I'm not very knowledgeable about graph theory, but I wrote this problem and a friend of mine believes he has solved it with some super complex and obscure methods. I posted this because I wanted to see if there are any methods relatively easy [for me] to understand and also to confirm my friend's answer. Thanks!
Comment: $K_5$ has $20$ times as many Eulerian trails (or "paths" in your quaint terminology) as Eulerian circuits. That's because a circuit has no starting point, so to make a circuit into a "path" you have to specify which edge is to be traversed first, and in which direction. Let me put it this way: if the graph were $C_5$ instead of $K_5$, is the answer you're looking for $1$ or $5$?
Comment: I'd attack the problem in two stages. First, enumerate the orientations of the graph (assigning a direction to each edge) such that each node has the same number of edges entering and leaving; then find the number of Eulerian circuits in each of the resulting digraphs. I don't know any "formula" for stage one. For $K_5$ because it's so small the first stage is easily done by hand: the number of such orientations is $\binom42\cdot2\cdot2=24$, and you can easily see that they are all isomorphic, so there is only one digraph to worry about in stage two.
Comment: There is a famous **determinant** formula for the number of Eulerian circuits in a digraph. I don't exactly remember it, I could look it up in my notes from the graph theory class I had years ago. Does that sound like the method your friend used?
Comment: Ah so sorry, thanks for bringing this to my attention. That lack of detail is my bad. I'll edit the original question, but for my question I'm asking for the number of paths (or trails) all from the same starting point. So, as per your example, if the graph were C₅ then the answer I'd be looking for would actually be 2. The actual problem I wrote is a word problem with bridges, but I hope you get the idea. If I've poorly phrased my question in any other way please let me know. Thanks!
Comment: If you just want to check your friend's answer you could just work out the correct answer from [this site](http://oeis.org/search?q=eulerian+circuits+complete+graph&language=english&go=Search). They give $264$ Eulerian circuits for $K_5$. But each Eulerian  circuit goes through your designated starting point twice, so I guess that means you get $528$ for your problem. Is that what your friend got?
Comment: Hahaha, I didn't even think to check OEIS... my friend in fact got $264$ as his answer, so I guess I can tell him he's wrong :) I don't  believe he used the determinant formula you mentioned. He told me something about using a modified gamma function.... I was just searching for an easier way to understand the solution.
Comment: Or actually, never mind that, I think he is right. OEIS says 264 is the number of directed Eulerian circuits, so that accounts for the two directions.
Answer: Without using fancy tools like the BEST theorem, we can figure out the problem using inclusion-exclusion.
At each vertex of $K_5$, we have $4$ edges. A circuit is going to enter the vertex, leave, enter, and leave again, dividing up the edges into two pairs. There are $\frac12 \binom42 = 3$ ways to pair up the edges, so there are $3^5 = 243$ ways to make this decision at every vertex.
Not all of these will correspond to an Eulerian circuit, because not all of them connect up the way we'd like. We could also see:

Two $5$-cycles (first diagram below). There are $\frac{5!}{2 \cdot 5} = 12$ ways to choose a $5$-cycle, and they'll always go together, so we should subtract $6$.
A $4$-cycle and some other stuff (second diagram below). There are $\binom{5}{4} \cdot 3 = 15$ ways to choose a $4$-cycle, and $3$ ways to decide what happens at the vertex it doesn't visit, so we should subtract $15\cdot3 = 45$.
A $3$-cycle and some other stuff (third diagram below). There are $\binom 53 = 10$ ways to choose a $3$-cycle, and $3^2$ ways to decide what happens at the two vertices it doesn't visit, so we should subtract $10 \cdot 3^2 = 90$.

But $243 - 6 - 45 - 90 = 102$ is still wrong, because we've double-counted one case. It's possible to have $3$ components: a $4$-cycle and two $3$-cycles (last diagram above). If we've chosen the $4$-cycle, there is one way to pair up the edges at the unvisited vertex to get the two $3$-cycles as well, so there's $15$ such configurations. We've subtracted them three times instead of once, so we should add them back in twice, getting $102 + 30 = 132$.
Multiplying by the two possible orientations, we get $264$ oriented Eulerian circuits. If we know which node is the first, but not which edge is the first, we can also start with two possible edges out of that node, getting $528$ oriented Eulerian paths starting at that node ($2640$ oriented Eulerian paths total).
Comment: @MishaLavrov I think it is practical for $K_5$ because all Eulerian orientations of $K_5$ are isomorphic.
Comment: BEST is useless anyway, since we are talking about undirected graphs.
Comment: It was suggested in the comments on the question that we can try applying it to each possible orientation of $K_5$. Not sure how practical that is.
Comment: @bof Oh, good point. I was just thinking of in general, where it has to be hard in order for the problem to be #P-complete.
Comment: I recall many years ago calculating the number of Eulerian circuits in $K_7$ (poresented as a puzzle about arranging a set of dominos) using three instances of the BEST theorem.
Comment: @MishaLavrov Thank you! Exactly the type of explanation/solution I was looking for. Very smart way of going about it.


Hypothesis testing for difference in medians vs. median difference

Question: I found this post saying that one should test for the median difference instead of the difference in medians, in particular if the data is skewed: http://onbiostatistics.blogspot.com/2015/12/median-of-differences-versus-difference.html The authors says "median of differences is the correct number to be used and is the number that corresponding to the signed rank test".
I did not find good explanations for this. My question: are there any reasons from a statistical perspective why the median difference should be preferred over the difference in medians?
To give some more background: The differences are paired. Moreover, the paired differences are highly skewed to the right (in my real data set), which is why I want to use a bootstrap hypothesis test.

Example
Suppose I have a two samples x1 and x2 as below. The samples are paired, for instance the id could specify the person and x1 could be a measurement before intervention and x2 after the intervention (for the same person).
id    x1      x2    difference
1   1.37    1.68    -0.31
2   2.18    2.99    -0.80
3   1.16    3.24    -2.07
4   3.60    3.08    0.52
5   2.33    2.19    0.13

The median difference would be: median(x1 - x2) = median(difference) = -0.31
The difference in medians would be: median(x1) - median(x2) = -0.80.
Comment: Among other points "difference in medians" ignores the pairings while "medians of differences" uses it.  So if the pairings are meaningful the latter may be preferable
Comment: I suspect that even that loses much of the pairing information
Comment: Concerning the last sentence before your example. Are you saying that you have differences arising from pairs and that those differences are right skewed? How many differences? What hypothesis do you want to test? (That the population median is 0? Or something else?) Finally, can you say why you want to use a re-sampling method rather than a nonparametric test such as Wilcoxon SR?
Comment: @BruceET. Yes, in my data set I have differences arising from pairs (as shown in the example) and these differences (corresponding to the `difference` column in the example) are right skewed. I have approx. 3500 such difference values. I want to test the H0: median(difference) = 0 against H1: median(difference) > 0 (or alternatively H0: median(x1) - median(x2) > 0 against H1: median(x1) - median(x2) > 0).
Comment: @BruceET. I have considered nonparametric re-sampling methods because, based on the observed 3500 differences, it does not seem that common assumptions (such as assumption of normality or for other tests assumption of symmetry) are fulfilled. In addition, I like re-sampling methods because of their flexibility in the test statistic (differences in medians or median difference can simply be defined as test statistic without issues). Please let me know if something in my answer is unclear or if you have other questions.
Comment: @BruceET. In addition, reading over the assumptions of the Wilcoxon signed-rank test (https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test), I noticed that in my data set the assumption "Each pair is chosen randomly and independently" is not fulfilled.
Comment: Well, if you can't reasonably assume your subjects are reasonably close to a random sample, then I don't see how _any_ test procedure can be valid.
Comment: In my case, I want to compare two reinforcement learning agents' performance (corresponding to `x1` and `x2`) on the exact same episodes (corresponding to `id`). The episodes are based on a static data set (and hence the same for both agents explaining why my data is `paired`). The episodes correspond to subsequent dates, e.g. `id=1` for `01.01.2015`, `id=2` for `02.01.2015` etc. This is why I'd say that the pairs are not chosen randomly (since they correspond to `subsequent` dates). Do you think that this disqualifies any test procedure?
Comment: If it's safe to assume the 3500 _subjects_ (each subjected to the same 2 treatments) are random, that's sufficient. With that many pairs you should find an effect if there is one. With that many subjects, paired t (= t on one sample of differences) should be OK even with skewness, or Wilcoxon as discussed if skewness very extreme. Unless you were explicitly ordered to do a re-sampling procedure (say, as part of coursework), nothing you have said so far about your design convinces me re-sampling is necessary. // If extra relevant info, please edit it into your Q for all to see and comment on.
Comment: @Henry, I can also keep the pairings with "difference in medians" when doing a bootstrap. I can re-sample the `id` and then compute `median(x1) - median(x2)` where `x1` and `x2` correspond to the `id`, i.e. `median(x1)` and `median(x2)` are computed based on the exact same `id`s.
Answer: Data. There are some minor discrepancies (maybe from rounding) in your data table.
The table below is what I get from inputting your x1 and x2. These are
the values I will use:
       x1   x2     d
[1,] 1.37 1.68 -0.31
[2,] 2.18 2.99 -0.81
[3,] 1.16 3.24 -2.08
[4,] 3.60 3.08  0.52
[5,] 2.33 2.19  0.14

Sample means and medians behave differently. The reason there needs to be a discussion here is that sample means and
sample medians behave in substantially different ways.
Means: If $D_i = X_{1i} - X_{2i},$ then $\bar D = \bar X_1 - \bar X_2,$ where bars designate sample means.
Medians: However, as for your data, one may have $\tilde D \ne \tilde X_1 - \tilde X_2,$ where tildes designate sample medians.
Paired Wilcoxon test. The point made in your link is that the paired Wilcoxon test is a essentially a one-sample signed-rank test on differences.
Thus, you get the same results from the following two tests involving
 medians. (I'm using R.)
One-sample Wilcoxon test on differences.
wilcox.test(d)

    Wilcoxon signed rank test

data:  d
V = 4, p-value = 0.4375
alternative hypothesis: true location is not equal to 0

Paired Wilcoxon test.
wilcox.test(x1, x2, paired=T)  # computes differences first

        Wilcoxon signed rank test

data:  x1 and x2
V = 4, p-value = 0.4375
alternative hypothesis: true location shift is not equal to 0

Incorrect procedure:  If you forget the parameter 'paired=T' in the paired
test, then R does a Mann-Whitney-Wilcoxon (rank-sum) two-sample test.
The P-value is not enormously different, but it should be clear that the
test below is not the paired test.
wilcox.test(x1, x2)  # TWO-sample test, NOT PAIRED

        Wilcoxon rank sum test

data:  x1 and x2
W = 8, p-value = 0.4206
alternative hypothesis: true location shift is not equal to 0

Graphical presentation of paired data. For much the same reasons, if you want to show a boxplot for paired data,
you must make a single boxplot of differences (as at left), not two separate boxplots of for Before and After. (In showing boxplots, I am assuming that your actual data have more than five subjects. It is unusual to make boxplots of as few as five observations.)

Confusion results from making separate stripcharts (dotplots) of scores Before and After because the plot does not show which Before values are paired with which After values.

You might try connecting data points to show pairs.

Note: For only five subjects, as in the data you show in your Question, the nonparametric Wilcoxon signed rank test would not show a significant result unless all five differences have the same sign.
Comment: Your answer greatly clarifies what the author (that I cited in my question) was referring to. If I was to use the nonparametric Wilcoxon signed rank test, all would be clear now. However, if I was to use a nonparametric bootstrap hypothesis test, it seems like both options are valid, right? (Difference in medians or median difference). Note that not only in case of the median difference but also in case of the difference of medians, I can account for pairs: in the difference of medians, I'd resample the `id` and then compute the difference of medians based on the corresponding `x1` and `x2.
Comment: If I were using a resampling procedure, I would resample differences.
Comment: What would be your motivation to do so?


Rails 4.0.3 - has_many through undefined method 'name' for nil:NilClass - only on production

Question: I have a branch model
class Branch < ActiveRecord::Base
    validates :name, presence: true

    has_many :company_branches
    has_many :companies, -> { uniq }, :through => :company_branches
end

and a company model
class Company < ActiveRecord::Base
    has_many :company_branches
    has_many :branches, -> { uniq }, :through => :company_branches
end

The company can have many branches through company_branches
class CompanyBranch < ActiveRecord::Base
    belongs_to :branch, touch: true
    belongs_to :company, touch: true
end

On my local machine everything works fine but when I try to save the form on my production Server I get: NoMethodError (undefined methodname' for nil:NilClass)`
The call in my controller is @company.update_attributes(company_params) - The controller receives the branch_ids as array, like branch_ids => [1, 2, 3]
Interesting part of the controller(It fails at @company.update_attributes(company_params)):
class Admin::CompaniesController < Admin::AdminController
    respond_to :html, :json
    load_and_authorize_resource

    def update
        @company = Company.find(params[:id])
        @company.update_attributes(company_params)
        ....
    end

    private
    def company_params
      params.require(:company).permit(:id, branch_ids: [])
    end
end

To clarify: I tried many things and currently only have one branch on my production server. Even with that one single branch I get the error when I try to save it.
Edit: I posted the full stacktrace here: http://pastebin.com/tw6hjkyF
Comment: @OliverM I added the stacktrace. I hope that helps.
Comment: I think that's the right hint. I just noticed I'm running 2.0.0 on my local machine and 2.2.0 on my production server and wanted to have a look if it has something to do with that.
Comment: Where is your app hosted? Have you run rake db:migrate?
Comment: The app is hosted on an own server. We deploy with capistrano so we have no migration problem. The app is running for serveral years now.
Comment: If it's failing at @company.update_attributes() etc with a nil class, won't that mean that your @company instance is nil?
Comment: I already checked that. The problem are the branches, not the company. As I wrote, everything works fine locally.
Comment: Stack trace might help
Comment: would you mind post a answer, I'm very interested to known the reason.
Comment: I will post the answer when I find out what happens. I will edit my post and add the stacktrace.
Comment: Have you just upgraded to ruby 2.2 from ruby < 2.2? There was an Active Record bug which was fixed for Rails 4.1/2. See the very top of your stack trace, has_cached_counter.
Comment: Ok I think that's probably it! Glad we could get to the bottom of it.
Answer: There is a bug with Active Record, you'll need to Upgrade Rails, or downgrade ruby from 2.2 to 2.1.8 or lower.
Comment: Thanks a lot! That was the reason.