Polar Transformation of Joint (Uniform and Normal) Probability Distribution

Question: I think I'm missing something basic here, so any help is appreciated!
Take $P_X(x) \sim \text{Uniform}(0, 1)$ and $P_Y(y) \sim \text{Normal}(0, \sigma^2)$. The joint probability distribution is
$$P_{XY}(x, y) = \frac{1}{\sqrt{2\pi\sigma^2}}e^{-y^2/(2\sigma^2)}$$
for $x \in [0, 1]$. We wish to transform this distribution to polar coordinates, $r = \sqrt{x^2 + y^2}$, $\theta = \text{arctan}(y/x)$. The determinant of the polar transformation is $|r|$, so my intuition is that the transformed distribution is
$$P_{R\Theta}(r, \theta) = \frac{r}{\sqrt{2\pi\sigma^2}}e^{-(r\sin\theta)^2/(2\sigma^2)}$$
for $0 < r < 1/\cos\theta$ and $\theta \in [-\pi/2, \pi/2]$. It is clear, however, that the conditional probability $P_{R | \Theta}(r | \theta)$ does not match the expression in the Cartesian form. Take, for example, $\theta = \pi/2$. We have $x = r\cos\theta = 0$ and $y = r\sin\theta = r$, so
$$P_{XY}(x = 0, y = r) = \frac{1}{\sqrt{2\pi\sigma^2}}e^{-r^2/(2\sigma^2)}$$
for $0 < r < 1/cos\theta$, which is the expected half-normal distribution. In the polar form, however, we get (ignoring the normalization)
$$P_{R|\Theta}(r | \theta = \pi/2) \propto \frac{r}{\sqrt{2\pi\sigma^2}}e^{-r^2/(2\sigma^2)}$$
for $0 < r < 1/cos\theta$, which is a Rayleigh distribution.
Where's my mistake? Thanks in advance!
Update
I worked through the normalization term:
$$P_\Theta(\theta) = \int_{0}^{1/\cos\theta}P_{R\Theta}(r,\theta)dr = \frac{\sigma^2}{(\sin\theta)^2\sqrt{2\pi\sigma^2}}\left(1 - e^{-(\tan\theta^2)/(2\sigma^2)}\right)$$
And thus the conditional probability is
$$P_{R|\Theta}(r | \theta) = \frac{P_{R\Theta}(r,\theta)}{P_{\Theta}(\theta)} = \frac{r(\sin\theta)^2}{\sigma^2}\frac{e^{-(r\sin\theta)^2/(2\sigma^2)}}{1 - e^{-(\tan\theta^2)/(2\sigma^2)}}$$
Something still isn't right!
Comment: You forgot the restriction of the support.  $(x,y)\in(0,1)\times\mathbb{R}$, not $(0,\infty)\times\mathbb{R}$.  So after transforming you don't get the entire $(r,\theta)\in(0,\infty)\times(-\frac\pi2,\frac\pi2)$.
Comment: Ah yes, good point. Thanks for pointing it out. How exactly do I fold that into this derivation? Other than incorrectly claiming $r > 0$ (instead of $0 < r < \cos\theta$, I'm not sure how that fact affects my flow of logic.
Comment: if $r$ is less than 1, then the integral is incorrect because it has $\frac{1}{cos(\theta)}$ as the upper limit. There may be other places also but I'll leave those to both of you since they are above my pay grade !!!!!
Answer: After a night's sleep and some retrospection, I understand why this conditional probability has the form that it does, and it is actually quite simple. This is just another example of Borel's paradox.
$$P_{XY|\Theta}(r\cos\theta, r\sin\theta | \theta = \pi/2) = \frac{1}{\sqrt{2\pi\sigma^2}}e^{-r^2/(2\sigma^2)}$$
describes the conditional probability along the $+y$ axis within a thin strip of $x$ and follows the expected half-normal distribution. On the other hand,
$$P_{R|\Theta}(r | \theta=\pi/2) = \frac{r}{\sigma^2}e^{-r^2/(2\sigma^2)}$$
describes the conditional probability along the $+y$ axis within a small wedge of $\theta$, which must grow proportionally to $r$.


means and errors for election polls

Question: I'm trying to assess how to compute the errors associated with a numbers of likely voter polls of the Warnock Georgia Senate race.
I have estimates of the margin of victory from 9 surveys of varying sample sizes. While these surveys likely have different approaches to their sample or weighting, I have no priors to weight some surveys higher than others except sample size. Also, to simplify things for my main question, you can assume there is no "undecided" category, so the results for the two candidate probabilities sum to 1. (This data is all from 538)
id estDemMargin (i.e., +2 means D= .51 & R =.49)     obs,
1    +2                                              713,
2    -1                                              550,
3    +1                                              500,
4    -1                                              500,
5    +4                                              857,
6    +4                                             1680,
7    +2                                             1011,
8    +3                                              578,
9    +9                                              500

Were the polls off or not?
What are the relevant statistics to make this assessment?
Is the estimated margin then +2.56 (mean of the reported margins) with an  s.e. of 3.05 (s.e. of the reported margins)  or s.e. = 0.96 (average of the individual survey s.e.'s). Or something else.
Both suggest the actual results (+2) is well within the CI, but there's obviously a much larger CI in the former case.
Again, I am inserted in the fundamental question about how to compute the s.e. for a series of estimates less about the other vagaries of these polls (e.g., I don't care about incorporating Silver's grading of polling firms here)
Answer: I couldn't be sure of your notation, and I didn't see a final result there. So I went to '538'
and got the data on the six polls currently listed for the Warnock race.
I show below how I would combine the six polls to get an overall
confidence interval.
For example, the first-listed poll of 857 likely voters showed
98% of them (840) choosing either Warnock or Loeffler, with 51% of
them (437) for Warnock. [That's 52.02% for Warnock among subjects declaring a preference.]
Similar computations for all six polls are summarized in R below:
LV = c(857,500,500,550,1342,713)         # 6 polls: all subjects
Ln = round(Lv*c(.98,.98,.91,.97,.97,1))  #  subj for W or L
Lw = round(Lv*c(.51,.49,.46,.48,.49,.5)) #  subjects for W
Fw = Lw/Ln                               #  fraction for W
round(Fw, 4)
[1] 0.5202 0.5000 0.5055 0.4944 0.5054 0.4993
n = sum(Ln);  w = sum(Lw)
w; n; w/n
[1] 2190        # Total for W
[1] 4334        # Total for W or L
[1] 0.5053069   # Overall fraction for W

Altogether, there were 2190 responses for Warnock out of 4334 responses for either
Warnock or Loeffler. Because we know of no reason to 'weight'
the polls other than sample size, this seems a reasonable way to combine
their findings. My method gives an overall $50.53\%$ of useful responses
favoring Warnock.
A Jeffries 95% confidence interval $(0.4904, 0.5202)$ for the fraction of likely voters
favoring Warnock is computed in R as follows:
qbeta(c(.025,.975), w+.5, (n-w)+.5)
[1] 0.4904225 0.5201842      # Jeffries Ci

Considered here as a frequentist confidence interval, this result is based on a Bayesian argument with the non-informative Bayesian prior $\mathsf{Beta}(0.5, 0.5).$ Taking into account
the binomial likelihood based on $n = 4334$ useful responses, the
,Bayesian posterior distribution is $\mathsf{Beta}(2190.5, 2144.5),$
quantiles $0.025$ and $0.975$ of which give the confidence interval.
[According to the Wikipedia page on binomial confidence intervals,
this Jeffries interval estimate has good coverage properties when
used as a frequentist confidence interval.]
Using the traditional (asymptotic) Wald 95% CI we get $(0.4904,0.5202).$ Specifically, this interval is of the
form $\hat p \pm 1.96\sqrt{\hat p(1-\hat p)/n},$ where $\hat p \approx 0.5053$ is the observed proportion in favor and $\sqrt{\hat p(1-\hat p)/n} \approx 0.0076$ is the (estimated) standard error.
On account of the relatively large sample sizes, it is not surprising
that the two interval estimates match.
p.hat = 0.5053069;  n = 4334
p.hat + qnorm(c(.025,.975))*sqrt( p.hat*(1-p.hat) /n)
[1] 0.4904219 0.5201919     # Wald CI

According to the New York Times the percentage of the final
vote for Warnock was 51.0%, so the point estimate from my
'combination' of polls is quite close to the final vote, and
the CIs cover the final vote percentage.
Answer: Thanks. My question was more theoretical than computational. So you're saying that the point estimate and error should be computed by pooling the "experiments," rather than considering the polls 9 experiments. (I guess they are independent "draws" so this would be reasonable.)

means and errors for election polls


Change Window in Cocoa Document-Based Application

Question: I have one window in a Cocoa-Document based application. I want to make this application have no titlebar. I know how to do this in a regular Cocoa app because there is a window called "window" in Cocoa-Document based apps I don't see any window declarations. So my question is how to I make a borderless window in a Cocoa Document_based app?
Thanks
Answer: Look in the document's nib file. In a document-based application, this is often called "MyDocument.xib". You can get rid of the old window and replace it with the type you prefer. Just remember to connected it to the appropriate outlet in File's Owner.
Comment: Yeah -- This.   Read the docs I pointed to, but this is the right answer. :)
Comment: I agree -- absolutely read those docs. It's one thing to change the window type, but to work that change into an application that makes sense will require changes to the document, too. You'll need an understanding of the document architecture.
Answer: An NSDocument [subclass] has an NSWindowController between the document and the document's window.  Typically, you'd subclass in NSWindowController to, say, create a document that has multiple windows.
In this case, you'll likely subclass NSWindowController to customize the creation of your window.   Or you could subclass NSWindow and have your document use your subclass instead of the generic NSWindow.
See the Document-Based Application guide.  The FAQ contains overview information on subclassing and the role of NSWindowController.


Como incrementar o contador com ng-repeat?

Question:

        {{ contador = contador + 1 }}

TESTDASDALGO

         1">
            {{ contador = 0 }}

Os valores estão sendo printados entre colchetes.
Uma outra dúvida:

A lógica deve ser feita no front? Tenho muita coisa condicional no meu projeto, provavelmente vai ficar bem confuso... (Há uma outra forma de se fazer)?

É possivel fazer algo parecido com o que escrevi abaixo?
var contador = 0;
angular.forEach($scope.columns, function(column){
    if(column.new){
        contador++;
        if(contador === 1){
            include('umarquivo.html');
        }
        if(contador > 1){
            '
'; //fechar uma div
            contador = 0;
        }
    }
});

Answer: Não há necessidade de realizar uma operação assim apenas para um contador de linhas, já que o ng-repeat fornece um automaticamente - $index:

angular.module('myApp', [])
.controller('myController', function($scope){
  $scope.paineis = ['aaaaa','bbbbb','ccccc','ddddd','eeeee','fffff'];
});

{{$index}} - {{i}}

Answer: Olá,
O ng-repeate fornece o índice da iteração, então você pode utilizar essa variável para auxiliar você a resolver o seu problema.
se quiser entender melhor o funcionamento do ng-repeat
https://docs.angularjs.org/api/ng/directive/ngRepeat

TESTDASDALGO

     1">
        {{ contador = 0 }}

Sempre evite colocar lógica de negócio na view, ela é responsavel pela representação da informação para usuário, procure sempre colocar lógica de views nos controllers


Does $ \Sigma_{n=1}^\infty(\frac{1}{n} - \ln(\frac{n+1}{n})) $ converge?

Question:
Does the following series converges or diverges:
  $$ \sum_{n=1}^\infty\left(\frac{1}{n} - \ln\left(\frac{n+1}{n}\right)\right) $$

I know that $ \sum_{n=1}^\infty \frac{1}{n} $ diverges and my intuition is that $\ln\frac{n+1}{n}$ doesnt effect it as it is going to $0$ as $n\to\infty$ so it still diverges but I'm not sure how to show it.
Thanks
Comment: $\frac{1}{n}-\ln(1+\frac{1}{n})=\frac{1}{2n^2}+o(\frac{1}{n^2})$
Comment: the result is the Eulergamma constant
Comment: Related: https://math.stackexchange.com/questions/2310697/how-can-we-show-that-sum-n-1-infty-leftx-over-n-lnnx-over-n-right/2310703#2310703
Answer: First note that
$$\sum_{n=1}^k(\frac{1}{n} -\log(n+1)+\log(n)))
=\sum_{n=1}^k\frac{1}{n}-\log(k+1)
=\log k+\gamma+\epsilon_k-\log(k+1)
$$
since the series telescopes (where $\epsilon_k\to 0$ and $\gamma$ is the Euler-Mascheroni constant). Finally
$$
\log k+\gamma+\epsilon_k-\log(k+1)=\log\left(\frac{k}{k+1}\right)+\gamma+\epsilon_k\to\gamma
$$
as $k\to \infty$ so that the series converges.
Comment: Why the downvote?  Please explain.
Answer: Use direct comparison test:
$$0<\frac1n-\ln\left(\frac{n+1}n\right)<\frac1{2n^2}$$
which follows from the Taylor expansion of the natural logarithm.
Comment: Why the downvote?  Please explain.
Answer: By Frullani's theorem
$$ \log\frac{n+1}{n}=\int_{0}^{+\infty}\frac{e^{-nx}-e^{-(n+1)x}}{x}\,dx \tag{1}$$
and since $\frac{1}{n}=\int_{0}^{+\infty}e^{-nx}\,dx = \frac{1}{n}$, by the dominated convergence theorem we get
$$\begin{eqnarray*} \sum_{n\geq 1}\left(\frac{1}{n}-\log\frac{n+1}{n}\right) &=& \int_{0}^{+\infty}\left(1-\frac{1-e^{-x}}{x}\right)\sum_{n\geq 1}e^{-nx}\,dx\\&=&\int_{0}^{+\infty}\left(1-\frac{1-e^{-x}}{x}\right)\frac{dx}{e^x-1}\\&=&\int_{0}^{+\infty}\left(\frac{1}{e^x-1}-\frac{1}{xe^x}\right)\,dx \tag{2}\end{eqnarray*}$$
where the function $g(z)=\frac{1}{e^z-1}-\frac{1}{ze^z}$ is regular in a right neighbourhood of the origin and has an exponential decay as $z\to +\infty$, hence it belongs for sure to $L^1(\mathbb{R}^+)$, implying that the original series is convergent. Additionally, the inequality
$$ \frac{1}{2}e^{-z}\leq \frac{1}{e^z-1}-\frac{1}{ze^z} \leq \left(\frac{1}{2}+\frac{z}{12}\right)e^{-z} \tag{3}$$
implies that
$$ \sum_{n\geq 1}\left(\frac{1}{n}-\log\frac{n+1}{n}\right)\in \left[\frac{1}{2},\frac{7}{12}\right].\tag{4}$$
Answer: The sequence of partial sums:  $S_n = 1+\dfrac{1}{2} + \dfrac{1}{3}+ \cdots+ \dfrac{1}{n}  - \ln n - \ln\left(\frac{n+1}{n}\right) \to \gamma$ ( the Euler constant ) which is the value of the series.
Comment: I believe there is a typo with your partial sums.


Organise android projects in eclipse and remove closed projects

Question: I want to know if there is anyway to organize the projects in Eclipse (In the package explorer) and remove closed ones.
Comment: r u want to remove it from harddisk or workspace ?
Answer: You can delete the project, then don't select 'delete from harddisk'. This will remove it from your explorer while keeping it on your PC.


Quadratic reciprocity and proving a number is a primitive root

Question: Let $p$ and $q$ be odd primes. Show that 2 is a primitive root of $q$, if $q = 4p + 1$
Comment: I have already shown that 2 is a quadratic nonresidue by applying Euler's Criterion formula
Answer: $ord_q2\mid \phi(q)$  $ \phi(q)=q-1=4p$
So, $ord_q2\mid 4p\implies ord_q2$ can be $2,4,p,2p,4p$
So, $p=2a+1,q=4p+1=4(2a+1)+1\equiv5\pmod 8$
Using this, $2$ is not a quadratic residue of $q\implies 2^{\frac{q-1}2}\equiv-1\pmod q\not\equiv1\implies 2^{2p}\not\equiv1$
So, $ord_q2\not\mid 2p$ so $ord_q2$ can be one of $4,4p$
If $ord_q2=4,q\mid(2^4-1)\implies q=3$ or $5$
But $3$ is not of the form $4p+1,$
and  $ord_32=2=\phi(3)\implies 2$ primitive root of $3.$
If $q=5,4=4p=5-1=\phi(5)\implies 2$ is  primitive roots of $5.$(here $p=1$ which is not considered to be prime, though)
$\implies ord_q2=4p=\phi(q)$ for $q\ge 5$


Does a strong checksum provide reasonable assurance of absolute data integrity?

Question: Does a checksum ensure absolute data integrity? That is, if a piece of data several gigabytes long changes a single bit, the odds are dependable that the checksum will be different, particularly with strong hash functions like SHA256?
Phrased differently, I'm asking whether a checksum offers assurance of reasonable integrity, that is, a few bytes here and there may commonly go astray without causing a checksum to fail (which would be fine for e.g., video files or other error-tolerant data streams), or does a correct checksum ensure the data is entirely intact?
To summarize, does a checksum provide assurance of sufficient integrity, or sufficient assurance of absolute integrity?
Comment: I'm sorry if this site isn't a good match for this question; if not, can it be migrated to the appropriate site instead of being closed?
Comment: Looks like a Stack Overflow question.
Answer: I'll give you a statistical answer. If the checksum from the file and the correct checksum (which I'll call the reference) disagree, we are 100% certain the file has an error. On the other hand if the checksum and the reference agree, we are reasonably assured the file is error-free.
How sure?
Suppose the checksum value is $n$ characters long in a $k$-letter alphabet. In an ideal checksum algorithm, an error occurring in the file will appropriately generate an incorrect checksum with probability
$$P_{chk}\text{(checksum fails|error)}=\frac{k^n-1}{k^n}=1-\frac{1}{k^n}$$
The assumption is that for any error or set of errors, the resulting checksum will be completely random. Since the correct checksum is $1$ in $k^n$ possibilities, then the probability that an error or set of errors in the file randomly results in the correct checksum value is $\frac{1}{k^n}$.
To illustrate this, let's make a basic checksum. I'll choose binary data ($k=2$ alphabet, either $1$'s or $0$'s). And let's say my file data is $M$ bits in length. We have to decide on an algorithm for our checksum. I'll propose that our simple algorithm is just the modulus of the base ten representation of our $M$ character data by $n$, our checksum character length. So for example $data=1001$, which represents 8+1=9, and let's say our checksum is $n=2$. From above, we know this isn't a good checksum, since $P_{chk}=1-1/4$, i.e., 25% of the time our checksum will erroneously agree with the reference despite containing an error. Nevertheless, the reference checksum for this example would be $9 \text{ mod } 4=1$, and our checksum in binary would then be $01$.
Now if we made an error in the data, for example, $data=1000$, we see that the checksum for the erred data would be $8 \text{ mod } 4=0$, or $00$ in our binary representation, so we'd be 100% confident that the data contains an error. On the other hand, if $data=0001$, $1 \text{ mod } 4=1$, and our checksum is $01$, we'd erroneously conclude that the data were correct.
To emphasize how much depends on the checksum algorithm itself, if you think about my toy algorithm, you'll realize it only catches mistakes in the lowest 2 bits. That is, the original statement is correct in the sense that agreement in my checksums will denote the data are correct 75% of the time; but only if errors are equally likely to happen in all bits. In reality, if the lowest two bits are correct, my checksum will always check out (try it yourself).
Lastly I just wanted to point out that given an ideal checksum algorithm, it's quite a remarkable tool. A gigabyte file you downloaded off the internet is $8589934592$ bits in length. To be truly sure that the file is correct, we'd need to compare the download to the actual file, which of course doesn't make sense (you'd already have the file!) Yet with a very modest choice of even an $n=64$, $k=2$ checksum (64-bit checksum), we can be sure with $P_{chk}=1-1/2^{64}\approx1$ that if the checksum and reference agree, our file is intact.
Comment: @JamesTheAwesomeDude What I was trying to convey to you was the importance of understanding how the checksum algorithm works. In my example, you can see there is a distinct difference between theory and practice because my checksum algorithm is *not* ideal. Also, different checksum algorithms have different purposes. In the most basic sense, an "ideal" checksum would give impossibly small odds of agreeing with reference given any error. In practice, the outcome depends greatly on algorithm used. But in general, yes, a checksum is not supposed to "tolerate" some errors unless designed to do so.
Comment: So we can confirm that a matching checksum has an almost zero likelihood of permitting *any error at all*?


Completeness of the space of sets with distance defined by the measure of symmetric difference

Question: Let $m$ be the measure defined on the set semiring $\mathfrak{S}_m$ and $m'$ its extension to the minimal ring $\mathfrak{R}(\mathfrak{S}_m)$. I read that $m'(A\triangle B)$ can be used as a distance in $\mathfrak{R}(\mathfrak{S}_m)$.
I would rather say that it can be used as a distance in the quotient $\mathfrak{R}(\mathfrak{S}_m)/\sim$ where we identify $A\sim A'$ when $m'(A\triangle A')=0$ [EDIT Mar 7'15: which is an equivalence relation, I would say, thanking future answerers for confirming or refuting this]: am I right?
I also read, in Kolmogorov-Fomin's Elements of theory of functions and functional analysis, that, with such a metric, the space $\mathfrak{M}$ of Lebesgue measurable sets, where $A$ and $A'$ are identified when $\mu(A\triangle A')=0$,  is complete, but I cannot see why, if $\{A_n\}\subset\mathfrak{M}$ is a sequence such that$$\forall\varepsilon>0\quad\exists N\in\mathbb{N}^+:\forall n,m\geq N\quad\mu(A_n\triangle A_m)<\varepsilon$$then a measurable $A$ must exists such that $\forall\varepsilon>0\quad\exists N\in\mathbb{N}^+:\forall n\geq N\quad\mu(A_n\triangle A)<\varepsilon$.
EDIT: Care Bear, whom I thank very much, has provided a proof for the case that $\bigcup_n A_n\in\mathfrak{M}$. According to Kolmogorov-Fomin's, $\bigcup_{n=1}^\infty A_n$ is Lebesgue-measurable only under the restrictive condition that $\exists K\geq 0:\forall N\in\mathbb{N}^+\quad\mu(\bigcup_{n=1}^N A_n)\leq K$ (problem 5 (b) here). Can anybody explain whether the lemma is valid in any case?
I $\infty$-ly thank you all for any answer!!!
Comment: FYI, I gave several references and applications to this metric in this [13 May 2005 sci.math post](http://mathforum.org/kb/message.jspa?messageID=3767449). See especially the paragraph beginning with "Note: This metric space has a number of interesting uses". I think this metric originated from Nikodym in the late 1920s, but I don't have my notes on this topic with me now to look it up. Finally, in that 2005 post I mention how to prove completeness in the paragraph that begins with "ADDITIONAL FACT: M[0,1] is a complete metric space".
Comment: By coincidence, I was looking at a paper this weekend that makes use of this metric. See the top half of p. 35 of Harry Max Schaerf, [*On the continuity of measurable functions in neighborhood spaces*](http://purl.pt/2158), **Portugaliae Mathematica** 6 #1 (1947), 33-44. The paper is freely available on the internet.
Comment: Thank you so much!!! The book has never made any mention of $L^1$ at the point where this interesting fact is stated: http://librarum.org/book/10022/144 :-( And I also see that, when it will discuss it, it will define it in a much less abstract way. Nevertheless, I suspect that, since $\mathfrak{M}$ must be a $\delta$-ring, we can use the corollary to theorem 11 at p. 267, which I think I've been able to prove in this more general case, which is the only case of limit concerning sets dealt with by the book; anyhow, I'm not sure how to use it...
Comment: Thank you very much: I'll look at it!
Answer: Quotient
Yes, you are right: in order for the distance to be a metric, and not just a "pseudometric", we need to take the quotient by the equivalence relation that you stated.
Completeness
Let's write  $d(A,B)=\mu(A\triangle B)$. To prove completeness of the space, it suffices to show that every sequence $A_n$ with $$d(A_n,A_{n+1})\le 2^{-n}\tag1$$ has a limit. This is a general metric space fact: from any Cauchy sequence one can extract a subsequence with property (1), and therefore obtain the convergence of the whole Cauchy sequence.
Let $B_n=\bigcup_{m\ge n }A_m$ and $C_n=\bigcap_{m\ge n}A_m$; both these sequences are nested. From (1), summing a geometric series,  we obtain $d(A_n,B_n)\le 2^{1-n}$ and $d(A_n,C_n)\le 2^{1-n}$. Hence $\mu(B_n\setminus C_n)\le 2^{2-n}$. Let $E=\bigcap B_n$. Since $C_n\subset A_n\subset B_n$ and $C_n\subset E\subset B_n$, it follows that $$
\mu(A_n\triangle E) \le \mu(B_n\setminus C_n)\to 0
$$
which proves $\lim A_n=E$ when $\mathfrak{M}$ is a $\sigma$-algebra.
Comment: (A) If a Cauchy sequence has a convergent subsequence, then it converges [exercise with definition of limit and Cauchy].  (B)   I did not say that $\mu(\bigcup_{m\geq n+1}B_m)=d(A_n,B_n)$, and this is not true.  Rather, I use $B_n\setminus A_n \subset \bigcup_{m\ge n} (A_{m+1}\setminus A_m)$. If a point is in $B_n$ but not in $A_n$, there is some set $A_{m+1}$ where it first appeared.
Comment: Everything happens within $\bigcup A_n$, which is a set of finite measure. You can restrict all considerations to this set, thus obtaining a unit.
Comment: I read in your question that $\mathfrak{M}$ is the space of Lebesgue measurable sets. The countable union of Lebesgue measurable sets is Lebesgue measurable. And I'm only kind enough to post 3 follow-up comments, which means this is the last one.
Comment: I find the explicit construction of $E$ fascinating. I don't understand a pair of things: why, if any subsequence satisfying (1) converges to $E$, then the sequence  converge to $E$? why $\mu(\bigcup_{m\geq n+1}B_m)=d(A_n,B_n)\leq 2^{1-n}$ and $\mu(A_n\setminus\bigcap_{m\geq n}A_m)=d(A_n,C_n)\leq 2^{1-n}$? $\infty$ thanks!
Comment: Thank you so much again!!! I had misunderstood what $A_n\triangle B_n$ is. (A) is a very useful lemma: I've proven and pencil written it on the margin (though I'm not Fermat). As to the other majoration, I see that $A_n\triangle C_n\subset\bigcup_{m\geq n}A_m\setminus A_{m+1}$, so I understand.
Comment: I realise you consider countable unions like $B_n$ as belonging to $\mathfrak{M}$, which I suspect not to be possible in general if ours is not a unitary ring ($\mathfrak{M}$ would be a $\delta$-ring, but not a $\sigma$-algebra): please correct me if I'm wrong. Does the lemma apply only to unitary rings $\mathfrak{R}(\mathfrak{S}_m)$ or also to non-unitary rings? $\bigcup_{n=1}^\infty$ thank$_n$! ;-)
Comment: You're very kind! I tried to verify that, but I didn't succeed... Why $\bigcup_n A_n\in\mathfrak{M}$? I tried to use the fact that $\{A_n\}$ is Cauchy, therefore bounded, i.e. I know that $\exists S\in\mathfrak{M}:\mu(A_n\triangle S)\leq K$ for some $K\geq 0$, but that hasn't helped me... Thank you again!
Comment: According to Kolmogorov-Fomin's $\bigcup_{n=1}^\infty A_n$ is Lebesgue-measurable if and only if $\mu(\bigcup_{n=1}^N A_n)$ is bounded by a constant independent from $N$: http://librarum.org/book/10022/145


Entity framework nesting complex types

Question: I have a stored procedure that returns multiple result sets.  Each one is a complex type.  The first result set would contain a list of items of the same complex type as the second result set, etc.  These do not cleanly correlate to specific entities.  For example, my POCO classes should be
public partial class Message
{
    public string Subject { get; set; }
    ...
    public List<Recipient> Recipients { get; set; }
}

public partial class Recipient
{
    public string Email { get; set; }
    ...
}

According to the documentation, "Entity and complex types can now be nested inside classes" for EF 6.  However, I cannot figure out how to create a LIST of a complex type within my first complex type.  When I edit my FunctionImport and use Get Column Information, it only returns the first complex type.  When I try Create New Complex Type, it still only returns the first complex type.  Finally, I have created all of the complex types I need manually and tried to add the Recipient complex type to the Message complex type, it will only allow a single Recipient to be added.  Is there something special you need to do to nest complex types?  Are there any examples out there?  I could not find anything that addressed this on CodePlex, but I may just be missing it.
Thanks in advance for all your help!
Answer: By nesting is in my opinion meant putting one class declaration into another:
public class A {
    public class B { }
}

In previous versions of EF, class B could not be mapped neither as entity or complex type while in EF6 it can be. It is the only meaning of nesting related to this feature.
When it comes to your question you still cannot map list of complex types. If you want a list you need to use entities (both as parent and children).
Comment: Thanks!  I was hoping there was a better way to handle my situation than listed in [this article](http://msdn.microsoft.com/en-us/data/JJ691402.aspx) on multiple result sets.
Comment: @ChristyPiffat: You would not avoid multiple result sets anyway because hierarchies are not mapped automatically when executing stored procedures. Stored procedures can return only flat objects per result set.

Entity framework nesting complex types


Will this code allow me to assign a number to a list and incrementally increase the number?

Question:  [ set list N = 1 () set list N = 1
   lput number-of-patches destination origin list N  N + 1]

I wish to be able to store information about collections of patches and when the criteria for the filling of the list is met the number of the list will be increased. Will this code work?
Comment: Sure it is. Change it temporarily to produce output, and see if it outputs what you need it to in order to test it. You don't have to put it in your actual program - a quick test program would work. If I had to wait for someone at SO to tell me if code I wrote worked or not, I'd never get anything done (and neither would anyone else).
Comment: FYI, NetLogo's [network extension](https://github.com/NetLogo/NW-Extension#readme), which is bundled with NetLogo 5.1, has an implementation of Dijkstra's algorithm, so you should not have to implement this yourself.
Comment: What happens when you try it? It seems you could have done that faster than you could have written and formatted your question here.
Comment: I can,t test this at present because it will produce no visible effect within my program. The purpose of this code is to allow me to calculate the distance of the links between to node patches. This will require the implementation of Dijkstras algorithm to achieve this which will be very complex. I am trying to ask whether the method of incrementing the list will work, it is not possible for me to test it at present.
Answer: Just looking at it, it will give you several syntax errors, regardless of whether the structure will do what you want. For example, the way you should construct a list with element '1' and name 'N' (which is what I think the first line is supposed to do) would be set N (list 1). You can test this by writing code as below and running test (eg by typing test in the command center at the bottom of the interface).
globals [N]
to test
  set N (list 1)
  print N
end

When writing code, your life is a lot easier if you build up the code in pieces, testing each one as you go either by inspecting agents to see if their property values change as you expect and/or putting print statements in lots of places to see what happens to your variables. This way you are introducing and fixing only a small number of errors in each step. Also, this means you are never writing code that you can't test immediately.
Comment: I'm sorry, I do not want to have a list with N = 1 items but rather a list with three items (number of patches , destination , origin) that will be inserted within the list once each piece of data is available for insertion. The N = 1 represents a means of identification of the list and is incrementally increased (using NN+1) each time the list is created. This will allow me to be able to easily reference the data for a road length within a route finding algorithm by looping through lists and referencing the position of the relevant piece of data so that it can be used within the algorithm.
Comment: Since you responded after Nicolas's comment, I am guessing that you don't want to use the already implemented algorithm in the Network extension for some reason. If this is true, please give an example telling us what you want to call your list (is it N, is it 1 , is is something else?). When you say 'each time the list is created', does that mean you have multiple lists? Or did you mean that a single list has additional items appended (which is what lput does)?


Do all the servers in a server room function as one server?

Question: In a server room..do all the servers function as one server? Is it like a bunch of computers doing the same think (like a cluster supercomputer) and how do they communicate with each other?
I have been looking everywhere on the internet but I still can't figure out how server rooms work.
Answer:
in a server room..do all the servers
  function as one server?

In your closet where you store your clothes, do all the trowsers work like one trowers?
The definition of a server room is: A room for servers. Mostly to keep them in a controlled environment (cooled, controlling who can steal them etc.).
There is NOTHING more in the definition of a server room. It is simply a room for servers.
Comment: THat one is for desktop use, the other for server use.
Comment: But only you wear all the clothes in your closet. Do servers in the same server room serve to only one client?
Comment: Maybe, Maybe not. Depends. Doesa closet only have stuff for one person? Seriously, what are you talking about? Server room in a company? LIKELY one client. Server room for a hosting center - likely one client per x servers. Not defined.
Comment: one more question..whats the difference between a server OS and desktop OS
Answer: That depends on the particular group of servers you're looking at. It could be Ethernet, Infiniband, FibreChannel, fiber optics -- practically anything connecting the servers together.
Usually servers perform distinct tasks unless you are really talking about a cluster designed to be a supercomputer (though VMWare & friends has blurred that line recently because a given workload can be moved around between different physical servers with impunity). Applications which wish to make full use of the processing power offered by that many machines needs to be specifically engineered to allow distributed computing of that sort -- they operate just as if you'd install that application on hundreds of desktop machines.
Really, there's little difference between desktop hardware and server hardware except that server hardware is much more expensive, and much more reliable, and much faster.
Comment: so do all the servers in a server room do different things?
Comment: @user46869 Not necessarily. Like Billy said, it depends on the requirements. If the owner of the data center needs a cluster/distributed computing environment, then many of the machines may be doing the same thing. If that's not a requirement, then many will be doing different things. There is *no* one-size-fits-all answer to your question.
Comment: server hardware is not necessarily faster than desktop hardware. It is usually more reliable, usually more expensive, and usually includes much more robust remote management/monitoring hardware (iLOM, ipmi, etc) than their desktop counterparts.
Comment: @ErikA: I was thinking mainly of hard drives -- 15k RPM drives are common for servers, but you'll rarely see them in a desktop. Servers usually also have extensive RAID arrays. But for things like CPU performance, true, servers aren't that much faster other than that server boards often take more than one CPU at a time.
Comment: But I know quite some server rooms without 15k hard drives ;) Somebelonging to smaller hosters (large+cheap drives, please), one to myself (I rather go 10k velociraptor + if needed a SSD cache).
Answer: All the servers in one server room are merely sharing in a facility that is (well should be) optimal for server use - a secure, temperature controlled environment, ideally with fire suppression and environmental monitoring.
They might or might not be working together in a cluster. More likely is that while there might well be machines in some kind of cluster arrangement in a server room, it would only be some of them, not all of them. Possibly these days its more common than people might think at first if one considers all the host servers in a virtualisation array as "clustered together" doing the same thing.
There's nothing inherent in a server room that makes a difference one way or another as to whether or not all or some of the servers inside it are in a cluster.


How to add certificate to drupal_http_request()?

Question: I am currently setting up a payment method in my Drupal 7 site and following the API documentation for the service I could use this cURL command for testing purposes:
$ curl -s -S -i --cert
./Swish_Merchant_TestCertificate_1231181189.p12:swish --cert-type p12 --
cacert ./Swish_TLS_RootCA.pem --tlsv1.1 --header "Content-Type:
application/json"
https://mss.cpc.getswish.net/swish-cpcapi/api/v1/paymentrequests --data
'{ "payeePaymentReference" : "0123456789", "callbackUrl" :
"https://myfakehost.se/swishcallback.cfm", "payerAlias" : "4671234768",
"payeeAlias" : "1231181189", "amount" : "100", "currency" : "SEK",
"message" : "Kingston USB Flash Drive 8 GB" }'

But since I am developing this function in Drupal 7 I want to use drupal_http_request instead. But I am confused about how to include the certificates used in the cURL command. Anyone?
EDITED:
After the suggestion below I added a context parameter. I still get "connection refused by destination". Is there anything more I should do? This is how my function looks so far:
function create_payment_request(){
  // Send payment request to Swish API
  $headers =  array('Content-Type'=>'application/JSON' );
  $url = "https://mss.cpc.getswish.net/swish-cpcapi/api/v1/paymentrequests";

  $context = stream_context_create([ 'ssl' => [
  'local_cert'        => '/mypathtocertificates/TestCertificate_123456789.pem',
  'passphrase'        => 'pass' ]]);

  $json = '{
  "payeePaymentReference": "0123456789",
  "callbackUrl: "/swish_callback",
  "payerAlias": "4671234768",
  "payeeAlias: "1231181189",
  "amount": "100",
  "currency": "SEK",
  "message": "testo 925"
}
';

  $options=array(
      'headers'=>$headers,
      'context' => $context,
      'method'=>'POST',
      'data'=>$json,
    );

    $result=drupal_http_request($url, $options);
    dpm($result);
}

Answer: You need to supply a context parameter in the options for drupal_http_request. The value is a stream context created using the PHP function stream_context_create.
There are a lot of possible parameters so you may have to hunt through the parameter list to find the ones you want.
Comment: Thanks a lot! I have edited my question. There is still something wrong though, the destination refuses to connect.
Comment: Not an expert on this but might you need a cacert entry as well?
Comment: That took me one step further. Now the status is "connecting", but I still get an error: "Error initializing socket". But thanks a lot, I will contact this payment provider directly to figure out the rest. Thanks a lot for your input. Correct answer since the context parameter is just what was missing.


Rolling a dice 10 times and getting exactly r same roll.

Question: I am interested in the probability of rolling a six-sided dice 10 times and getting exactly r same roll. I wrote a simple brute-force Monte Carlo simulation program to get the probability, and I also calculated the probability using binomial distribution mass function.
My Monte Carlo simulation flows like this:
-> roll a dice 10 times (an example roll: 2,1,3,4,3,6,5,3,3,2)
-> count the number of same rolls (for the example above, 2:2, 3:4)
-> extract the highest number of same rolls (for the example above, extract 4)
-> record in a list accumulating the counts (for the example above, the key "4" will increment by 1 since it's 1 case where the roll result in 4 of the same)
-> repeat 100,000 times
I used binomial mass function like this:
for example, getting exactly 8 of the same 6*10C8*(1/6)^8*(5/6)^2 = 0.0111%
The Monte Carlo result and the binomial function result converge when the r is larger than 4, but diverge when r <= 4 . See below list of results:
M.C. Result: {2: 6.7621, 3: 52.9124, 4: 31.0536, 5: 7.8071, 6: 1.3046, 7: 0.1483, 8: 0.0111, 9: 0.00046, 10: 1e-05} %
Binomial Result: {2: 174.426, 3: 93.0272, 4: 32.5595, 5: 7.8143, 6: 1.3024, 7: 0.1488, 8: 0.0111, 9: 0.00050, 10: 9.922e-06} %
I'm just wondering why it works up until 3 or 4...
Comment: If I understand correctly, you are calculating the pmf of the maximum component of a multinomial vector. Since the number of trials is $10$, when a particular component is greater than or equal to $5$, then it must be the maximum. Since the marginal distribution of each component is binomial, your method work in such case. However when you want to calculate the probability that the maximum is equal to $4$ or less, then you cannot use this method. There are possible cases where there exist other component is larger than this one.
Comment: Your binomial computation is an overcounting. For instance, when $r=3$, there are sequences of rolls in which 2 numbers both appear 3 times each. In your method, this sequence would be counted twice. Of course, this becomes unlikely for large $r$, and disappears when $r>5$.
Answer: Consider this roll: 1, 1, 1, 2, 3, 6, 6, 6, 6, 6. It is a valid case for $r=3$ in your function $6\cdot \binom{10}{r}\cdot \left( \frac{1}{6}\right) ^r \cdot \left( \frac{5}{6}\right) ^{10-r}$. However, we can see the problem - this roll should be considered only for $r=5$ because of five same rolls. The Monte Carlo counts this for $r=5$, but it is also one of rolls involved in calculation for $r=3$.
This is obviously caused by the factor $\left( \frac{5}{6}\right) ^{10-r}$. The initial 6 in your formula chooses, which number will be that, which is $r$-times repeated, but this doesn't prevent possibility, that some (maybe more than $r$) of the other will be same to each other. The problem is mostly visible on small $r$'s, because there is the highest probability (actually, on $r>5$ it is rather impossible), that this situation happens.
You will need to find a correct distribution. However, it will be much more complicated.
Comment: Thank you. It makes so much sense now.
Answer: The issue is that the probability is actually more complicated than the binomial formula you have.  Let's look at the case of $r = 2$: you're calculating the probability that one number comes up exactly twice and then multiplying by six.  What this quantity is, is the expected amount of numbers that come up exactly twice.  This is (significantly) different than the probability that $2$ is the largest frequency.  In particular, you need to account for two facts:

That $2$ will only be recorded if nothing comes up three times
That even if two (or more) numbers come up twice then you only count $2$ once.


Why does Box-Cox transformation fail in following situation?

Question: In the book, Linear Models with R by Julian Faraway, it says that if max(y)/min(y) is small, then Box Cox won't do anything because power transformations are well approximated by linear transformations over short intervals.
Why does it say that power transformation is approximated by linear transformation over short intervals? And if so, why when max(y)/min(y) is small, Box Cox fails?
Comment: I don't think Box-Cox fails here. It just tells you that keeping the existing scale is fine, or that using a transformed scale doesn't help much.
Comment: $(m+h)^r\approx m^r(1+r\frac h m)$ for small $\frac h m\le\frac M m-1$
Answer: (mostly copied from the comment by Nick Cox)   The Box-Cox transform does not really fail: it is more that it is unnecessary, as there will be no need of transformation if max/min is small.  Mostly, with max/min small all the observations are away from zero (relatively), so the power transform will be well approximated linearly over a short interval!
Comment: I will edit that


Clefs for saxophone playing

Question: Is alto saxophone music written for ordinary treble and bass clefs?
Comment: If this question is just about clefs and not about the transposing of the Sax then it could have very easily just been answered with a google search.
Answer: Most saxophones, and all the "usual" saxophones, are transposing instruments. This means that when they read and play a C on their sheets, the sound that comes out is not a piano C.
Saxophone music is thus always written in treble clef, but they don't sound like a piano treble clef when played.
Sopraninos, altos, baritones and contrebass saxophones are in E♭, meaning that their C is a piano E♭.
Soprillos, sopranos, tenors and bass saxophones are in B♭.
There are also a few rare saxophones in C (i.e., non-transposing or, possibly, transposing by octaves) and in F1, but you probably can't find music written from them readily in the commerce.

Adolphe Sax designed a range of saxophones for the symphonic orchestra, in which instruments are mainly in C, and another one for wind bands and military orchestra, in which instruments are usually in B♭ and E♭. Wind bands readily adopted the instruments while symphonic orchestra did not, which lead to the disappearance of C and F instruments.
Comment: I don't see how this answers the question. The question as I understand it asks about what clefs the instrument's music is written in. Bass / Treble / Alt or Tenor.
Comment: It's written in the text that music is written in treble clef but that it does *not* correspond to the piano treble clef as in an middle A written for saxophone is not 442Hz (or so). What would you add to that?
Answer: Saxophone is written in treble clef, transposed alternately in Bb and Eb (soprano is Bb, alto is Eb, tenor is Bb, etc.).

Clefs for saxophone playing


How to initialize different classes of objects automatically?

Question: I want to make a class registry class that automatically makes a UITableViewCell and when the user presses the button it'll go to that class and run the code.
Currently to do something like that, in the view controller I have to do something like this
Function1Class *function = [[Function1Class alloc] init];
function.view.backgroundColor = [self veryLightGrayColor];
[self.navigationController pushViewController: menu animated: YES];

Then in the data source I make a new case in cellForRowAtIndexPath, and in the delegate I make a case in didSelectRowAtIndexPath for a one line method call.
I'd like to change the code so anyone that wants to add a new class to this page can just do it at one place, something like:
Function1 *function;
[self addClass:function];

And in addClass the "function" passed in will be stored in an array
For the cellForRowAtIndexPath and didSelectRowAtIndexPath cases they can easily call the right methods by storing in an array.
The problem is how do I automate the initialization of each class object passed into addClass?
I could get the user to write code like this to add in their class
Function1 *function = [[Function1 alloc] init];
[self addClass:function];

Then the class object is already initialized, but that means during startup EVERY class object is getting initialized, which is a problem if there is a lot of classes. How can I take out a class object from the array, and then initialize it to use it? The class objects are all different classes, so I can't hardcode arrayOfClassObjects[i] = [[Function1 alloc] init];
Thanks
Comment: Can you use reflection? Something like `[[NSClassFromString(@"ClassNameOnlyKnownAtRuntime") alloc] init]`?
Comment: ^That might be very promising. Let me try that out.
Answer: Classes are objects, so you can store the classes in an array:
NSArray *functions = @[ [Function1 class],
                        [Function2 class] ];

Then, when you want to instantiate one, you make it indirectly:
id instance = [[functions[0] alloc] init];

So your addClass: should be something like:
- (void)addClass:(Class)cls {
    [self.classList addObject:cls];
}


Prove a set of continuous function is bounded.

Question: Let $C_b(\mathbb{R})$ denote the space of all bounded, continuous functions $f : \mathbb{R} → \Bbb C$. Let $C_0(\mathbb{R})$
denote the set of continuous functions $f : \mathbb{R} \to \Bbb C$ for which
lim $f(x) = 0$ as $x\to\pm \infty$.
a) Prove that every $f ∈ C_0(\mathbb{R})$ is bounded.
So I need to show $|f| < M$ for some $M$.
b) Prove that $C_0(R)$ is closed in $C_b(R)$
I just really need help.  I don't know how to show these two things.
I know that $d$ makes $C_b(\mathbb{R})$ into a complete metric space.  That's the only Theorem from class I really have.
Comment: hint: On large closes balls $f$ is bounded. Can you use the decay of $f$ to zero to show that the function is small far outside?
Comment: Yes the $f:R->C$ and I'm not sure what the decay of f to zero is.  Haven't learned that.
Comment: hint on b: can you show that any sequence in $C_0$ that converges uniformly to some $f$ is again in $C_0$?
Comment: $f(x)=0$ as $x\to\pm \infty$ means that $f$ decays to zero
Comment: mean of $C$ is $\mathbb{C}$(complex number?)
Comment: Yes, I mean the complex numbers.
Comment: Did you lose your interest on this question?
Answer: Since $f$ tends to zero as $|x|\to \infty$, there exist $R_0$ such that $|f(x)|\leq 1$ for every $|x|\geq R_0$. Due to compactness of $[-R_0,R_0]$ we find that $f$ is bounded there by a constant $M$. Thus $\|f\|_\infty\leq \max\{M,1\}$
Let $f_k \in C_0(\mathbb{R})$ be given and such that $f_k\to f$ uniformly (i.e. in $C_b(\mathbb{R})$. This is an assumption! If $f$ turns out to be in $C_0$, we have shown that $C_0$ is closed in $C_b$ by definition. We need to show that $f(x)=0$ as $|x|\to\infty$.
For every large enough $|x|$ and some fixed $k$, we find the estimate $$|f(x)|\leq |f(x)-f_k(x)| +|f_k(x)| \leq  \varepsilon$$
The first term in the middle is small due to the uniform convergence, the second term tends to zero for fixed $k$.
@ OP: Can you give the precise argument here?
Comment: I think you used the wrong norm in (2), but I don't see big changes.
Comment: Could you be more specific? I simply want to show that the uniform (here the supnorm enters) limit $f$ of $f_k$ is again in the $C_0$
Comment: For the last statement you can use $|f (x)| \leq |f_k(x) - f(x)| + |f_k(x)|$. For some fixed large enough $k$.
Comment: How did we get $f_k -> f$ uniformly?
Comment: @ John: I also thought about putting this in, but rejected the idea first. But due to you comment I finally changed my answer
Comment: @user201483 That's an assumption. Convergence in the metric on $C_b(\mathbb{R})$ is precisely uniform convergence in the standard analytic sense. So we are taking some arbitrary sequence in the subspace which converges in the large space and showing that its limit is in fact in the subspace, which is enough to show that it's closed.
Answer: Problem a) is easy.
Ad b): I'm assuming that your distance $d$ is defined by $d(f,g):=\sup_{-\infty<x<\infty}|f(x)-g(x)|$. Consider a function $f_0\in C_b\setminus C_0$. Then there is an $\epsilon>0$ and a sequence $(x_n)_{n\geq1}$ with $|x_n|\to\infty$ $\>(n\to\infty)$ and $|f_0(x_n)|\geq 2\epsilon$ for all $n\geq1$.
Now the set
$$\bigl\{g\in C_b\>\bigm|\>d(g,f_0)<\epsilon\bigr\}$$
is a neighborhood of $f_0$ that does not intersect $C_0$.


How to upgrade to Drupals latest version via Composer?

Question: Currently I have 8.6.13 installed.
composer update drupal/core --with-dependencies
Package "drupal/core" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update

When I tried to look in to composer.json we don't have drupal/core in
require.
https://www.drupal.org/docs/8/update/update-core-via-composer
How to upgrade to 8.7.0?
$ composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.0].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.1].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.10].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.11].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.12].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.13].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.14].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.15].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.2].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.3].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.4].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.5].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.6].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.7].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.8].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.9].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.x-dev].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.15].
    - drupal/core 8.7.0 requires egulias/email-validator ^2.0 -> satisfiable by egulias/email-validator[2.0.x-dev].
    - Installation request for drupal/core 8.7.0 -> satisfiable by drupal/core[8.7.0].
    - Installation request for egulias/email-validator ^1.2 -> satisfiable by egulias/email-validator[1.2.0, 1.2.1, 1.2.10, 1.2.11, 1.2.12, 1.2.13, 1.2.14, 1.2.15, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.2.8, 1.2.9, 1.2.x-dev].

Answer: I had exactly the same issue while performing upgrades. The solution for me was removing/renaming the vendor folder and the composer.lock file and run composer update drupal/core --with-dependencies.
You can also try to update dependency explicitly with composer update egulias/email-validator drupal/core --with-dependencies. This usually works in this type of issues, but it didn't work for me.
Given that you don't see drupal/core in your composer.json you might also try composer require drupal/core.
Answer: Before installing with Composer, make sure to remove the vendor directory and the composer.lock file and run composer install.


Achieving/maxing out 1GBPS connectivity on a nginx server

Question: This page (http://www.remsys.com/nginx-on-1gbps) claims that it can max out a 1gbps line using JBOD setup and no raid. Currently I'm on a 1gbps dedicated port and I'm on raid 10 (4x2TB - the disks that comes with 100tb.com servers).
Currently I'm only peaking at 500-550mbps. wa% would show something around 20% everytime.
I'm looking into maxing out this 1gbps port because I have an unmetered service from them. Do you guys think that the page that I referenced would be better than my current raid setup? Do you guys have any other suggestions on how to max out the performance of this server? TYI.
Comment: That's what i was going to write, i have yet to see 1Gbps unmetered, real unshared for under 3.000 US$/month
Comment: Just because it's unmetered doesn't mean there aren't other servers on their main pipe...
Comment: It is unmetered and dedicated. It's 100TB, softlayer network. 100TB is a known host.
Comment: @AnsellCruz That's irrelevant. Even reputable hosts have a good chance of overselling bandwidth, because customers tend not to sit pegged at the max. A host with 20 servers might have 10 Gbps of bandwidth in their network, but be able to fairly promise 1Gbps per server the majority of the time.
Comment: Alright thanks for the comments. Then lets assume that its a 1gbps dedicated pipe. The question is disk related, regardless of the line speed.
Answer: A lone 2 TB disk can fill a gigabit pipe these days. That requires 125 MByte/sec, which is right about what you should expect for a 7200 RPM 2 TB disk.
Now, that assumes you're sending just one big file down the link, and there's no fragmentation in the file. With RAID-10, you at least double the read data rate of a single disk, and if you're using a decent RAID controller, quadruple it. (Write data rate is only doubled with 4-drive RAID-10.)  This gives you enough excess disk I/O capacity to deal with a bit of fragmentation or a small amount of concurrent access.
If you benchmark your disk array, you will probably find that read performance drops by an order of magnitude or more for random reads. This is what happens when there is fragmentation, or when you start sending too many simultaneous files. The disk drive heads spend more time traveling between sectors on the hard drive than they spend in place reading data.
The article suggests breaking the data up and giving each disk its own nginx instance, but that only works if you are able to predict a good way of evenly dividing the workload across disks and nginx instances. If your clients demand downloads unpredictably, you could end up concentrating all reads on a single disk, giving worse performance than the RAID configuration.
If you absolutely had to have better performance without changing the hardware configuration and benchmarked series read performance at only 2x that of a single disk, you could shift to RAID-0. You'd have greater risk of disk failure this way, of course.
The article you link to claims nginx has a really bad I/O performance problem with file reads. Perhaps it has since been fixed. If not, you can alleviate it with multiple nginx instances. You don't have to tie them to individual disks as suggested in the article. You could just set up a proxy to distribute requests round-robin fashion. You'd want to benchmark this carefully to tune the proper number of nginx instances for your particular workload. There is no single "right" answer for all situations.
You could also be running into the problems associated with TCP slow start or one of the inefficiencies in HTTP fixed by SPDY. There's not a whole lot you can practically do about these issues today. The solutions require widespread deployment of experimental technology, which due to network effects means you're looking at a rollout time of years, maybe even decades.
If the problem is simply due to trying to serve too many simultaneous users or too few large files, thereby pushing your disks toward the random file access end of the scale and away from the series I/O end, there's nothing you can do short of adding more spindles. That could mean going with a 6+ disk RAID-10 configuration, multiple servers, or some combination.


Show field twice in node page

Question: I created a custom bundle (content type) and I've created fields
One of those field is a file type field, is a video file, stored in the private storage. I installed the videojs module to allow to watch the video.
I need to show this field twice in the node page. One in the generic file formatter that allows the user to download the file, and I also need to play the video. I decided to set up as generic file formatter and customize the twig template to show again with the video player.
I achieve to show twice with the settings formatter (generic file) with this code in the node--mybundle--full.html.twig template
{{ content.field_sd_video }}

I thought it would be something easy like field+formatter:
{{ content.field_sd_video|videojs_formatter }}

But I can't find a simple way to achieve this.
Answer: You can do this in UI, UI and code mixed, code only and in html:
Display Suite
Install the module Display Suite and configure this in UI.
Extra Field
Use the hook hook_entity_extra_field() to get an extra field in Manage Display. You need hook_ENTITY_TYPE_view() to copy the data (in this case the file) into the new field.
Clone field in code
See
How to display a field twice in a view mode?
The last has the least overhead, but is not customizable and you have to define the field settings yourself. If you configure the second field temporarily in UI and export the view mode to yaml this helps to find the settings you need in code.
Place link html in template
Or if you want a quick solution in the template and you only need a simple formatted file link you can get the file url from the node and put it in html markup:
Example Video

Comment: Or you could preprocess node too, and create a new variable that themes the value of the filefield into a link, and output that in the twig template
Comment: Yes, @Kevin. I tried that. I'm trying to get the field value and change the formatter. But I'm not sure, how can I access to the field value. In the preprocess_node I've the $variables['node'] and I know exist the [videojs theme]8http://cgit.drupalcode.org/videojs/tree/README.md#n105) function.
Comment: @4k4 I would like to not have to implement a module, I believe that the 2nd and 3rd solution needs a custom module, isn't it ? I thought I could achieve this in my own bootstrap subtheme that I already have.
Comment: @ferriol, see my 4th example
Answer: I finally found the solution, I put this code in preprocess node function. It has to be easy, but not easy to know how ;)
function mytheme_preprocess_node(&$variables) {

     $variables['video_caption'] = $variables['node']->get('field_video')
         ->view(array(
            'label' => 'hidden',
            'type' => 'videojs_player_list'
        ));
}

and I only has to add this line in twig file:
{{ video_caption }}

in my case node--mybundle--full.html.twig template
Thanks @4k4 your answer was usefull
For those arrive here looking for something similar
I was inspired by Twig Recipes on page 41
It was usefull for me Twig debugging. Playing with kint and node variable and the classes used to wrap the information. Then I found that the field comes with FileFieldItemList and then I found the view method that uses EntityViewBuilderInterface
Comment: That's a very helpful for others, providing the final solution. Btw. this is similar to http://drupal.stackexchange.com/questions/218144/how-to-display-a-field-twice-in-a-view-mode, only that you get the field object `FileItemList` from the node and in the linked question it is coming from the source field.

Show field twice in node page


Drupal Commerce Export Orders in CSV format

Question: How can I export Order details along with custom line item fields data in CSV format?
Comment: You can use Views and Views Export modules. It is kinda straight forward. Views Export provides you with a Export display , you do the filter in the view and in the end it will return you a link where the orders can be downloaded in csv format . Success!
Answer: You can use Views and Views Export modules.
Views Export provides you with a Export display, you do the filter in the view and in the end it will return a link where the orders can be downloaded in csv format.


Inverse of a triangular matrix

Question: Let $A$ be an $n \times n$ upper triangular matrix with integer entries and all diagonal entries are $1$

Prove / Disprove: $A^{-1}$ is not a power of $A$ unless $A$ is the identity matrix

I only know $A^{-1}$ exists and of course, it has all integer entries.
Any help?
Comment: $A^{-1}=\frac{1}{det A} adj A$ , $det A=1$ and $adjA$ has all integer entries
Comment: Why must $A^{-1}$ have all integer entries? Was this (like the fact that diagonal entries are $1$) given as part of the problem? Are there any other "givens" that you've failed to mention (like the diagonal entries)?
Comment: yes , all diagonal entries are 1. See my post again, i have edit it!
Comment: I saw that. I was asking if there was anything *else* that you didn't mention. Also: how do you know that $A^{-1}$ has all integer entries?
Comment: Right. (That wasn't so clear before you added the "diagonal = 1" constraint. :( )
Answer: Hint: work out the $2 \times 2$ and $3 \times 3$ cases by hand (i.e., assume your matrix is
$$
A = \begin{bmatrix}
1 & a \\ 0 & 1
\end{bmatrix}
$$
and its inverse is
$$
A^{-1} = \begin{bmatrix}
1 & c \\ 0 & 1
\end{bmatrix}
$$
and see what you can conclude about $a$ and $c$.
Answer: Denote $A=I+N$ where $N$ is some nilpotent non-zero upper triangular matrix and suppose $A^{-1}=(I+N)^k$.
Then it should be $(I+N)^{k+1}=I$ and then with the use of of binomial formula $a_1N+a_2N^2+\dots+ a_{k+1}N^{k+1} =0 $
$N(a_1I+a_2N +\dots+ a_{k+1}N^ k)  =0$
but $B=a_1I+a_2N +\dots+ a_{k+1}N^ k$ is full rank matrix and $N$ in nonzero matrix so it is impossible to be $NB=0$.
So $N$ must be $0$.
Comment: Very nice!.....
Comment: @lhf Thank you, we have similar answers given almost at the same time :)
Answer: Hint:  It is enough to prove that $A^m=I$ implies $A=I$.
Write $A=I+N$ with $N$ nilpotent. Then $A^m$ is easy to compute using the binomial theorem. Argue that $A^m=I$ implies $N=0$ by considering the diagonals of $N$. For instance, the secondary diagonal of $A^m$ is $m$ times the secondary diagonal of $N$.

Inverse of a triangular matrix


Prove that the preimage of an affine scheme is affine for an affine map of schemes

Question: Let $f\colon X\rightarrow Y$ be an affine map of schemes (i.e. there is an affine open cover $(U_i)_{i\in I}$ of $Y$ such that $f^{-1}(U_i)$ is affine for all $i$).
Now given some affine open subscheme $V$ of $Y$ I need to show, that $f^{-1}(V)$ is also affine.
So every solution I have found online either uses quasi-coherent sheaves or fiber products. But we did not learn these yet. My Problem is that i don't even know where to begin so I would like to receive some hints.
I know that we obtain a cover of $f^{-1}(V)$: $f^{-1}(V)=\bigcup_{i\in I} f^{-1}(V)\cap f^{-1}(U_i)$ and we can pick Rings $A_i$ with $f^{-1}(U_i)=spec(A_i)$. And now I don't know how to continue.
Comment: You need to prove that $U:=f^{-1}(V)$ is affine. There is a criterion for a scheme to be affine (exercise II.2.17 in Hartshorne). You must solve this exercise and use it to prove that $U$ is affine.
Answer: There is a trick to solve these kinds of problem. It is called the affine communication lemma by Vakil in his note Foundations of Algebraic Geometry. For convenience, I recall statements here
Affine Communication Lemma. Let $X$ be a scheme and $U,V$ two affine open subschemes, then $U \cap V$ can be written as a union of affine open subschemes that are simultaneously principal in both $U,V$.
Setting $P$ to be being affine in $X$ in the following corollary of the above gives what you want.
Corollary. Let $P$ be some property of affine open subschemes of $X$, such that:

If an affine open $\operatorname{Spec}(A) \subset X$ has $P$, then for any $f \in A$, $\operatorname{Spec}(A_f) \subset X$ has $P$.
If $(f_1,...,f_n)=A$ and $\operatorname{Spec}(A_{f_i}) \subset X$ have $P$, then $\operatorname{Spec}(A) \subset X$ has $P$.

Suppose that $X = \bigcup_i \operatorname{Spec}(A_i)$ with each $\operatorname{Spec}(A_i)$ having $P$, then any affine open subscheme of $X$ has $P$.
Proof (of the corollary). Let $\operatorname{Spec}(A)$ be any affine open of $X$. Cover $U$ by a finitely many principal opens $\operatorname{Spec}(A_{g_i})$ such that each of them is principal in some $\operatorname{Spec}(A_i)$ (by affine communication lemma and quasi-compactness of affine schemes). By the first condition, each $\operatorname{Spec}(A_{g_i})$ has $P$, by the second condition, $\operatorname{Spec}(A)$ has $P$ too.
Thanks to the affine communication lemma, it is sufficient to prove that if $\operatorname{Spec}(A) = \bigcup_{i=1}^n \operatorname{Spec}(A_{f_i})$ and each $f^{-1}(\operatorname{Spec}(A_{f_i}))$ is affine, then $f^{-1}(\operatorname{Spec}(A))$ is affine. That is, we reduce to the case $Y= \operatorname{Spec}(A)$ is affine and have to prove $X$ is affine.
Now is the point where you should use exercise II.2.17 in Hartshorne as suggested by hm2020. For each $f \in \Gamma(X,\mathcal{O}_X)$, let
$$X_f = \left \{x \in X \mid f \neq 0 \in \mathcal{O}_{X,x}/\mathfrak{m}_x \right \}.$$
and we have to find $g_1,...,g_n \in \Gamma(X,\mathcal{O}_X)$ so that $X_{g_i}$ are affine and $(g_1,...,g_n) = \Gamma(X,\mathcal{O}_X)$. Here you can cheat a little by "pretending" that $X$ is affine to find $g_i$ from $f_i$. Comment if you cannot do this.


Why are 3 separate Arrays generating the same set of random numbers in c#

Question: I am trying to create 3 separate arrays with 7 random numbers. The problem I am running into is that when the 3 arrays are generated they all have the same set of 7 random numbers. None of them have different numbers. I am unsure on what I need to do in order for the 3 arrays to have different random numbers.
Here is the code I have so far.
static void Main(string[] args)
{
    int[] array1 = GenerateRandomArrayNumbers();
    int[] array2 = GenerateRandomArrayNumbers();
    int[] array3 = GenerateRandomArrayNumbers();

    DisplayArray(array1);
    DisplayArray(array2);
    DisplayArray(array3);
}

static void DisplayArray(int[] arr)
{
   foreach(int i in arr)
    {
        Console.Write($" {i} ");
    }
    Console.WriteLine();
}

static int[] GenerateRandomArrayNumbers()
{
    int[] RandonNumSet = new int[7];

    Random rNumber = new Random();

    for (int index = 0; index < RandonNumSet.Length; index++)
    {
        int generateNum = rNumber.Next(1, 50);
        RandonNumSet[index] = generateNum;
    }
    Array.Sort(RandonNumSet);
    return RandonNumSet;
}

Here is what it displays:
13  16  22  29  34  37  42
13  16  22  29  34  37  42
13  16  22  29  34  37  42

Thanks for any suggestions!
Answer: All of your new Random() instances share the same seed (since they're created at the same clock time).
You should either reuse a single instance or specify different seeds.
Comment: @SLaks There are _thousands_ of duplicates of this.
Comment: How would I specify different seeds?


A filed download doesn't initiate from my Android app

Question: I am currently building an Android app using HTML5. Inside my app, I am providing link to a HTML file available inside tomcat server on my machine.

Beep

The HTML file "sample.html" has link to download a file in same file location, where the sample.html is placed.
sample.html has this --> Click to download
The problem here is, when I run my app on an android mobile, the link stays dumb and it won't initiate the download from the given path.
But, the same URL when I open in a web browser, the download starts.
Could anyone let me know why this URL is not initiating the download inside my app??
I already enabled "Allow installation of non-Market applications" in the settings of my android device.
Comment: does you sample.html gets loaded in the app?
Comment: yes @PrafulBhatnagar, it gets loaded on my app. Just the download doesn't work. :(
Comment: what server are you using... have you tried setting up the mime type for apk...
Comment: the server am using is Apache Tomcat webserver.
am not sure how to "setup mime type for apk" - would this help me move on further?
Comment: check out the post in my edited answer..
Answer: Use 10.0.2.2 as IP for server running on the same machine as the Android emulator.
Check out following post with similar problem:
Download File inside WebView
Check out this link for setting up the mime type in tomcat.
Copied for reference:
In Tomcat 5.x and 4.x, the default mappings between MIME types and file extensions are stored in the file tomcat_home/conf/web.xml, where tomcat_home is the path under which Tomcat was installed on your server. The mappings specified there are applied to all web / WAP applications hosted on your Tomcat server. Application-specific mappings should be set in the WEB-INF/web.xml file under the directory of your web / WAP application.
Each mapping is specified with the <mime-mapping>, <extension> and <mime-type> tags. Here is an example:
<web-app>

...

  <mime-mapping>
    <extension>xhtml</extension>
    <mime-type>application/vnd.wap.xhtml+xml</mime-type>   </mime-mapping>

  <mime-mapping>
    <extension>wml</extension>
    <mime-type>text/vnd.wap.wml</mime-type>   </mime-mapping>

  <mime-mapping>
    <extension>wmls</extension>
    <mime-type>text/vnd.wap.wmlscript</mime-type>   </mime-mapping>

  <mime-mapping>
    <extension>wbmp</extension>
    <mime-type>image/vnd.wap.wbmp</mime-type>   </mime-mapping>

...

</web-app>

Comment: thanks for the reply Praful bhatnagar - no, this did not work :(
Comment: Praful I added mime type to the web.xml file but with no success. here is what I added -

apk
application/vnd.android.package-archive
Comment: also, the link you gave (download file inside webview) was not helpful to me as i am using only HTML5
Comment: ohh sorry i thought you were using something like phoengap that runs in webview...
Comment: I am sorry too.. I mentioned phonegap, but there also I just used HTML5. I am not aware of the other ways :(
Comment: this link excellently works on a web-browser but playing around with me, as an android app
Comment: bit confused... is it a phonegap app or web app hosted on web server... if its a phonegap app then phonegap app runs in webview so you might need `DownloadListener`..
Comment: am sorry Praful, if I confused you. I stopped working on phonegap for this, and currently executing the whole stuff on a tool called Mosync. here it's completely on HTML5 and javascript.
Comment: dont know much about Mosync.. if it creates an apk from javascript and html then there are high chances that it is getting executed in web view.. sicne native app bundled as apk can only execute html and java script in webview (unless they have created there own webview kind of UI widget).. and as i shared in my answer it looks like you have to use `DownloadListner` for downloading file from the webview....
Comment: no Praful, they do not have webview kind UI widget... I tried to understand their concept, they are just creating an apk from JS and HTML. jquery is also allowed here.
do u have any idea, how to get access to a phone's browser with code inside an app? using JS?
Is this actually possible from a native android app? if yes, i will try working out with the JS...
Comment: sorry for enforcing the same point again.. But in android you can only execute java script and html either in browser if the app is web app or in web view if the js+html is bundled as the native app (apk file)..
Comment: sorry to bother u Praful. thanks for ur help. I will see if I can do my stuff completely as a webapp..
Answer: If you are using real device you must set your url with static ip of your machine like 192.168.0.10 and in emulator 10.0.0.2
See this post.
Comment: My IP is 192.168.0.103 -I replaced this with "localhost" and still the problem is same.
Comment: What is your tool for creating app?
Comment: I used "phoneGap", "Mosync" to achieve the same but it's a failure in both tools.
Comment: I thinck you should change the path of href property in  tag to this Click to download


Multiple Jquery dialogs on page using same classes

Question: I have multiple places on my page where I want to open a jquery dialog boxes when a link is clicked. I am using class selectors so in theory I should be able to open each of them. My problem is that with the code I have it will only open the first dialog I click. Why is this???
    //modal help div
    $('.dialogbox').dialog({
                   modal:true,
                   autoOpen: false
                   });
    $(".modalhelp").click(function() {
$('.dialogbox').dialog('open')

});
The html:

Hello

NO HELLO

Answer: In your .click() handler you need to reference the one you want relatively, like this:
$(".modalhelp").click(function() {
  $(this).next('.dialogbox').dialog('open');
});

Instead of opening all .dialogbox elements, we're only calling .dialog('open') on the very next sibling
 by using .next().  If there may be elements in-between the clicked anchor and the .dialogbox then then this would change a bit, for example .nextAll('.dialogbox:first').


Why do $\omega$-models of subsystems of $\mathsf{Z}_2$ satisfy full induction?

Question: Richard Shore, in his 2010 paper in the Bulletin of Symbolic Logic, 'Reverse Mathematics: The Playground of Logic', writes that

Obviously, if an $\omega$-model $\mathcal{M}$ (those with $M = \mathbb{N}$) is a model of one of the systems above, such as $\Pi^1_1\text{-}\mathsf{CA}_0$, then it is also a model of the analogous system, such as $\Pi^1_1\text{-}\mathsf{CA}$.

Unfortunately, it is not obvious to me, although I'm sure I'll kick myself once someone explains.
Thanks in advance!
Answer: An $\omega$-model $M$ has for its first-order part the standard natural numbers from the metatheory (think: some model of ZFC containing $M$ as a set). Since the standard numbers satisfy induction for all properties definable in the metatheory, in particular they satisfy induction for all properties definable in the model $M$, because any property definable in $M$ by an $L_2(M)$ formula is definable in the metatheory by a formula of set theory with parameters.
A similar thing happens even if we start with a model $N$ of $\mathsf{ACA}_0$ which may not have satisfy the full induction scheme. If $M$ is a countable coded $\omega$-submodel of $N$, meaning it has the same numbers as $N$, then $N$ will think that $M$ satisfies full induction. This is because $M$ is coded in $N$ using a single sequence of sets, so set quantification over $M$ can be simulated by arithmetical quantification in $N$ using $M$ as a set parameter. Because $\mathsf{ACA}_0$ includes the induction scheme for arithmetical formulas with parameters, $N$ believes that $M$ satisfies full induction.
One thing to watch out for is that some people, including Shore, use $\mathbb{N}$ to refer to the set $\omega = \{0, 1, 2, \ldots\}$ from the metatheory, while others, including Simpson, use $\mathbb{N}$ to refer to the first order part of any given model of arithmetic, which may not be $\omega$.
Comment: Thanks. The two situations are completely parallel: even if $V$ is a nonstandard, non-well-founded model of set theory, if it satisfies ZFC then it will *think* of itself as well founded, and so it will think that any $\omega$-model it contains must satisfy full induction.
Comment: Thanks Carl, that clarifies things substantially. The point about countable coded $\omega$-submodels is also really interesting.


Java Graphics 2D UI Arrow Head Direction

Question: I want to draw an arrow using Graphic fillpolygon. But my arrow head is in a reverse side. Any idea?
int xpoints[] = { 20, 30, 30, 35, 25, 15, 20 };
int ypoints[] = { 10, 10, 30, 30, 45, 30, 30 };
int npoints = 7;
g2D.fillPolygon(xpoints, ypoints, npoints);

Answer: Java 2D coordinates are given in user space, in which the top-left is (0, 0). See Coordinates:

When the default transformation from user space to device space is used, the origin of user space is the upper-left corner of the component's drawing area. The x coordinate increases to the right, and the y coordinate increases downward, as shown in the following figure. The top-left corner of a window is 0,0. All coordinates are specified using integers, which is usually sufficient. However, some cases require floating point or even double precision which are also supported.

I found Java 2D - Affine Transform to invert y-axis, so I modified it to translate the origin to bottom-left, and combined it with your arrow:
protected  void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D) g;

    Insets insets = getInsets();
    // int w = getWidth() - insets.left - insets.right;
    int h = getHeight() - insets.top - insets.bottom;

    AffineTransform oldAT = g2.getTransform();
    try {
        //Move the origin to bottom-left, flip y axis
        g2.scale(1.0, -1.0);
        g2.translate(0, -h - insets.top);

        int xpoints[] = { 20, 30, 30, 35, 25, 15, 20 };
        int ypoints[] = { 10, 10, 30, 30, 45, 30, 30 };
        int npoints = 7;
        g2.fillPolygon(xpoints, ypoints, npoints);
    }
    finally {
      //restore
      g2.setTransform(oldAT);
    }
}

full source
Comment: Wouldn't it just be easier (and much faster) to change the polygon coordinates than to transform the whole canvas?
Comment: @WChargin I did explain that in Java 2D top-left is (0, 0) first. I presented an answer that makes the platform obey what OP thought was the natural representation of data, but nothing is stopping from posting your answer that does the opposite.


Retornar um botão ao seu estado original após o 'popup de download'

Question: No meu projeto Java Web há um botão de exportar uma lista para um arquivo CSV que, quando clicado, apresenta a mensagem de 'Por favor, aguarde' por alguns segundos para, em seguida, retornar ao seu estado original e permitir novas exportações.
Acontece que, em algumas circunstâncias, o processamento desse arquivo CSV pode tomar mais tempo que o timeout definido no javascript, levando o usuário a pensar que a sua solicitação não foi processada e fazendo com que muitas vezes ele clique novamente no botão de exportar, gerando um novo processamento num ciclo infernal.
Eu gostaria de saber se há alguma forma de condicionar o retorno do estado original do botão ao popup de download do arquivo CSV, de modo que o usuário não consiga fazer nova solicitação até que a atual seja efetivamente processada.
Segue abaixo o html do botão:

        <fmt:message key="relatorio.exportar" />

E o código javascript:
function exportar() {
    var msg = document.getElementById("export").innerHTML;
    document.getElementById("export").innerHTML="<fmt:message key='relatorio.exportar.aguarde'/>";

    var token = new Date().getTime();
    var t = document.forms.relatorioForm.target;
    document.forms.relatorioForm.elements['total'].value='${listTO.total}';
    document.forms.relatorioForm.elements['downloadToken'].value=token;
    document.forms.relatorioForm.action="<c:url value='/relatorio/transacao/exportar.se'/>";
    document.forms.relatorioForm.submit();
    if (!window.navigator.cookieEnabled) {
        $("#lista").hide();
        document.getElementById("export").innerHTML = msg;
    }
    document.forms.relatorioForm.action="<c:url value='/relatorio/transacao/listar.se'/>";
    document.forms.relatorioForm.target=t;
    setTimeout(function retornaBotaoExportar() {
        document.getElementById("export").innerHTML="  <fmt:message key='relatorio.transacao.exportar' />	";
    }, 8000);
}

Comment: Só um detalhe: no innerHTML do setTimeout vc está colocando outra td dentro da td original, ficando assim uma td dentro da outra com o mesmo id.
Comment: Outra coisa: o que tem no target do form?
Comment: Não tenho certeza se vc está abordando o problema da forma certa, não faz muito sentido rodar um timeout para fazer algo desse tipo, sugiro que vc abra o csv em uma outra pagina . window.open('url do csv')
Answer: Tem como tu transformar em um ajax e mudar o estado do botão no callback
function retornaBotaoExportar() {
    //Seu codigo
}
$.ajax({type:'GET',
        cache: false,
        url: rquestURL,
        data:params,
        success: function(response) {
            retornaBotaoExportar();
        });


Why had Jackie Robinson chosen number 42?

Question: Any athlete, whether child, amateur, or professional, chooses a number and tends to wear it for sentimental reasons.
Does anyone know why Jackie Robinson had chosen number 42?
Comment: I don't know. The assumption in your question is that athletes typically choose their own numbers. My assumption has always been that athletes are usually assigned numbers by their team. One of us is mistaken; it might be me.
Comment: Do rookies typically pick their own jersey numbers? I thought they get numbers assigned by the team.
Comment: Are you trying to make a point?  Did Robinson not have control over the number he wore over the duration of his career?
Comment: Some players wear a number they have chosen in Little Leagues until they retire from the bigs.  Have you never heard a story told by the announcer as to why a player wears a certain number?
Comment: I always thought stories like that were the exceptions, not the norm. But to answer your question, no, I have never played a team sport that required numbered jerseys.
Comment: The initial premise isn't necessarily true; I've coached youth teams where the numbers given are assigned randomly - kids are just given a shirt that fits them. At higher levels some players get to choose their numbers, others don't. It depends on talent, how "established" a player is, and what numbers are available on that team, as the team won't (usually) take away another player's number without his approval. Thus, the real issue that (I think) @BenMiller is raising is "Did Jackie Robinson choose to wear 42 when he played Major League Baseball or was it just a random number he was given?"
Answer: As Benjamin Hoffman explained for the New York Times baseball blog, 42 is just one of Robinson's numbers:

42 represents just his time with the Brooklyn Dodgers.
Playing football while at U.C.L.A., Robinson wore 28, but for the Bruins basketball team he switched to 18. In his time in the Negro Leagues he played for the Kansas City Monarchs and may have had as many as three different numbers, with various accounts having him wearing 5, 8 and 23. And while there seems to be some debate about his number while playing for the Montreal Royals, the Dodgers Class-AAA affiliate in 1946, a video about his time with the team produced by the CBC clearly shows him wearing 10.

As you can see, he wore many numbers over his sports career.  As far as I have been able to tell, he had never worn number 42 before he played for the Brooklyn Dodgers, and the number was probably just assigned to him by the team.


How to align a link in the middle of a paragraph?

Question: I have been struggling with adding a link with the text 'here' to flow inline with the entire paragraph.
Essentially what I would like to do is
'Gibberish here detailing the required steps.'
How can I accomplish this so as to have everything in a single line? I have tried doing this but it gives me the results attached in the screenshot.
<code>          <Flex direction="column" gap="s">
          GIBBERISHH{" "}
          <Anchor
            href=""
            trackingId=""
            label="Read the Walkthrough"
          />
          detailing the required steps.
        </Flex>
</code>

Edit: Also tried changing the Flex direction to a row but I get this result which is not what I need either. Any suggestions would be great!
Comment: the direction of the flex is `column` change it to `row` and everything will come in a line
Comment: @mrtechtroid updated my post with the row direction. I tried that as well and does not work.
Comment: How is your anchor component defined
Comment: What do you mean? @DanielA.White
Comment: Why do you have the everything wrapped in  if you want them inline ? Just wrap in a  tag or a
Comment: just overcomplicating things @WiseCode. thanks. i feel dumb right now lol
Answer: Why not a "p" tag if it's a paragraph:
<code>    <p>
          GIBBERISHH{" "}
          <Anchor
            href=""
            trackingId=""
            label="Read the Walkthrough"
          />
          detailing the required steps.
    </p>
</code>
Comment: thanks.  or a  works great!
Comment: Maybe accept his answer if it solved your problem. @TanDev


Linux Command line Help | extract specific parts from file

Question: Suppose I have a log which has data in the format given below
        Time           number status
2013-5-10 19:18:43.430 123456 success
2013-5-10 19:28:13.430 134324 fail
2013-5-10 19:58:33.430 456456 success

I want to extract the numbers having success status.
Is there any way in linux using command line(grep, sed) to extract the data as mentioned. ??
Thanks all ..
Answer: grep only solution:
grep -Po '\d+(?= success)' file

or with awk only:
awk '$4=="success"&&$0=$3' input

Answer: cat file | grep success | awk '{print $3}'

Comment: A cat? You're wearing out the keyboard and the PIDs with that extra program.
Comment: So what? Will it kill your CPU? I've given a working solution without even looking into `man`. Sure, you can achieve the same with a number of other standard tools, and even with the `awk` alone. There is always a room for improvement, everywhere, but it does not mean that the solution will be more elegant and readable.
Answer: You could do
(grep 'success' | cut -d ' ' -f 3) <$file

Answer: This prints numbers based on success status-:
 awk '$4 ~ /success/ {print $3}' logfile

Answer: Using perl:
perl -ne '/success/ && split && print "$_[2]\n"' inputfile


Nx 16 Invalid package name "@nx-cloud"

Question: I'm getting the error Invalid package name "@nx-cloud" of package "@email@example.com": name can only contain URL-friendly characters. everytime I try to install any package to my project. Is there any problem with the last version of Nx or maybe i have a wrong configuration?
Answer: The package should be nx-cloud and not @nx-cloud

Nx 16 Invalid package name "@nx-cloud"


What is the importance of non-informative prior in Bayesian Inference?

Question: By the name, noninformative prior, the prior distribution doesn't contain any information about the parameter. Then why we use this thing to estimate the parameter by the Bayesian approach?
Answer: The purpose of using a non informative prior is to utilize a more objective approach. Non-informative priors allow the data to have a greater influence on the posterior. Though, if you have enough data, your choice of prior is not really going to matter.
That said, the term non-informative can be misleading. A uniform distribution does input information into a model since it provides equal probability weight to extreme values (imagine SAT scores, a non-informative prior would say that a perfect score is just as likely as an average score on the scale).
In my own research, I have bought into McElreath's line of reasoning and use semi-informative priors. These are priors that work more to regularize results rather than input any information into a model. I find them more useful than a non-informative prior when modeling a parameter that I do not have strong prior information about.


WP Heartbeat API in Vanilla JS (addEventListener for custom events)

Question: Why following code written in jquery works great, but when I try to use it with vanilla js then it's not working.
Here is WP Heartbeat API code - https://github.com/WordPress/WordPress/blob/master/wp-includes/js/heartbeat.js
jQuery(document).ready( function($) {
  $(document).on('heartbeat-tick', function() {
    console.log('jquery');
  });
});

jQuery(document).ready( function($) {
  document.addEventListener('heartbeat-tick', function() {
    console.log('Heartbeat tick JS');
  });
});

jQuery(document).ready( function($) {
var event = new Event('heartbeat-tick');
window.addEventListener('heartbeat-tick', function() {
    console.log('Heartbeat tick JS');
});
window.dispatchEvent(event);
});

Answer: Your document event is not firing because you are dispatching the event on the window. Call document.dispatchEvent to dispatch it to the document.

jQuery(document).ready(function($) {
  var event = new Event('heartbeat-tick');

  $(document).on('heartbeat-tick', function() {
    console.log('jquery');
  });

  document.addEventListener('heartbeat-tick', function() {
    console.log('Heartbeat tick JS from document');
  });

  window.addEventListener('heartbeat-tick', function() {
    console.log('Heartbeat tick JS from window');
  });

  console.log('window');
  window.dispatchEvent(event);
  console.log('document');
  document.dispatchEvent(event);
});

Comment: Unfortunately it is still not working, console returns: window
    Heartbeat tick JS from window
    document functions.js:603:3
    jquery
    jquery
    jquery
    jquery
Comment: If it helps here is wp heartbeat api code https://github.com/WordPress/WordPress/blob/master/wp-includes/js/heartbeat.js


Existence and uniqueness of PDE with solutions in $W^{k,p}$ with $p \neq 2$?

Question: I just realised that i have never seen the space $W^{k,p}$, $p\neq 2$, used in showing existence/uniqueness to some PDE. Usually books/lectures build up theory about $W^{k,p}$ (like certain compact embeddings) spaces and then immediately show well-posedness to some PDE in the space $H^k$. Typically with Poisson's equation.
I am very curious about how to show existence to PDEs where their solutions live in $W^{k,p}$, $p \neq 2$. Obviously these spaces are not Hilbert so Lax-Milgram goes out of the window. Can someone give me a cool example or cite some book that goes through an existence proof?
Thanks
Answer: Let $\Omega\subset\mathbb{R}^N$ be a bounded domain, $p\in (1,\infty)$, $q\in (1,\infty)$, $\frac{1}{p}+\frac{1}{q}=1$, $f\in L^q(\Omega)$. Consider the problem $$\tag{1}
\left\{ \begin{array}{rl}
 -\operatorname{div}(|\nabla u|^{p-2}\nabla u)=f &\mbox{ in $\Omega$} \\
  u\in W_0^{1,p}(\Omega) &\mbox{}
       \end{array} \right.
$$
The operator $ \Delta_pu=\operatorname{div}(|\nabla u|^{p-2}\nabla u)$ is called $p$-Laplacian. We say that $u\in W_0^{1,p}(\Omega)$ is a solution (weak solution) of (1) if forall $\phi\in C_0^\infty(\Omega)$ $$\tag{2}\int_\Omega |\nabla u|^{p-2}\nabla u\nabla \phi=\int_\Omega f\phi$$
One way to solve the equation (2) is to consider the energy functional $F:W_0^{1,p}(\Omega)\rightarrow\mathbb{R}$ associated to it: $$F_p(u)=\frac{1}{p}\int_\Omega|\nabla u|^p -\int_\Omega fu$$
It is a pleasurable exercise to show that $F_p$ is a strictly convex functional and hence it must have an unique minimizer. Moreover you can show that if $u\in W_0^{1,p}$ is the minimizer, hence $$\langle F_p'(u),\phi\rangle=\int_\Omega |\nabla u|^{p-2}\nabla u\nabla \phi-\int_\Omega f\phi=0,\ \forall\ \phi\in W_0^{1,p}$$
To get a problem where the solution lies in $W^{k,p}$ with $k>1$ you need to ask more differentiability, for example, in the $p$-laplacian problem we need only that $k=1$.
Note 1: Observe that standard Dirichlet problem is included here and the same technique applies to solve this problem.
Note 2: If you ask more regularity of $f$, for example $f\in L^{r}$ with $r>\frac{N}{p}$, you can show that in fact $u\in C_{loc}^{1,\alpha}(\Omega)$ for some $\alpha\in (0,1)$.
Comment: Thanks, very informative answer. Is there a way to do it without using calculus of variations (a topic which I am not very fond of)?
Comment: I know that there is a banach space Lax-Milgram version, but i dont know if it is possible to solve this problem by using it. There are the notions of $S^+$ and pseudo-monotone operators and with it the Brezis theorem, but i think that in some way they are related with Calculus of Variations.