What is the most powerful result about the maximum of i.i.d. Gaussians? The most used in practice?

Question: Given $X_1, \ldots, X_n, \ldots \sim \mathscr{N}(0,1)$ i.i.d., consider the random variables
$$ Z_n := \max_{1 \le i \le n} X_i\,. $$

Question: What is the most "important" result about these random variables?
To clarify "importance", which result has the most other such results as a logical consequence? Which of the results is used most often in practice?

More specifically, it seems to be folklore knowledge among (theoretical) statisticians that the $Z_n$ are "basically the same as" $\sqrt{2 \log n}$, at least asymptotically. (See this related question.)
However, there are many related results of this type, and it seems to be the case that most aren't equivalent, nor imply each other. For example$^*$,
$$ \frac{Z_n}{\sqrt{2 \log n}} \overset{a.s.}{\to} 1 \,, \tag{1}$$
which if nothing else also implies the corresponding results in probability and distribution.
However, it doesn't even imply seemingly also related results (see this other question), like
$$ \lim_{n \to \infty} \frac{\mathbb{E}Z_n}{\sqrt{2 \log n}} =1 \,, \tag{2}$$
(this is exercise 2.17 on p. 49 of $\dagger$), or another folklore result:
$$ \mathbb{E}Z_n = \sqrt{2 \log n} + \Theta(1) \,. \tag{3}$$
Non-asymptotically, it is also known that for each $n$ (see here for a proof),
$$  \sqrt{c \log n} \le  \mathbb{E}Z_n \le \sqrt{2 \log n} \tag{4} $$
for some small $c$. Similar results can also be shown for $|Z_n|$, since $Z_n$ is heavily right-skewed.
The proof of this last result is much more straightforward than the proofs of the other results. My hope had been that the first asymptotic result would have implied all of the other asymptotic ones, so that I could feel confident focusing all of my time and energy in understanding that result. But, again, that seemingly is not true, so now it is unclear to me which I should focus on.
$^*$See pp. 265-267 of the second edition of Galambos, The Asymptotic Theory of Extreme Order Statistics, printed in 1987. It is probably also stated somewhere in the first edition.
$\dagger$ Boucheron, Lugosi, Massart, Concentration Inequalities: A Nonasymptotic Theory of Independence. Aside: This book actually cites Galambos for the result in question, but I can't find it mentioned anywhere in Galambos -- only the first result I mentioned.
Comment: Do you know that when you use \dots in MathJax the result sometimes appears as if you'd used \ldots and sometimes as if you'd used \cdots, depending on the context? $$ \begin{align} & \text{X_1, \dots, X_n, \dots \sim \mathscr{N}(0,1)} & & X_1, \dots, X_n, \dots \sim \mathscr{N}(0,1) \\ \\ & \text{X_1, \ldots, X_n, \ldots \sim \mathscr{N}(0,1)} & & X_1, \ldots, X_n, \ldots \sim \mathscr{N}(0,1) \end{align} $$ I replaced \dots with \ldots in this question.
Comment: @MichaelHardy Oh I thought it was always centered. Thanks for the fix!
Answer: In any probabilistic application, the most fundamental object is the distribution, with the moments and limiting properties being derivable from this.  Hence, the most "important" result, in the sense you've described, is the full distribution function $F_{Z_n}(z) = \Phi^n(z)$ (equivalently, the corresponding density function).  In practice, this distributional result is perhaps less illuminating than some of the more basic asymptotic properties you've already listed.  Although it logically implies these asymptotic results, in my view, those results are likely to be more illuminating in understanding the changing nature of the extreme value as we change $n$.
It is clear from your question that you have a good understanding of the extreme value properties in the case of a maximum of IID standard normal random variables.  These properties are all logically derivable from the distribution function for $Z_n$, so that is the most fundamental object at work in this problem.  As in many cases, the most fundamental object is not necessarily the most illuminating, and so you will probably find that you have to make do with knowing all the results, and knowing that they illuminate different aspects of the problem.
Comment: I don't have a specific reference to recommend, but I'd think these results would be derived in books on extreme value theory.  I'd suggest you start by looking for some graduate-level texts on that subject and see if you can find the derivations there.
Comment: Thanks for this answer -- I appreciate it. Do you know of a reference for how to derive all of these properties from the distribution function for $Z_n$? I've been having extreme difficulty finding anything that explains this, because it's all either "folklore" or "hand-holding".
Comment: For the record, I've read the links and they don't help. That's why I asked the question.
Answer: W.I.P.: Work in progress
Following p. 370 of Cramer's 1946 Mathematical Methods of Statistics, define $$\Xi_n = n(1 - \Phi(Z_n)) \,. $$ Here $\Phi$ is the cumulative distribution function of the standard normal distribution, $\mathscr{N}(0,1)$. As a consequence of its definition, we are guaranteed that $0\le \Xi_n \le n$ almost surely.
Consider a given realization $\omega \in \Omega$ of our sample space. Then in this sense $Z_n$ is both a function of $n$ and $\omega$, and $\Xi_n$ a function of $Z_n, n$, and $\omega$. For a fixed $\omega$, we can consider $Z_n$ a deterministic function of $n$, and $\Xi_n$ a deterministic function of $Z_n$ and $n$, thereby simplifying the problem. We aim to show results which hold for almost surely all $\omega \in \Omega$, allowing us to transfer our results from a non-deterministic analysis to the non-deterministic setting.
Following p. 374 of Cramer's 1946 Mathematical Methods of Statistics, assume for the moment (I aim to come back and supply a proof later) that we are able to show that (for any given $\omega \in \Omega$) the following asymptotic expansion holds (using integration by parts and the definition of $\Phi$):
$$ \frac{\sqrt{2\pi}}{n}\Xi_n = \frac{1}{Z_n}e^{-\frac{Z_n^2}{2}}\left( 1 + O \left( \frac{1}{Z_n^2} \right) \right) \quad ~~ as ~~ Z_n \to \infty \,. \tag{~}$$
Clearly we have that $Z_{n+1} \ge Z_n$ for any $n$, and $Z_n$ is almost surely an increasing function of $n$ as $n\to \infty$, therefore we claim in what follows throughout that for (almost surely all) fixed $\omega$: $$ Z_n \to \infty \quad \iff \quad n \to \infty \,. $$
Hence it follows that we have (where $\sim$ denotes asymptotic equivalence):
$$ \frac{\sqrt{2\pi}}{n} \Xi_n \sim \frac{1}{Z_n} e^{-\frac{1}{Z_n^2}} \quad ~~ as ~~ Z_n \to \infty \quad n \to \infty \,. $$
How we proceed in what follows amounts essentially to the method of dominant balance, and our manipulations will be formally justified by the following lemma:

Lemma: Assume that $f(n) \sim g(n)$ as $n \to \infty$, and $f(n) \to \infty$ (thus $g(n) \to \infty$). Then given any function $h$ which is formed via compositions, additions, and multiplications of logarithms and power laws (essentially any "polylog" function), we must have also that as $n \to \infty$: $$ h(f(n)) \sim h(g(n)) \,. $$ In other words, such "polylog" functions preserve asymptotic equivalence.

The truth of this lemma is a consequence of Theorem 2.1. as written here. Note also that what follows is mostly an expanded (more details) version of the answer to a similar question found here.
Taking logarithms of both sides, we get that:
$$\log ( \sqrt{2\pi} \Xi_n ) - \log n \sim -\log Z_n - \frac{Z_n^2}{2} \,. \tag{1}$$
This is where Cramer is somewhat cagey; he just says "assuming $\Xi_n$ is bounded", we can conclude blah blah blah. But showing that $\Xi_n$ is suitably bounded almost surely seems to be actually somewhat non-trivial. It seems that the proof of this may essentially be part of what's discussed on pp. 265-267 of Galambos, but I am not sure given that I am still working to understand the content of that book.
Anyway, assuming one can show that $\log \Xi_n = o(\log n)$, then it follows (since the $-Z_n^2/2$ term dominates the $-\log Z_n$ term) that:
$$ - \log n \sim - \frac{Z_n^2}{2} \quad \implies \quad Z_n  \sim \sqrt{2 \log n} \,. $$
This is somewhat nice, since it is already most of what we want to show, although again it is worthwhile to note that it is essentially only kicking the can down the road, since now we have to show some certain almost surely boundedness of $\Xi_n$. On the other hand, $\Xi_n$ has the same distribution for any maximum of i.i.d. continuous random variables, so this may be tractable.
Anyway, if $Z_n \sim \sqrt{2 \log n}$ a.s., then clearly one can also conclude that $Z_n \sim \sqrt{2 \log n}(1 + \alpha(n))$ for any $\alpha(n)$ which is $o(1)$ as $n \to \infty$. Using our lemma about polylog functions preserving asymptotic equivalence above, we can substitute this expression back into $(1)$ to get:
$$\log(\sqrt{2 \pi} \Xi _n)- \log n \sim -\log (1 + \alpha) - \frac{1}{2}\log 2 - \frac{1}{2}\log \log n - \log n - 2 \alpha \log n  - \alpha^2 \log n \,.  $$
$$ \implies -\log(\Xi_n \sqrt{2 \pi}) \sim \log(1 + \alpha) + \frac{1}{2} \log 2 + \frac{1}{2} \log \log n + 2\alpha \log n + \alpha^2 \log n \,. $$
Here we have to go even further, and assume that $\log \Xi_n = o( \log \log n) ~~ as ~~ n \to \infty$ almost surely. Again, all Cramer says is "assuming $\Xi_n$ is bounded". But since all one can say a priori about $\Xi_n$ is that $0 \le Xi_n \le n$ a.s., it hardly seems clear that one should have $\Xi_n = O(1)$ almost surely, which seems to be the substance of Cramer's claim.
But anyway, assuming one believes that, then it follows that the dominant term which does not contain $\alpha$ is $\frac{1}{2} \log \log n$. Since $\alpha = o(1)$, it follows that $\alpha^2 = o(\alpha)$, and clearly $\log ( 1 + \alpha) = o (\alpha) = o(o(\alpha \log n))$, so the dominant term containing $\alpha$ is $2 \alpha \log n$. Therefore, we can rearrange and (dividing everything by $\frac{1}{2}\log\log n$ or $2 \alpha \log n$) find that
$$ - \frac{1}{2} \log \log n \sim 2 \alpha \log n \quad \implies \quad \alpha \sim - \frac{\log \log n}{4 \log n} \,. $$
Therefore, substituting this back into the above, we get that:
$$Z_n \sim \sqrt{2 \log n}- \frac{\log\log n}{2 \sqrt{2 \log n}}  \,, $$
again, assuming we believe certain things about $\Xi_n$.
We rehash the same technique again; since $Z_n \sim \sqrt{2 \log n} - \frac{\log \log n}{2 \sqrt{2 \log n}}$, then it also follows that
$$ Z_n \sim \sqrt{2 \log n} - \frac{\log \log n}{2 \sqrt{2 \log n}} (1 + \beta(n)) = \sqrt{2 \log n} \left( 1 - \frac{\log \log n}{8 \log n}(1 + \beta(n)) \right) \,,$$
when $\beta(n)=o(1)$. Let's simplify a little before substituting directly back into (1); we get that:
$$ \log Z_n \sim  \log(\sqrt{2 \log n}) + \underbrace{\log \left(1 - \frac{\log \log n}{8 \log n}(1 + \beta(n))  \right) }_{\log(O(1)) = o(\log n)} \sim \log (\sqrt{2 \log n}) \,.$$
$$ \frac{Z_n^2}{2} \sim  \log n - \frac{1}{2} \log \log n (1 + \beta) + \underbrace{\frac{(\log \log n)^2}{8 \log n} ( 1 \beta)^2}_{o((1+ \beta) \log \log n)}  \sim \log n - \frac{1}{2} (1 + \beta) \log \log n \,. $$
Substituting this back into (1), we find that:
$$ \log ( \sqrt{2 \pi} \Xi_n) - \log n  \sim - \log(\sqrt{2 \log n}) - \log n + \frac{1}{2}(1 + \beta) \log \log n \quad \implies \quad \beta \sim \frac{\log (4 \pi \Xi_n^2)}{\log \log n} \,. $$
Therefore, we conclude that almost surely
$$Z_n \sim \sqrt{2 \log n} - \frac{\log \log n}{2 \sqrt{2 \log n}} \left(1 + \frac{\log(4 \pi) + 2 \log( \Xi_n)}{\log \log n} \right)\\ = \sqrt{2 \log n} - \frac{\log \log n + \log (4 \pi)}{ 2 \sqrt{2 \log n} } - \frac{\log (\Xi_n)}{\sqrt{2 \log n}} \,.  $$
This corresponds to the final result on p.374 of Cramer's 1946 Mathematical Methods of Statistics except that here the exact order of the error term isn't given. Apparently applying this one more term gives the exact order of the error term, but anyway it doesn't seem necessary to prove the results about the maxima of i.i.d. standard normals in which we are interested.

Given the result of the above, namely that almost surely:
$$Z_n \sim \sqrt{2 \log n} - \frac{\log \log n + \log (4 \pi)}{2 \sqrt{2 \log n}} - \frac{\log (\Xi_n)}{\sqrt{2 \log n}} \quad \implies \\ Z_n = \sqrt{2 \log n} - \frac{\log \log n + \log (4 \pi)}{2 \sqrt{2 \log n}} - \frac{\log (\Xi_n)}{\sqrt{2 \log n}} + o(1)\,. \tag{$\dagger$}$$
2. Then by linearity of expectation it follows that:
$$ \mathbb{E}Z_n = \sqrt{2 \log n} - \frac{\log \log n + \log (4 \pi)}{2 \sqrt{2 \log n}} - \frac{\mathbb{E}[\log (\Xi_n)]}{\sqrt{2 \log n}} + o(1) \quad \implies \\ \frac{\mathbb{E}Z_n}{\sqrt{2 \log n}} = 1  - \frac{\mathbb{E}[\log \Xi_n]}{2 \log n} + o(1) \,. $$
Therefore, we have shown that
$$  \lim_{n \to \infty } \frac{\mathbb{E} Z_n}{\sqrt{2 \log n}} = 1 \,,$$
as long as we can also show that
$$ \mathbb{E}[\log \Xi_n] = o(\log n) \,. $$
This might not be too difficult to show since again $\Xi_n$ has the same distribution for every continuous random variable. Thus we have the second result from above.
1. Similarly, we also have from the above that almost surely:
$$\frac{Z_n}{\sqrt{2 \log n}} = 1 - \frac{\log(\Xi_n)}{2 \log n} +o(1),.$$
Therefore, if we can show that:
$$ \log(\Xi_n) = o(\log n) \text{ almost surely}, \tag{*}$$
then we will have shown the first result from above. Result (*) would also clearly imply a fortiori that $\mathbb{E}[\log (\Xi_n)] = o(\log n)$, thereby also giving us the first result from above.
Also note that in the proof above of ($\dagger$) we needed to assume anyway that $\Xi_n = o(\log n)$ almost surely (or at least something similar), so that if we are able to show ($\dagger$) then we will most likely also have in the process needed to show $\Xi_n = o(\log n)$ almost surely, and therefore if we can prove $(\dagger)$ we will most likely be able to immediately reach all of the following conclusions.
3. However, if we have this result, then I don't understand how one would also have that $\mathbb{E}Z_n = \sqrt{2 \log n} + \Theta(1)$, since $o(1) \not= \Theta(1)$. But at the very least it would seem to be true that $$\mathbb{E}Z_n = \sqrt{2 \log n} + O(1) \,.$$

So then it seems that we can focus on answering the question of how to show that $$ \Xi_n = o(\log n) \text{ almost surely.} $$
We will also need to do the grunt work of providing a proof for (~), but to the best of my knowledge that is just calculus and involves no probability theory, although I have yet to sit down and try it yet.
First let's go through a chain of trivialities in order to rephrase the problem in a way which makes it easier to solve (note that by definition $\Xi_n \ge 0$):
$$\Xi_n = o(\log n) \quad \iff \quad \lim_{n \to \infty} \frac{\Xi_n}{\log n} = 0 \quad \iff \quad \\ \forall \varepsilon > 0, \frac{\Xi_n}{\log n} > \varepsilon \text{ only finitely many times} \quad \iff \\ \forall \varepsilon >0, \quad \Xi_n > \varepsilon \log n \text{ only finitely many times} \,.$$
One also has that:
$$\Xi_n > \varepsilon \log n \quad \iff \quad n(1 - F(Z_n)) > \varepsilon \log n \quad \iff \quad 1 - F(Z_n) > \frac{\varepsilon \log n}{n} \\ \iff \quad F(Z_n) < 1 - \frac{\varepsilon \log n}{n} \quad \iff \quad Z_n \le \inf \left\{ y: F(y) \ge 1 - \frac{\varepsilon \log n}{n}  \right\} \,. $$
Correspondingly, define for all $n$:
$$ u_n^{(\varepsilon)} = \inf \left\{ y: F(y) \ge 1 - \frac{\varepsilon \log n}{n}  \right\} \,. $$
Therefore the above steps show us that:
$$\Xi_n = o(\log n) \text{ a.s.} \quad \iff \quad \mathbb{P}(\Xi_n = o(\log n)) = 1 \quad \iff \quad \\
\mathbb{P}(\forall \varepsilon > 0 , \Xi_n > \varepsilon \log n \text{ only finitely many times}) = 1 \\
 \iff \mathbb{P}(\forall \varepsilon > 0, Z_n \le u_n^{(\varepsilon)} \text{ only finitely many times}) = 1 \\
\iff \mathbb{P}(\forall \varepsilon >0, Z_n \le u_n^{(\varepsilon)} \text{ infinitely often}) =0 \,. $$
Notice that we can write:
$$ \{ \forall \varepsilon >0, Z_n \le u_n^{(\varepsilon)} \text{ infinitely often} \}  = \bigcap_{\varepsilon > 0} \{ Z_n \le u_n^{(\varepsilon)} \text{ infinitely often} \} \,.$$
The sequences $u_n^{(\varepsilon)}$ become uniformly larger as $\varepsilon$ decreases, so we can conclude that the events $$\{ Z_n \le u_n^{(\varepsilon)} \text{ infinitely often} \}  $$ are decreasing (or at least somehow monotonic) as $\varepsilon$ goes to $0$. Therefore the probability axiom regarding monotonic sequences of events allows us to conclude that:
$$\mathbb{P}(\forall \varepsilon >0, Z_n \le u_n^{(\varepsilon)} \text{ infinitely often}) = \\
\mathbb{P} \left( \bigcap_{\varepsilon > 0} \{ Z_n \le u_n^{(\varepsilon)} \text{ infinitely often} \} \right) = \\
\mathbb{P} \left( \lim_{\varepsilon \downarrow 0} \{ Z_n \le u_n^{(\varepsilon)} \text{ infinitely often} \} \right) = \\
\lim_{\varepsilon \downarrow 0} \mathbb{P}(Z_n \le u_n^{(\varepsilon)} \text{ infinitely often}) \,.$$
Therefore it suffices to show that for all $\varepsilon >0$,
$$\mathbb{P}(Z_n \le u_n^{(\varepsilon)} \text{ infinitely often}) = 0 $$
because of course the limit of any constant sequence is the constant.
Here is somewhat of a sledgehammer result:

Theorem 4.3.1., p. 252 of Galambos, The Asymptotic Theory of Extreme Order Statistics, 2nd edition. Let $X_1, X_2, \dots$ be i.i.d. variables with common nondegenerate and continuous distribution function $F(x)$, and let $u_n$ be a nondecreasing sequence such that $n(1 - F(u_n))$ is also nondecreasing. Then, for $u_n < \sup \{ x: F(x) <1 \}$, $$\mathbb{P}(Z_n \le u_n \text{ infinitely often}) =0 \text{ or }1 $$
  according as
  $$\sum_{j=1}^{+\infty}[1 - F(u_j)]\exp(-j[1-F(u_j)]) < +\infty \text{ or }=+\infty \,. $$

The proof is technical and takes around five pages, but ultimately it turns out to be a corollary of one of the Borel-Cantelli lemmas. I may get around to trying to condense the proof to only use the part required for this analysis as well as only the assumptions which hold in the Gaussian case, which may be shorter (but maybe it isn't) and type it up here, but holding your breath is not recommended. Note that in this case $\omega(F)=+\infty$, so that condition is vacuous, and $n(1-F(n))$ is $\varepsilon \log n$ thus clearly non-decreasing.
Anyway the point being that, appealing to this theorem, if we can show that:
$$\sum_{j=1}^{+\infty}[1 - F(u_j^{(\varepsilon)})]\exp(-j[1-F(u_j^{(\varepsilon)})]) = \sum_{j=1}^{+\infty}\left[ \frac{\varepsilon \log j}{j} \right]\exp(-\varepsilon \log j) = \varepsilon \sum_{j=1}^{+\infty} \frac{ \log j}{j^{1 + \varepsilon}}  < + \infty \,. $$
Note that since logarithmic growth is slower than any power law growth for any positive power law exponent (logarithms  and exponentials are monotonicity preserving, so $\log \log n \le \alpha \log n \iff \log n \le n^{\alpha}$ and the former inequality can always be seen to hold for all $n$ large enough due to the fact that $\log n \le n$ and a change of variables), we have that:
$$ \sum_{j=1}^{+\infty} \frac{\log j}{j^{1 + \varepsilon}} \le \sum_{j=1}^{+\infty} \frac{j^{\varepsilon/2}}{j^{1 + \varepsilon}} = \sum_{j=1}^{+\infty} \frac{1}{j^{1 + \varepsilon/2}} < +\infty \,,$$
since the p-series is known to converge for all $p>1$, and $\varepsilon >0$ of course implies $1 + \varepsilon/2 > 1$.
Thus using the above theorem we have shown that for all $\varepsilon >0$, $\mathbb{P}(Z_n \le u_n^{(\varepsilon)} \text{ i.o.}) = 0$, which to recapitulate should mean that $\Xi_n = o(\log n)$ almost surely.
We need to show still that $\log \Xi_n = o(\log \log n)$. This doesn't follow from the above, since, e.g.,
$$ \frac{1}{n} \log n = o(\log n) \,, - \log n + \log \log n \not= o(\log n) \,.  $$
However, given a sequence $x_n$, if one can show that $x_n = o( (\log n)^{\delta})$ for arbitrary $\delta >0$, then it does follow that $\log(x_n) = o(\log \log n)$. Ideally I would like to be able to show this for $\Xi_n$ using the above lemma (assuming it's even true), but am not able to (as of yet).


Using "this" within a method

Question: Can I use this in the method, or is it wrong?
Fields:
private int level;
private String name;

Methods
public void check(String Name, int newlevel)
{
       if (this.level < newlevel )
       {
           this.level = newslevel;
           this.Name = Name;

           System.out.println("." Name+" you are in the right level);
       }
       else
       {
           System.out.println("Sorry your are not on the right level" );
       }
}

Answer: Yes. You can do this. It's often used in setters:
public void setX(int x) {
   this.x = x;
}

In the above, if you omit the this, you're simply setting the parameter x to itself - not what you want! For this reason, the keyword final is often used:
public void setX(final int x) {
   this.x = x;
}

In the above, if you omit the this, then the compiler will complain that you're setting x to itself.
Answer:
can I use this in the method

this is mostly used in methods, just as you are using it. It refers to the the object on which the method is called, this implies that it cannot be used in static methods
Answer: yes, its absolutely fine .this is usually used to refer to the current object. we use this to diffrentiate between the instance variables and local variables.
 private name;
 public void m1(String name){
 this.name=name;
 }

Comment: is it okay to leave the parameter as newLevel OR do i have to change it to level
Comment: you can leave it as newLevel, if you change it to level then you should definitely use this.level(instance variable)= level(local variable)
Comment: you are welcome, please accept the most appropriate answer if you are happy with one :)

Using "this" within a method


ActiveMQ Artemis: Message draining without HA policy "scale-down"

Question: In an ActiveMQ Artemis HA cluster (v2.13.0), the HA policy's <scale-down/> property causes the backup broker to move all pending messages to one of the remaining live instances if the master instance fails. Once drained, the slave broker stops itself and waits for the master instance to go live again. This behavior effectively reduces the number of broker pairs in a cluster, even if just one master broker fails. Right?
When the <scale-down/> property is not set, the slave broker becomes live on master failure, and the number of live brokers in a cluster does not change. However, I am wondering if a live backup instance still moves pending messages to other brokers if shutdown intentionally (i.e., SIGTERM). This behavior would preserve all messages in case of intentional broker shutdown while keeping the number of live brokers in case of failures.
Answer:
This behavior effectively reduces the number of broker pairs in a cluster, even if just one master broker fails. Right?

That's correct.

When the  property is not set, the slave broker becomes live on master failure, and the number of live brokers in a cluster does not change.

That's also correct.

However, I am wondering if a live backup instance still moves pending messages to other brokers if shutdown intentionally (i.e., SIGTERM).

If scale-down is not configured then no messages will be moved.
The scale-down functionality was really designed for cloud use-cases where live-only clusters would grow and shrink based on demand. When the cluster shrinks the broker that's going away needs a way to preserve its messages so it dumps them to another broker in the cluster. Furthermore, cloud infrastructure typically makes HA configuration moot due to the management and redundancy provided by the cloud itself. For example, if a node fails then the cloud infrastructure can simply restart it. In this case the broker can simply re-attach to whatever storage it was using before and all the durable messages which were there before the crash (or whatever) will still be there.
In my opinion, while it is technically possible to use scale-down in an HA configuration with a live and a backup I don't think it makes much sense to do so since the live and backup already share message data (either via shared-storage or replication).
Finally, it's worth noting that scale-down can be performed administratively using the ActiveMQServerControl MBean.
Comment: Thanks for your explanation, much appreciated. What I'm trying to address is really both use-cases, scaling _and_ high availability. While it is true that for cloud environments the general availability is high, I have seen numerous node failures in different setups (e.g., kernel panics, admin errors, JVM kills due to out-of-memory, etc.) that I would like to address for a use-case where message loss is not acceptable.
Is there a manual way to initiate message draining which can be triggered as a pre-stop hook?
Comment: I don't see why any of the conditions you listed would necessarily lead to message loss with or without HA. Typically in a cloud environment if a node fails then the cloud infrastructure will simply restart it. In this case the broker can simply re-attach to whatever storage it was using before and all the durable messages which were there before the crash (or whatever) will still be there.
Comment: I updated my answer to provide additional clarity. Hope that helps!


Remove blank space from string copy and paste

Question: I'm trying to get a Copy and Paste to work
It copies the string successfully but when I paste that into notepad for example but it inserts blank space before and after the string.
Process:

Copy: string
Paste Result in Notepad: <blank space>String<blank space>
Ideal Result wanted: string

I was wondering if a String trim() could be used?

$(document).ready(function() {
  $('button').click(function() {
    var btntxt = $(this).text();

    var copy = $(this).parent().find('.copy').text();

    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val(copy).select();
    document.execCommand("copy");
    $temp.remove();

    $('.confirmation').hide().html('Copied ' + btntxt + ' code to clipboard').fadeIn(100).delay(800).fadeOut(200);

    $('.main').trigger("click");
  });

  $('.main div').click(function() {
    var range = document.createRange();
    var selection = window.getSelection();
    range.selectNodeContents(this);
    selection.removeAllRanges();
    selection.addRange(range);
  });
});

      string to be copied

    <button>

      TMPL
    </button>

      string to be copied

    <button>

      Mason
    </button>

   Copied to clipboard

Any help would be appreciated, thank you
Answer: Like you wrote "I was wondering if a String trim() could be used?"
Yes you could use it:
var copy = $(this).parent().find('.copy').text().trim();

Working example:

$(document).ready(function() {
  $('button').click(function() {
    var btntxt = $(this).text();
    var copy = $(this).parent().find('.copy').text().trim();
    var $temp = $("<input>");

    $("body").append($temp);
    $temp.val(copy).select();
    document.execCommand("copy");
    $temp.remove();

    $('.confirmation').hide().html('Copied ' + btntxt + ' code to clipboard').fadeIn(100).delay(800).fadeOut(200);

    $('.main').trigger("click");
  });

  $('.main div').click(function() {
    var range = document.createRange();
    var selection = window.getSelection();

    range.selectNodeContents(this);
    selection.removeAllRanges();
    selection.addRange(range);
  });
});

      string to be copied

    <button>

      TMPL
    </button>

      string to be copied

    <button>

      Mason
    </button>

   Copied to clipboard

Or you could change your HTML, so that there are no line breaks:
string to be copied

Working example:

$(document).ready(function() {
  $('button').click(function() {
    var btntxt = $(this).text();
    var copy = $(this).parent().find('.copy').text();
    var $temp = $("<input>");

    $("body").append($temp);
    $temp.val(copy).select();
    document.execCommand("copy");
    $temp.remove();

    $('.confirmation').hide().html('Copied ' + btntxt + ' code to clipboard').fadeIn(100).delay(800).fadeOut(200);

    $('.main').trigger("click");
  });

  $('.main div').click(function() {
    var range = document.createRange();
    var selection = window.getSelection();

    range.selectNodeContents(this);
    selection.removeAllRanges();
    selection.addRange(range);
  });
});

    string to be copied

    <button>

      TMPL
    </button>

    string to be copied

    <button>

      Mason
    </button>

   Copied to clipboard

Comment: Thank you so much, that's done it,  as I'm still learning I wasn't sure where to place this.


Filter dataset based on values existing in another data frame

Question: I have simplified the two datafrfames:
a = data.frame(ID = c("1", "2", "3", "4", "5"))
b = data.frame(ID = c("1", "1", "6", "7", "8", "8", "3"))

How do I filter data frame b with the matching values in a so only the values of 1:5 will remain in b? So only 1, 1, and 3 will remain in b?
Comment: Try `b[b$ID %in% a$ID, , drop = FALSE]`
Answer: This can be solved using merge or an inner join. Here are different approaches:
Base R
merge(a, b)

  ID
1  1
2  1
3  3

dplyr
library(dplyr)
inner_join(a, b)

data.table
library(data.table)
setDT(a)[setDT(b), on = "ID", nomatch = 0L]

Comment: Why post an answer to an obvious duplicate post?


For every closed set $F$ in a completely regular space $X,$ does there exist a nonzero continuous function $f:X\to [0,1]$ such that $f=0$ outside $F?$

Question: Let $X$ be a completely regular space, that is, for every closed set $F\subseteq X$ and $x\not\in F,$ there exists a continuous function $g:X\to [0,1]$ such that $g(F) = \{0\}$ and $g(x) =1.$

Question: For every closed set $F\subseteq X,$ does there exist a nonzero continuous function $f:X\to [0,1]$ such that $f=0$ outside $F?$
Answer: Not true even in the real line. If $F$ is a singleton set then any continuous function vanishing outside $\{x\}$ is identically $0$.


Verifying that $e^t$ is a solution to $(2t − t^2)y''+ (t^2-2)y'+2(1-t)y=0$, then deriving the general solution.

Question: Verify that $e^t$ is a solution of the differential equation
$$(2t − t^2)y''+ (t^2-2)y'+2(1-t)y=0.$$
Use this solution to find the general solution.
Comment: Plug in $c(t)e^t $ then solve the equation to get the parameter c(t)...
Comment: Welcome to Math.SE! What have you tried so far?
Comment: i have tried a series solution using y=∑CmX^(m+r), and reduction of order, none of which have worked for me
Comment: Why not just plug in $e^t$ for $y$, and check that it works?
Comment: that would work, but the general solution is also needed
Comment: The method here is called "reduction of order."  If you know one solution, then you can get another, linearly independent solution by following Isham's advice above.
Answer: $$(2t-t^2)y''+(t^2-2)y'+2(1-t)y=0$$
First verify that $e^t$ is a solution:
$$(2t-t^2)e^t+(t^2-2)e^t+2(1-t)e^t=(2t-t^2+t^2-2+2-2t)e^t=0e^t=0$$
Also note that based on the format of the equation, there is likely a power function that works. So try $y=t^n$.
$$n(n-1)(2t-t^2)t^{n-2}+n(t^2-2)t^{n-1}+2(1-t)t^n=0$$
$$\implies(n-2)t^{n+1}-(n^2-n-2)t^n+(2n^2-4n)t^{n-1}=0$$
$$\implies(n-2)(t^{n+1}-(n+1)t^n+2nt^{n-1})=0$$
$$\implies n=2$$
So $y=t^2$ is a solution. Since any multiple of a solution of this DE is another solution, all linear combinations work.
Note that we could also find the $y=t^2$ solution by simply noticing $2t-t^2+t(t^2-2)=t^3-t^2=t^2(1-t)$, which gives it away.
Answer:
$$y=Ae^t+Bt^2$$
Answer: It is easy to verify that $y_1(t)=e^t$ is a solution to your differential equation, just by substituting it into your ODE, as shown in @RomanChokler's answer.

Since we know one solution, and we are trying to find a second linearly independent one, it is ideal to use reduction of order. We will assume the other solution to be of the form $y_2(t)=v(t)y_1(t)$, where $v(t)$ is an unknown function to be determined. Hence, in our case, we will substitute $y_2(t)=v(t)e^t$ into our ODE.
$$(2t-t^2)\color{green}{y''}+(t^2-2)\color{#000090}{y'}+2(1-t)\color{#aa0000}{y}=0 \tag{1}$$
$$(2t-t^2)\color{green}{(e^t\cdot v''+2e^t\cdot v'+e^t\cdot v)}+(t^2-2)\color{#000090}{(e^t\cdot v'+e^t\cdot v)}+2(1-t)\color{#aa0000}{(e^t\cdot v)}=0$$
Gathering derivatives of $v$ and simplifying, we see that we must solve the following second order differential equation:
$$t(2-t)v''+(-t^2+4t-2)v'=0 \tag{2}$$
Solving the above is not difficult: notice that the term involving the $v$ has dropped out. Thus, it is evident that we can reduce the order of $(2)$ with the change of variable $w=v'$, giving a separable differential equation:
$$w'=\frac{-t^2+4t-2}{t(t-2)}w \tag{3}$$
Using the fact that $\dfrac{-t^2+4t-2}{t(t-2)}=\dfrac{1}{t}+\dfrac{1}{t-2}-1$, it can be shown with ease that the solution to $(3)$ is:
$$w(t)=\frac{c_1 t(t-2)}{e^t}$$
Now recall our change of variable, and integrate both sides with respect to $t$. We obtain the following solution via integration by parts:
$$v(t)=\frac{k_1 t^2}{e^t}+k_2 \tag{4}$$
Where $k_1:=-c_1$. Since we now have $v(t)$, we conclude that the second linearly independent solution is $y_2(t)=t^2$.
Answer: The differential equation is given by
$$y''(t)-\frac{t^2-2}{t(t-2)}\,y'(t)+\frac{2(t-1)}{t(t-2)}\,y(t)=0\,.$$
Observe that this is the same as
$$\big(y''(t)-y'(t)\big)-\frac{2(t-1)}{t(t-2)}\,\big(y'(t)-y(t)\big)=0\,.$$
Consequently,
$$\frac{\text{d}}{\text{d}t}\,\left(\frac{y'(t)-y(t)}{t(t-2)}\right)=0\,,\text{ or }y'(t)-y(t)=a\,t(t-2)\,,$$
for some constant $a$.  Ergo,
$$\frac{\text{d}}{\text{d}t}\,\big(\exp(-t)\,y(t)\big)=-a\,t(t-2)\,\exp(-t)\,,\text{ whence }y(t)=\exp(t)\,\int\,\big(-a\,t(t-2)\,\exp(-t)\big)\,\text{d}t\,.$$
Hence, for some constant $b$,
$$y(t)=\exp(t)\,\big(a\,t^2\,\exp(-t)+b\big)=a\,t^2+b\,\exp(t)\,.$$


If Var is certain Value omit the WHERE

Question: Is it possible to omit the WHERE if a variable is a certain value? The following doesn't work and I am struggling to find an answer;
DECLARE @rMonth int, @rYear int, @sID int
SET @rMonth  = 0;
SET @rYear = 0;
SET @sID= 0;

SELECT
    TCS.bStatus AS jStatus, TCS.ID, TCS.sID, TCS.insDate, TCS.statusLabel, TCS.cID
FROM
    TCS
    CASE WHEN @rMonth > 0 THEN
        WHERE month(insDate) = @rMonth AND year(insDate)  = @rYear
END

Comment: If you have a large table and care about performance, you should ask another question.  The structure of your `where` (and the `where` statements in the answers) prevents the use of indexes.
Answer: WHERE
  (@rMonth <= 0)
  OR
  (month(insDate) = @rMonth AND year(insDate) = @rYear)

Comment: Thank you @GSerg. please read my comment in the above answer. I need to retrieve all records When rMonth = 0.
Comment: This will retrieve all records when rMonth = 0.
Answer: This is common scenario to include a clause conditionally
check this out:
WHERE
     (@rMonth = 0  OR MONTH(insDate) = @rMonth)
AND  (@rYear = 0 OR YEAR(insDate) = @rYear)
AND  (@sID = 0 OR sID = @sID)

In above query and for each clause, right hand side of "OR" is applied only if left hand side is false.   Otherwise whole clause is considered as true and does not filter any row.
Hopefully,by using above trick any complex clause could be written in right side of "OR" rather than a simple equality comparision.
Comment: @JohnSaunders You are right, passing those parameters as NULL sounds more standard. But he tries to consider 0 as Nothing, so thats his choice :)
Comment: Interesting. I usually see that done with NULL, like `WHERE (@rMonth IS NULL OR MONTH(insDate) = @rMonth)`
Answer: Another two options to achieve the same result:
one - using CASE statement like you wanted initially:
WHERE MONTH(insDate) = CASE WHEN @rMonth > 0 THEN @rMonth ELSE MONTH(insDate) END
AND YEAR(insDate) = CASE WHEN @rYear > 0 THEN @rYear ELSE YEAR(insDate) END
AND sID = CASE WHEN @sID > 0 THEN @sID ELSE sID END

and another - using ISNULL and NULLIF functions:
WHERE MONTH(insDate) = ISNULL(NULLIF(@rMonth, 0), MONTH(insDate))
AND YEAR(insDate) = ISNULL(NULLIF(@rYear, 0), YEAR(insDate))
AND sID = ISNULL(NULLIF(@sID, 0), sID)

If Var is certain Value omit the WHERE


How to use SELECT in function to compare fields

Question: There are 3 tables: Event, Booking, and Booking_Day.
The idea is that one can book separate days of the event.
I would like to put a constraint on Booking_Day so that Day has to be within Date_Start and Date_End range of the corresponding Event. I decided to use a function that will do this
create table Event
(
  Event_ID   int identity
    constraint Event_pk
      primary key nonclustered,
  Date_Start date not null,
  Date_End   date
)

create table Booking
(
  Booking_ID int identity
    constraint Booking_pk
      primary key nonclustered,
  Event_ID   int not null
    constraint Booking_Event_Event_ID_fk
      references Event
)

create table Booking_Day
(
  Day        date not null,
  Booking_ID int  not null
    constraint Booking_Day_Booking_Booking_ID_fk
      references Booking,
  constraint Booking_Day_pk
    primary key nonclustered (Day, Booking_ID)
)

And the function:
CREATE FUNCTION check_if_in_range (
    @Event_id int,
    @Day DATE
) RETURNS int
BEGIN
    declare @result TABLE  (Day DATE,Booking_ID INT,Event_ID INT,Date_start DATE, Data_end DATE)

    INSERT into @result

    SELECT Booking_Day.Day, Booking.Event_ID, Event.Date_Start, Event.Date_End

    FROM ((Booking_Day INNER JOIN Booking on Booking_Day.Booking_ID = B.Booking_ID )
    INNER JOIN Event on Event.Event_ID = Booking.Event_ID) WHERE Booking_Day.Day = @Day AND B.Event_ID = @Event_id

    return ((@Day >= @result.Date_start) AND (@Day <= @result.Data_end))

END

Because of the primary key constraint on Booking_day table, the above should return only one row.
When trying to add function do database I get "[[S0001][137] Must declare the scalar variable "@result".
How do I deal with it? Is my approach entirely wrong and I don't need a table within the function for this?
Answer: I don't understand why you would be using a table variable for this.  You cannot just refer to a table unless you specify a FROM clause -- you are confusing table variables and scalar variables.
But why bother with variables at all?
IF (EXISTS (SELECT 1
            FROM Booking_Day bd INNER JOIN
                 Booking b
                 ON bd.Booking_ID = B.Booking_ID INNER JOIN
                 Event e
                 ON e.Event_ID = b.Event_ID
           WHERE b.Day = @Day AND
                 b.Event_ID = @Event_id AND
                 @Day >= e.Date_Start AND
                 @Day <= e.Data_end
          )
        )
BEGIN
    return 1
END;
return 0


Apache serving content via smb

Question: So basically, I want to host a network smb share on my Redhat 6.2 Apache httpd server.  My basic configuration is outlined below, however, I keep getting errors.
So my basic configuration
/mnt/ShareDocs -> network \\smb\share

/etc/fstab
//smb/shared /mnt/ShareDocs cifs defaults,wsize=65535,file_mode=0777,dir_mode=0777,sec=ntlm,credentials=/root/.creds 0 0
Apache 2.2 (httpd.conf)
<Directory "/var/www/help">
  Options Indexes FollowSymLinks
  AllowOverride None
  Order allow,deny
  Allow from all
</Directory>

Alias /help /var/www/help

tail -f error_log gives me -> Symbolic link not allowed or link target not accessible: /var/www/help
So I take the symbolic link out of the equation, and go directly at the mount point.  I change my directory to ...
<Directory "/mnt/ShareDocs"> ...

I then get a different error message that says..
[error] [client ip] (13)Permission denied: access to /help/Manual.pdf denied
Does anyone have any ideas?
Comment: What distro is this ?
Comment: @Iain I noticed that I didn't supply that piece of information, I just updated my question.
Comment: Is SELinux enabled ?
Comment: @Iain yes  >sestatus --> SELinux status: enabled
Answer: Your problem will quit likely be due be due to SELinux.
First set SELinux into permissive mode
setenforce 0

and then test your setup. If it now works then SELinux is proved to be the culprit.
You can use the tools available to figure out what needs changing.
grep denied /var/log/audit/audit.log | audit2why

or look at
grep denied /var/log/audit/audit.log | audit2allow

and take appropriate action.
Don't forget to set SELinux back to enforcing
setenforce 1

Disabling SELinux isn't a good solution.

Apache serving content via smb


Autorização em class libraries

Question: Dúvida
Estou com um projeto em que toda a regra de negócio está encapsulada em um conjunto de DLL's com arquitetura em 3 camadas.
Gostaria de saber, qual é a melhor abordagem para o controle de autorização nestas dll's. É possível utilizar o Identity? Existe algum design pattern ou alguma outra abordagem mais indicada para solucionar este problema?
Levando em consideração que um usuário pode ter um perfil com acesso a determinadas funcionalidades (métodos ou classes).
Inicialmente, implementei uma tabela de funcionalidades e uma tabela de perfil que contem estas funcionalidades. Na aplicação, um Attribute acima de métodos ou de classes indica qual funcionalidade pode acessar o código.
Para verificar se o usuário pode acessar o código, é verificado se o perfil deste tem a funcionalidade descrita no Attribute. Contudo, não tenho certeza de que esta forma é a mais elegante para a situação.
Arquitetura
A arquitetura da solução está implementada de acordo com a arquitetura Onion. A camada Service encapsula toda a regra de negócio do sistema e tem acesso ao Domain e aos Repositorios.
O projeto Web (MVC) e Web Api possuem acesso a DLL Services, e o controle de acesso entra neste momento. Para evitar que estes e os demais projetos externos que queiram acessar os Services implementem cada um seus controles de autorização, foi criado um controle de acesso conforme descrito abaixo.
Código atual
AttributeUsage(AttributeTargets.Method)]
public class ControleAcessoAttribute : Attribute
{
    private string[] funcionalidades;
    private UsuarioAutenticado usuario;

    public ControleAcessoAttribute(params string[] funcionalidades)
    {
        this.funcionalidades = funcionalidades;
        this.usuario = UsuarioAutenticado.GetInstance();
        VerificarAcesso();
    }

    public void VerificarAcesso()
    {
        var isAutorizado = VerificarFuncionalidades();
        if(!isAutorizado)
        {
            throw new NegocioException("O usuário autenticado não possui permissão para acessar esta funcionalidade.");
        }
    }

    public bool VerificarFuncionalidades()
    {
        foreach (var item in usuario.Perfil.Funcoes)
        {
            for (int i = 0; i < funcionalidades.Length; i++)
            {
                if(item.Descricao.Contains(funcionalidades[i]))
                    return true;
            }
        }
        return false;
    }

Método de utilização
public class Foo
{
      [ControleAcesso("Bar","Foo")]
      public void Bar()
      {
           //Some code here
      }
}

Um outro problema
Um outro problema que estou enfrentando é em saber qual é o usuário autenticado nas aplicações, uma vez que o projeto web pode implementar Session e outros não. Esta autenticação deveria ser responsabilidade da DLL? O mais correto seria guardar a autenticação no banco de dados?
Comment: Vinícius, vou reabrir sua pergunta por considerar que há a possibilidade de obter uma boa resposta. Porém sugiro ainda que edite a questão colocando algum trecho de código que exemplifique sua abordagem. Abraço!
Comment: Irei editar a pergunta com o código existente hoje e a arquitetura utilizada nas DLL's!
Answer: Gostaria de saber, qual é a melhor abordagem para o controle de autorização nestas dll's. É possível utilizar o Identity?
É possível, mas o Identity foi pensado para a arquitetura MVC, inicialmente. Funcionará bem se o fluxo da sua camada de serviços for parecido com um Controller.
Existe algum design pattern ou alguma outra abordagem mais indicada para solucionar este problema?
Depende do que você precisa. Aproveitando o gancho da sua implementação por Attribute passando funcionalidades por parâmetro, a aproximação é correta, mas tenho algumas observações:
Strings são mais propensas a problemas em algum momento (principalmente os problemas de digitação). Ao invés de usar:
[ControleAcesso("Bar","Foo")]

Crie um Enum de funcionalidade:
public enum Funcionalidade {
    Foo, Bar
}

Passe eles como parâmetro:
[ControleAcesso(Funcionalidade.Bar, Funcionalidade.Foo)]

VerificarFuncionalidades poderá ser simplificado e ficará mais eficiente e mais seguro em termos de código.
Sobre Sessions, você terá que escrever um controle próprio de sessões, visto que você não está usando solução pronta de alguma arquitetura conhecida.
Sobre onde guardar estes dados, acho que é uma parte opinativa da questão. Por balanceamento de carga, prefiro manter no banco de dados ou usando alguma cache chave-valor, como o Redis, por exemplo.
Comment: @Vinícius Mais segura, eu diria. Que fique grande. Melhor assim do que algo propenso a erro.
Comment: Irei incrementar a pergunta então com o código que tenho hoje
Comment: @Vinícius Atualizei a resposta.
Comment: inicialmente estava com enum mas este estava muito grande. O enum estava enumerando as chaves das funcões cadastradas no banco de dados. Você acha essa abordagem correta?

Autorização em class libraries


htaccess rewrite rule - no extension and slash

Question: I am not familiar with .htaccess file so excuse me if my question is a little absurd.
When I request for
localhost/mydomain/blog.php

I want to have a url of this form:
localhost/mydomain/blog/

My website directory looks like that:

The .htaccess file includes the following:
Remove .php extension
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]
</IfModule>

With this link
Blog

The url is:
localhost/createforweb_1.1/blog

But I want to add a trailing slash, so if I add these lines in htaccess:
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://localhost/createforweb_1.1/$1/ [L,R=301]

I get this error:
The requested URL /blog/.php was not found on this server.

I'm sure is very simple but I have a little experience in .htaccess rewrite!
LATEST .htaccess file (whole file)
<IfModule mod_rewrite.c>
 Options +FollowSymlinks
# Options +SymLinksIfOwnerMatch
 RewriteEngine On
# RewriteBase /
</IfModule>

Options -MultiViews

## Adding a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [L]

ALTERNATIVE SOLUTION
I just created a folder for every page, moved the files inside and renamed them into index.php. The new directory tree looks like that:

Now I request blog folder and blog/index.php is loading. URL becomes createforweb.gr/blog/
Is this an acceptable solution, or it will create problems in the future?
Answer: Put this code in your .htaccess under DOCUMENT_ROOT directory:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## Adding a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [L]

Comment: Thank you abubhava! Although blog.php exists in the website directory, I now get the following error message: "The requested URL /blog.php was not found on this server."
Comment: THat is most likely because of the other trailing slash rule. Let me suggest you something for that as well.
Comment: Still the same error! I have tried many combinations but I don't know what exactly I am doing..
Comment: Post your latest .htaccess in your question. Also I didn't get what is `createforweb_1.1`? Is hat your DOCUMENT_ROOT?
Comment: I have edited my question with the new .htaccess. createforweb_1.1 is my DOCUMENT_ROOT. Thanks again!
Comment: Ok and now the error you're getting is `The requested URL /blog.php was not found on this server.` **INSTEAD OF** `The requested URL /blog/.php was not found on this server.` right?
Comment: Sorry for late reply. I just deployed above code on my webserver and everything worked fine. `/blog` became `/blog/` and internally it loaded `/blog.php`. Can't guess what is causing problem for you. Make sure above .htaccess is in right under createforweb_1.1 and you have `Options +FollowSymLinks -MultiViews` and `RewriteEngine On` lines at the top.
Comment: .htaccess is right under createforweb_1.1 folder and the .htaccess file looks like the one I edited again. The same error occurs! How can not be able to load the existing blog.php file?
Comment: Hmm as you can see the erro you;re getting that `/blog.php` not found for a URI in your browser `/blog` which is becoming `/blog/` first in the browser. All that means that rules are working fine because it is trying to load `/blog.php` correctly. Can you directly enter `/blog.php` in the browser and see what you get.
Comment: When I enter "http://localhost/createforweb_1.1/blog.php" it gets the right page (of course the url remains /blog.php)
Comment: Ah you have `/createforweb_1.1/` in your URL. That means it is NOT DOCUMENTR_ROOT. I have asked this specifically and you wrote that it is root :)
Comment: Make sure my edited .htaccess is 1 level above `createforweb_1.1` which is your `$DOCUMENTR_ROOT` and then enter this URL in browser: `http://localhost/createforweb_1.1/blog`
Comment: I thought .htaccess file should be at the same level as index.php. I uploaded the files here "http://createforweb.gr" and it does not load css files and then creates an infinite loop!
Comment: Does `http://localhost/createforweb_1.1/blog` load `blog.php` or it still throws 404? Once that is resolved we'll resolve css problems easily.
Comment: http://localhost/createforweb_1.1/blog still throws the following error: "The requested URL /blog.php was not found on this server." I use the .htaccess file from HTML5-boilerplate (http://html5boilerplate.com/), so the .htaccess file contains other rules too. I don't know if something else affects what we are trying to do.
Comment: As much as I want to help you I think it won't be possible without looking directly at your server. If you can provide me a temporary access to your server pls write an email to: anubhavas[at]gmail[dot]com
Comment: I just came up with a solution (check "createforweb.gr"). I edited my question. Is this a correct approach?
Comment: If you have only handful of php files to manage then this is an acceptable work around. However if you can have lots of php files in future then it will be same # of directories plus same # of index.php files inside them which will create some clutter for you to manage.


Executar método quando inicializar a classe

Question: Tenho uma classe chamada ligacao e quando inicializo ela(dentro de um botão) quero que outro método que está dentro dessa classe( que é iniciado em uma terceira classe) reexecute e mude de ObservableList.
Classe ligacao (o boolean b é que muda o ObservableList):
class ligacao {
    protected static boolean b;
    public licacao(boolean b){
        this.b = b;
    }
    static FilteredList<Person> filtrar;
    public static FilteredList get(ObservableList<Person> obs, ObservableList<Person> obs2){
        filtrar = new FilteredList<>(obs, p -> true);
        if(b == true){
            filtrar.removeAll(obls);
            filtrar = new FilteredList<>(obs2, p -> true);
        }else{
            filtrar.removeAll(obs2);
            filtrar = new FilteredList<>(obs, p -> true);
        }
        return filtrar;
    }
}

Classe em que a classe ligacao é inicializada:
    carne.setOnAction((Carne) -> {
        try {
            boolean b = false;
            System.out.println(b);

            if(carne.getText().endsWith("Carnê")){
                carne.setText("Tabela");
                System.out.println(b);
                b = true;
                System.out.println(b);
            }else{
                carne.setText("Carnê");
                System.out.println(b);
                b = false;
                System.out.println(b);
            }
            System.out.println(b);
            new ligacao(b);
            System.out.println(b + "\n");
        } catch (Exception e) {
            e.printStackTrace();
        }

    });

(terceira classe) Onde inicializa o método get da classe ligacao:
FilteredList<Person> filtrar = ligacao.get(obs(), obs2());

O problema que que não muda o método get.
O que faço?
Comment: @EduardoFernandes Não existe nenhuma regra que proíba um construtor acessar uma variável estática. É verdade que isso não é lá uma boa prática de programação, mas o compilador e a JVM aceitam isso normalmente.
Comment: @VictorStafusa O meu comentário não se referia a isso. Na altura o campo `b` **não** estava declarado como estático e era acedido no método estático `get`.
Comment: É possível em JAVA um método *static* usar um atributo não *static*? Para isso ser possível, estou a pensar em C#, seria declarar `b` como `public static boolean b;`
Comment: Estava assim é que eu acabei apagando.
Comment: Acredito que esse seu código não compile. Um construtor não pode acessar uma variável estática. Além disso ele está com o nome errado.
Comment: Me desculpe por ter colocado o código faltando algumas partes, mas o código compila.
Comment: Haha verdade, permite mesmo :)
Comment: @ramaral o `this.b = b;` compila sim, pois é permitido acessar um campo estático usando uma variável ao invés do nome da classe (no caso, a variável é o `this`). Entretanto, isso é uma péssima prática de programação e não deveria ser feito nunca, mas a linguagem permite sim.
Answer: Vamos ver a sua primeira classe:
class ligacao {
   // ...
   public licacao(boolean b){
   // ...

Aqui temos um erro de compilação, pois o nome do construtor deveria ser ligacao, e não licacao. Além disso, a convenção de nomes dita que nomes de classes iniciam com letras maiúsculas, e desobedecer essa conveção não é uma boa ideia.
Um pouco mais abaixo:
filtrar.removeAll(obls);

Não há nenhuma variável obls. Acho que você quis dizer obs.
Também neste método:
if(b == true){

Por favor, NUNCA compare uma expressão ou variável booleana com == true ou == false. Isso é uma má prática de programação. Ao invés disso, use simplesmente assim:
if (b) {

E se quisesse comparar com false, bastaria usar isso:
if (!b) {

O método também tem como retorno FilteredList bruto sem o tipo genérico ao invés de FilteredList<Person>. O compilador deve estar dando algumas warnings dos tipos rawtypes e unchecked por causa disso.
Olhando aonde você usa a classe ligacao de fora dela, temos estes dois lugares:
new ligacao(b);
ligacao.get(obs(), obs2());

No primeiro caso, a instância de ligacao recém-criada não será utilizada para nada e será perdida para ser devorada pelo coletor de lixo. O único efeito disso será alterar o valor da variável estática b (que não vejo sentido ser protected ao invés de private). No segundo caso, o método get é estático. Como conclusão, instâncias da classe ligacao são inúteis, e portanto não tem sentido de serem instanciadas. O construtor que você usou nada mais é do que um setter disfarçado, e usar construtores para isso é algo horroroso. A sugestão neste caso seria eliminar o construtor e usar um setter estático:
class Ligacao {
    private static boolean b;
    public static void setFlag(boolean novoValor) {
        b = novoValor;
    }

// Na segunda classe:
Ligacao.setFlag(b);

Vamos aproveitar e dar uma olhada no código que veio da segunda classe, e tentar rastrear qual é o valor do b dela:
carne.setOnAction((Carne) -> {
    try {
        boolean b = false;
        System.out.println(false); // Escrevia b, mas b é sabidamente false.

        if(carne.getText().endsWith("Carnê")){
            carne.setText("Tabela");
            System.out.println(false); // Escrevia b, mas b é sabidamente false.
            b = true;
            System.out.println(true); // Escrevia b, mas b é sabidamente true.
        }else{
            carne.setText("Carnê");
            System.out.println(false); // Escrevia b, mas b é sabidamente false.
            b = false; // Não faz nada, pois b já é false.
            System.out.println(false); // Escrevia b, mas b é sabidamente false.
        }
        System.out.println(b);
        Ligacao.setFlag(b);
        System.out.println(b + "\n");
    } catch (Exception e) {
        e.printStackTrace();
    }

});

Vamos simplificar então, tirando os System.out.println desnecessários e as instruções desnecessárias:
carne.setOnAction((Carne) -> {
    try {
        boolean b = false;
        if (carne.getText().endsWith("Carnê")) {
            carne.setText("Tabela");
            b = true;
        } else {
            carne.setText("Carnê");
        }
        Ligacao.setFlag(b);
        System.out.println(b + "\n");
    } catch (Exception e) {
        e.printStackTrace();
    }
});

Podemos simplificar um pouco mais se notarmos que b só será verdadeiro se a condição do if for verdadeira e com isso podemos usá-la diretamente como o valor de b:
carne.setOnAction((Carne) -> {
    try {
        boolean b = carne.getText().endsWith("Carnê");
        carne.setText(b ? "Tabela" : "Carnê");
        Ligacao.setFlag(b);
        System.out.println(b + "\n");
    } catch (Exception e) {
        e.printStackTrace();
    }
});

Aqui, ainda cabe questionar o nome do parâmetro do lambda: Carne. Isso não é um nome apropriado, pois isso é uma variável e portanto deveria começar com letra minúscula. Além disso, ter duas variáveis cujo nome difere apenas pelas maiúsculas e minúsculas, a saber carne e Carne é uma má prática de programação pois deixa o código bem confuso. Sugiro renomear o Carne para alguma outra coisa.
Agora, voltando a sua primeira classe, percebe-se que você esqueceu o private na declaração do campo estático filtrar, mas vamos dar uma olhada no que o método get faz (já aplicadas as correções que sugeri antes):
private static FilteredList<Person> filtrar;
public static FilteredList<Person> get(ObservableList<Person> obs, ObservableList<Person> obs2) {
    filtrar = new FilteredList<>(obs, p -> true);
    if (b) {
        filtrar.removeAll(obs);
        filtrar = new FilteredList<>(obs2, p -> true);
    }else{
        filtrar.removeAll(obs2);
        filtrar = new FilteredList<>(obs, p -> true);
    }
    return filtrar;
}

Se b for verdadeiro eis o que ocorre:

Cria uma lista com todos os elementos de obs e o atribui à variável estática filtra, portanto perdendo a referência anterior da lista não importando o que ela era.
Remove todos os elementos de obs que estão na lista (e portanto todos os elementos), o que resulta em uma lista vazia.
Cria uma outra lista com todos os elementos de obs2. A lista anterior é perdida para o coletor de lixo, e portanto o trabalho realizado nela nos passos 1 e 2 foi desperdiçado.
Retorna a lista com os elementos que estavam em obs2.

Se b for falso:

Cria uma lista com todos os elementos de obs e o atribui à variável estática filtra, portanto perdendo a referência anterior da lista não importando o que ela era.
Remove todos os elementos de obs2 que estão na lista, o que resulta em uma lista com os elementos de obs que não estão em obs2. Se não houver nenhum elemento que esteja em ambas as listas, isso não vai fazer nada.
Cria uma outra lista com todos os elementos de obs. A lista anterior é perdida para o coletor de lixo, e portanto o trabalho realizado nela nos passos 1 e 2 foi desperdiçado.
Retorna a lista com os elementos que estavam em obs.

Observe que em ambos os casos, a lista que fica guardada ao final é irrelevante, pois da forma como o método get foi codificado, qualquer tentativa de acessar o conteúdo desta lista necessariamente a fará ser perdida.
Tudo isso ficaria muito mais simples assim:
public static FilteredList<Person> get(ObservableList<Person> obs, ObservableList<Person> obs2) {
    return new FilteredList<>(b ? obs : obs2, p -> true);
}

E é assim que o seu código fica no final das contas:
class Ligacao {
    private static boolean b;

    public static void setFlag(boolean novoValor) {
        b = novoValor;
    }

    public static FilteredList<Person> get(ObservableList<Person> obs, ObservableList<Person> obs2) {
        return new FilteredList<>(b ? obs : obs2, p -> true);
    }
}

carne.setOnAction(x -> {
    try {
        boolean b = carne.getText().endsWith("Carnê");
        carne.setText(b ? "Tabela" : "Carnê");
        Ligacao.setFlag(b);
        System.out.println(b + "\n");
    } catch (Exception e) {
        e.printStackTrace();
    }
});

FilteredList<Person> filtrar = Ligacao.get(obs(), obs2());

Por fim, algumas pessoas podem achar que acessar o campo estático usando this causa um erro de compilação. Isso não é verdade, pois é permitido acessar um campo estático usando uma variável ao invés do nome da classe e no caso, a variável é o this). Entretanto, isso é uma péssima prática de programação e não deveria ser feito nunca, mas a linguagem permite.
E também acessar uma variável estática de dentro do construtor é perfeitamente válido na linguagem Java. Na maioria das vezes (nem sempre, existem algumas exceções), fazer isso não é boa prática de programação e tende a deixar o código ruim e propenso a ocorrência de bugs, mas a linguagem Java permite.
Comment: Esses erros nos nomes das variáveis era por que me foi aconselhado que  usa-se nomes mais simples e quando fui trocar não deu muito certo. E essa parte `carne.setText(b ? "Tabela" : "Carnê");` não tinha conhecimento disso. Mas mesmo corrigindo o código, ele vai toda vez que eu clicar no botão ele vai mudar o `Person`(`obs()`) padrão para o outro `Person`(`obs2()`)?(Aqui fica o mesmo `Person`) Mas Obrigado por ter me alerdado sobre o `this` e outras cosas.
Comment: @lucasdaniel Na sua terceira classe, o que os métodos `obs()` e `obs2()` retornam?
Comment: São um leitura no banco de dados e retornam `ObservableList`, cada um é uma tabela do banco de dados.
Comment: Tem alguma ideia de como fazer isso?
Comment: Isso começou a funcionar quando usei FXML, e já que todo(ou quase todo) o código vai ficar em uma só classe faz-se assim:`tableview.getItems().clear()` e `tableview.getItems().addAll(b ? obs : obs2)`. Valeu por responder e desculpe por demorar para marcar como certar.


what is this size operator is doing in the function call?

Question: what is the work of this if Enquiry(lis1).size: and can we use .size at the time of calling the function if it is so ,then whatt will argument lis1 will receive in the function definition def Enquiry(lis1): and please elaborate this because i am beginner in python
import numpy
def Enquiry(lis1):
    return(numpy.array(lis1))
lis1 = []
if Enquiry(lis1).size:
    print("Not Empty")
else:
    print("Empty

Answer: For a numpy array, the size is a property that contains the size of the numpy.array object. The param, lis1 is a python object exposing the array interface. And yes, you can use .size while calling Enquiry(lis1) because when it's evaluated, it returns a numpy.array object and then calls .size on it.
sample usage:
>>> import numpy
>>> v = numpy.array([1, 2, 3])
>>> v.size
3
>>> dir(v)
[..., 'shape', 'size', 'sort', ...]
>>>
>>> getattr(v, 'size')
3

The function signature (use, help(numpy.array)) to see this:
Help on built-in function array in module numpy.core.multiarray:

array(...)
    array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)

    Create an array.

    Parameters
    ----------
    object : array_like
        An array, any object exposing the array interface, an object whose
        __array__ method returns an array, or any (nested) sequence.


Why will the Knights not have any of their players picked by the Kraken?

Question: I find it weird that for some reason, the Knights are not included in the list of teams that will have to sacrifice a player to the Kraken.
What is the reasoning with this? Is it that they are too new a team and they are given a chance by not letting one of their players get taken, or it's that the 30 picks system lands on a nice number and they decided to not change it?
Answer: It's because the Golden Knights are a recent expansion team themselves, and so they don't have to give up a player to Kraken, the newest expansion team.
This is based on the agreement the Knights made when joining the league. They wouldn't be part of the expansion draft for a number of years, but also wouldn't get a share of the expansion fee either. See this ESPN article:

The Golden Knights do not have to give up a player in the expansion
draft, a deal owner Bill Foley struck with the NHL in their original
franchise agreement in 2016. The only downside for Vegas? Foley
doesn't get a cut of Seattle's $650 million expansion fee, which
equates to a $21.67 million check for the other 30 teams.

Also as a side note, most NHL expansion teams over time tend to take years, sometimes even a whole decade, before becoming contenders. The Knights are an exception to the trend. Had they followed the usual trajectory, they would've been a mediocre team, with little expectation to be part of the expansion draft.
Comment: More specifically, it was in the original Knights franchise agreement that they would not be subject to any further expansion drafts for (some number of years I can't find right now). See e.g. "Why is Vegas exempt from the expansion draft?" at [ESPN](https://www.espn.co.uk/nhl/story/_/id/31811624/how-nhl-expansion-draft-work-seattle-kraken-schedule-format-rules-players-available).
Comment: "Had they followed the usual trajectory, they would've been a mediocre team..."  ...like the Kraken ended up being in their first season.
Comment: OK yeah so its an agreement, and an usual one at that. And that also comes with that they dont get a cut of the Kraken expansion fee.
Comment: Correct. I couldn't find the exact wording, but see my second paragraph, added more info including the expansion fee


Conditions for Muirhead's inequality hold for cyclic sums

Question: I know that Muirhead's inequality apply only for symmetrical sums, but all inequalities  with cyclic sums I have seen have the sequence in the greater side majorizing the sequence in the smaller side (what is necessary for Muirhead's inequality hold for symmetrical sums).
Also I couldn't find any counter-example that shows Muirhead's inequality doesn't hold for cyclic sums, so I wonder if the conditions for Muirhead's inequality hold in a cyclic sum are known, because if they are known, and easier to check than to prove a "hard" inequality then it would make way easier to prove a lot of other inequalities.
Comment: @Macavity I didn't know they could hold without majorization, thanks for this and for the link!
Comment: Maybe you should be asking under what condition(s) on the exponents on either side does cyclic sum inequalities hold.  Muirhead or majorization as a name may be a red herring here - maybe they hold without the majorization condition as well.  Related, check  https://artofproblemsolving.com/community/c6h103761p681279
Answer: For a cyclic sum the majorization is not enough.
For example, for non-negative variables $(3,2,0)\succ(3,1,1)$ but the inequality
$$a^3b^2+b^3c^2+c^3a^2\geq a^3bc+b^3ac+c^3ab$$ is wrong.
Try $a\rightarrow+\infty$ and $b^2-bc<0$.
By the way, there is the following way to prove of the Murhead's type cyclic inequalities.
We'll prove that $$\sum_{cyc}a^5b^2\geq \sum_{cyc}a^4b^2c$$ for non-negative variables.
Indeed, by AM-GM $$\sum_{cyc}a^5b^2=\frac{1}{19}\sum_{cyc}(14a^5b^2+2b^5c^2+3c^5a^2)\geq\sum_{cyc}\sqrt[19]{\left(a^5b^2\right)^{14}\left(b^5c^2\right)^2\left(c^5a^2\right)^3}=\sum_{cyc}a^4b^2c.$$
Vasile Cirtoaje was first, which proved that if this way does not work, so the inequality is wrong.
For example, we'll try to prove that $$\sum_{cyc}a^3b^2\geq \sum_{cyc}a^3bc$$ by this way.
We'll try to find values of $\alpha$, $\beta$ and $\gamma$ such that $\alpha+\beta+\gamma=1$ and the inequality
$$\alpha a^3b^2+\beta b^3c^2+\gamma c^3a^2\geq a^3bc$$ would be true by AM-GM.
Indeed, by AM-GM $$\alpha a^3b^2+\beta b^3c^2+\gamma c^3a^2\geq a^{3\alpha+2\gamma}b^{2\alpha+3\beta}c^{2\beta+3\gamma}$$ and we obtain the following system:
$3\alpha+2\gamma=3,$ $2\alpha+3\beta=1$ and $\alpha+\beta+\gamma=1$, which gives $$(\alpha,\beta,\gamma)=\left(\frac{5}{7},-\frac{1}{7},\frac{3}{7}\right)$$ and since $-\frac{1}{7}<0$, this way does not give a proof, which says that the inequality is wrong.
Comment: Michael I know there are counter-examples where Muirmaid's inequality doesn't work for cyclic sums. I also know there are infinite examples where it works for cyclic sums.
I'm not asking for alternative ways to prove cyclic sum inequalities so specific examples and how to prove them don't matter. My question was **in which conditions Muirhead's inequality hold for cyclic sums?**
Comment: thanks for the counter-example, but I don't think that answers the question, as it does not states what the condition to Muirhead's inequality be true is.
Comment: An example where Muirhead's inequality is true for cyclic sums is: $$\sum_{cyc}a^4b^1c^0d^0\geq \sum_{cyc}a^2b^1c^1d^1$$

$(4, 1, 0, 0) \succ (2, 1, 1, 1)$
Comment: @Tiago Cavalcante See please better my post. Your inequality is true because we can prove it by AM-GM.
Comment: By the way, the inequality $\sum\limits_{cyc}a^4b\geq\sum\limits_{cyc}a^3bc$ for four non-negative variables is wrong because we can-not prove it by using AM-GM, but $(4,1,0,0)\succ(3,1,1,0)$.
Comment: @Tiago Cavalcante Can you read my post? OK. Give me some cyclic  inequality in the Muirhead's typing and I'll say to you if your inequality is wrong or it's right. Maybe by this way you'll see that I gave the condition, which you look for.
Comment: Michael the condition you gave is that it is true only if it can be solved by AM-GM, but this condition is one of the type "if you can solve this another way, then it is true", which is a obvious "condition". I'm pretty sure there are other dozens of ways to show that a inequality is true or false, I don't think any of them can be called conditions.
Comment: It's not interesting already, if we can prove it by another way, because it's just wrong(it's exactly the condition: if we can not prove the muirhead typing inequality by AM-GM, so the inequality is wring).
Comment: We can write the condition, for which all solutions of some system are non-negative. This thing you can write by yourself already. For which you need to read my post.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/142203/discussion-between-tiago-cavalcante-and-michael-rozenberg).
Answer: Here's a Necessary and Sufficient condition for a true $3-$ variebles cyclic Muirhead-like Inequality. (Assuming all the variables are positive)
(I strongly suggest that you only read the 'Theorem' and 'Example' parts, and if you wish to learn more about ToC Method, please visit the link below)
Theorem. Consider the 'Triangle of Coefficient' (ToC for brevity) of the inquality you wish to prove, a $3-$ variebles cyclic Muirhead-like Inequality is true if and only if all the $-1$ is within the convex hull constructed by the $1$ . (In this case this convex hull is always a triangle, and it's also true if $-1$ lands on the side. Also note that due to cyclic symmetry, the ToC is rotationally symmetric by $2\pi/3$ in terms of its centroid.) $\square$
The proof for neccesity is quite simple because this determination works for any inequality, thus I won't prove it here and I'll focus on the proof for sufficiency.
Hint for the proof for neccessity: by AM-GM, we get the feeling of that the more unevenly-distrubuted the exponents are, the stronger the term is.
Here I'll first use the neccessity part of this theorem to cope with a counterexample, you may gain a basic idea of ToC Method as well.
Example1. Let's focus on a specific counterexample which Michael Rozenberg has provided.
Let $f:=\sum{a^3b^2}-\sum{a^3bc}$ , its ToC
$$
\begin{bmatrix}
0&&0&&1&&0&&0&&0\\
&0&&-1&&0&&-1&&0\\
&&0&&0&&0&&1\\
&&&1&&-1&&0\\
&&&&0&&0\\
&&&&&0
\end{bmatrix}
$$
Simply draw the triangle constructed by $1$, its' clear that the $-1$ are all outside of this triangle , which immediately falsifies this inequality. We may construct many other counterexamples by using this determination backwards. $\square$
Finally I'll give a proof for sufficiency. (This proof is extremely not rigorous because there's not yet a set of terms for ToC method. I just hope it conveys the basic ideas. If you can't stand this proof (I can't myself) , please just skip to the next part, in which I'll demonstrate the idea of this proof with an example.)
Proof. Note that the ToC of any $3-$ variebles cyclic Muirhead-like Inequality consists of three elements $1$ and three elements $-1$ . Consider a specific $-1$ and denote its position in the ToC as $P$ , and the three $1$ as $A,B,C$ .
Now that $P$ is inside the triangle $A,B,C$ , let $a,b,c$ respectively represent $S_{\triangle{BPC}},S_{\triangle{APC}},S_{\triangle{CPA}}$ .
Because any binary AM-GM results in a pair of affined unit $[1,-2,1]$ , we get the insight that AM-GM is associated with midpoints, which corresponds to centroids in trenary cases. By Lami's Theorem, the ratio of the coefficients in AM-GM equals to the ratio $a:b:c$ . By writing down this AM-GM, we have completed the proof. $\square$
Example2. For positive real numbers $a,b,c$, prove that:
$$
a^3b+b^3c+c^3a\geqslant abc(a+b+c)
$$
Let $g:=\sum{a^3b}-\sum{a^2bc}$ , its ToC
$$
\begin{bmatrix}
0&&1&&0&&0&&0\\
&0&&-1&&-1&&1\\
&&0&&-1&&0\\
&&&1&&0\\
&&&&0
\end{bmatrix}
$$
By applying Pick's Theorem, we may quickly calculate that the ratio of coefficients is $1:2:4$ , which implies this AM-GM Inequality
$$
\sum(a^3b+2b^3c+4c^3a)\geqslant\sum{7\left(a^7b^7c^14\right)^{\tfrac17}}=7\sum{abc^2}
$$
Simply by rearranging the terms proves the desired inequality. $\square$
Example3. This is an example Michael Rozenberg used in his answer, with ToC it's easier to figure out the coefficients.
For positive real numbers $a,b,c$, prove that:
$$
a^5b^2+b^5c^2+c^5a^2\geqslant abc(a^3b+b^3c+c^3a)
$$
Let $h:=\sum{a^5b^2}-\sum{a^4b^2c}$ , its ToC
$$
\begin{bmatrix}
0&&0&&1&&0&&0&&0&&0&&0\\
&0&&0&&-1&&0&&0&&0&&0\\
&&0&&0&&0&&0&&-1&&1\\
&&&0&&0&&0&&0&&0\\
&&&&0&&-1&&0&&0\\
&&&&&1&&0&&0\\
&&&&&&0&&0\\
&&&&&&&0
\end{bmatrix}
$$
By applying Pick's Theorem, we may quickly calculate that the ratio of coefficients is $2:3:14$ , which implies this AM-GM Inequality
$$
\sum(2a^5b^2+3b^5c^2+14c^5a^2)\geqslant\sum19\left(a^{38}b^{19}c^{76}\right)^{\tfrac1{19}}=19\sum{a^2bc^4}
$$
Simply by rearranging the terms proves the desired inequality. $\square$
You may see from Example2 and Example3 that this method is rather stereotyped, and I belive you could even write a programme specialised to solve such problems. This actually suggests the validity of this theorem.


How to use mgt-people-picker in react framework

Question: I'm trying to use mgt-people-picker inside my SPFx Webpart with React framework, and couldn't get the selected-people attribute work. I tried passing an array of graph user objects to it but no luck.
When I tried to use
document.querySelector('mgt-people-picker').selectUsersById(["id","id"])

it threw an error saying "Property 'selectUsersById' does not exist on type 'Element'"
The documentation is quite limited and unclear and there isn't much reference that I could find. Can anyone tell me how to use it?
Answer: React passes all data to web components in the form of HTML attributes. For primitive data this is fine, but it does not work when passing rich data, like objects or arrays. In those cases you will need to use a ref to pass in the object. See docs
Here is an example setting the users by id:
export default class HelloWorld extends React.Component<IHelloWorldProps, {}> {
  public render(): React.ReactElement<IHelloWorldProps> {
    return (
      <mgt-people-picker ref="peoplePicker"></mgt-people-picker>
    );
  }

  componentDidMount() {
    if (this.refs.peoplePicker) {
      let peoplePicker = this.refs.peoplePicker as MgtPeoplePicker;

      peoplePicker.addEventListener('selectionChanged', e => console.log(peoplePicker.selectedPeople));

      peoplePicker.selectUsersById(['4782e723-f4f4-4af3-a76e-25e3bab0d896']);
    }
  }
}

Comment: Awesome, please accept the answer so others can find it easier
Answer: With React, you can use PeoplePicker from the @microsoft/mgt-react module. Here is an example:
  <PeoplePicker
    selectionMode="single"
    defaultSelectedUserIds={[email@example.com"}]}
    selectionChanged={onChangePeople}
  />

And the event handler:
  function onChangePeople(e) {
    console.log(e.detail);
  }

Comment: the `selectionChanged` is not triggered in my case


Report Error in ERPNEXT cloud base frapppoecloud

Question: Error
whenever i creat the report i found this error any one help me to resole this .. what is the issue !!!
Answer: Have you tried running:
<code>bench migrate
</code>
Comment: Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach?
Answer: Frappe Cloud doesn't support development environments. In development environments, you may create query reports with Python code in your application level. In a production environment, changes like these (creating reports) are typically stored in the site level.
If you're seeing this error while creating a new (non custom) report, then this is most likely a bug. Without version information or access to installed apps & site, relying on Frappe Cloud support would be your best bet.


Buttons won't align properly in Firefox

Question: Rails 4, Ruby 2, Bootstrap 3, DataTables 1.10
Buttons for pagination align properly in IE and Chrome.  They won't align in Firefox.  I tried using this patch for Firefox.  I tried using input-group/input-group-btn.  This code is generated by DataTables.
In Firebug, the funky block in the upper right corner of First refers to ALL the li elements in the HTML in reverse order.  Leftmost is "last", then "next", then "previous, then "first".
Firefox:

Chrome and IE:

HTML generated by DataTables for Bootstrap:

                    First

                    Previous

                    Next

                    Last

Comment: Can you make a [fiddle](http://jsfiddle.net/)?
Comment: @Vucko The fiddle is http://jsfiddle.net/wszd0bt7/7/.  However, IE and Chrome both drop the Last button in it.  The Firefox display is similar to that shown here except it doesn't show the funky box in the upper right corner of First, at least that I can see...
Comment: @R_G you are mixing Jquery UI(using fg-button, ui-state-default classes) with Bootstrap and hence the styling issues. They do have [example for bootstrap](http://datatables.net/examples/styling/bootstrap.html) on their site. [Fiddle using datatable's bootstrap](http://jsfiddle.net/anpsmn/wszd0bt7/22/)
Comment: @anpsmn This entire table is built using DataTables with the jquery-datatables-rails gem, so that is where that mixed styling originates.
Comment: OBTW, where did all our comments from the last couple of days go???
Comment: @R_G Though you got the issue solved, you can post this query as an issue there on the plugin page as this is strange that they are mixing classes. Could be some mismatch of versions.
Answer: you set as like this to set
.fg-button {
    float: left;
    cursor: pointer;
    margin: 0;
    padding: 0;
    position: relative;
    text-align: center;
    text-decoration: none !important;
}

Live Demo
Comment: Where is the class "fg-button" stored?
Comment: @ i am not... in over extra style sheet.

Buttons won't align properly in Firefox


Select TOP 2 values for each group

Question: I'm having problem with getting only TOP 2 values for each group (groups are in column).
Example :
ID    Group    Value
1        A       30
2        A      150
3        A       40
4        A       70
5        B        0
6        B      100
7        B       90

I expect my output to be
ID    Group    Value
 1       A       150
 2       A        70
 3       B       100
 4       B        90

Simply, for each group I want just 2 rows with the highest Value
Answer: Most databases support the ANSI standard row_number() function.  You would use it as:
select group, value
from (select t.*,
             row_number() over (partition by group order by value desc) as seqnum
      from t
     ) t
where seqnum <= 2;

To set the id you can use row_number() in the outer query:
select row_number() over (order by group, value) as id,
       group, value
from (select t.*,
             row_number() over (partition by group order by value desc) as seqnum
      from t
     ) t
where seqnum <= 2;

However, changing the id seems suspicious.
Comment: @o_O  Editing an answer for simple oversites/typos... sure.  Editing an answer to impose your personal preferences... I find presumptuous.
Comment: @JohnCappelletti I'm sorry, being *presumptuous* wasn't my intention. I've seen people formatting SQL queries the way I did, so I thought to do the same., my bad! Will rollback
Comment: @o_O No worries and no apologies necessary.  Again, just my opinion,'
Comment: @o_O . . . I'm pretty neutral on whether keywords should be capitalized (I generally don't capitalize them; why bother the pinky finger so much?).  I am very particular about indentation.  My indentation style is described in Chapter 1 of "Data Analysis Using SQL and Excel".
Answer: You can use CTE with rank function ROW_NUMBER() .
Here is query to get your result.
;WITH cte AS
  ( SELECT Group, value,
           ROW_NUMBER() OVER (PARTITION BY Group ORDER BY value DESC) AS rn
    FROM test
  )
SELECT Group, value FROM cte
WHERE rn <= 2
ORDER BY value

Comment: Years later and its good. The most straight forward and working answer.

Select TOP 2 values for each group


Why can't I read my cookie value?

Question: I am trying to do some stuff with cookies. For now i am just trying to read a cookie and display the value in a popup-box using alert(value).
The tutorial I am following is :
http://www.w3schools.com/js/tryit.asp?filename=tryjs_cookie_username
Somehow this doesn't work when I implement this into my web application. The cookie will be created, but the reading part somehow does not work. When I use Web Developer Toolbar, I can see that a cookie named 'language' is there.
This is the script block in my Index.aspx
function createCookie() {
    var box = document.getElementById("language");
    var value = box.options[box.selectedIndex].value;
    var name = "language";
    var days = 1;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else var expires = "";
    document.cookie = name + "=" + value + expires + ";path=/;";
    document.cookie = 'language=en; expires=Thu, 2 Aug 2012 20:47:11 UTC;                                   path=/'
    window.location = 'http://localhost:57688';
}

function readLanguageCookie() {
    var language = getCookie("language");
    if (language != null && language != "") {
        alert("Language is: " + language);
    } else {
        language = "en";
        if (language != null && language != "") {
            setCookie("language", language, 365);
        }
    }
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

And this is how I try to execute the method
<form method="get" action="http://localhost:57688">
hjhj
<select id="language" onchange="readLanguageCookie()">
<option value="en">English</option>
<option value="nl">Dutch</option>
</select>
</form>

Cookie details:
Name    language
Value   en
Host    localhost
Path    /
Secure  No
Expires Thu, 02 Aug 2012 20:47:11 GMT

What am I doing wrong here?
Comment: I would look into a different resource; w3schools can be sketchy at times and generally is frowned upon at SO by most users. Try [Quirksmode's Cookie page](http://www.quirksmode.org/js/cookies.html) instead. There's also [MDN's `document.cookie` page](https://developer.mozilla.org/en/DOM/document.cookie).
Comment: What exactly "does he not do"? It's working for me, but I can see your "readLanguageCookie()" doesnt make sense. It is reading the cookie, and depending on that value, setting the cookie... [Check my fiddle](http://jsfiddle.net/feZAC/)
Comment: Can you post the actual content of the cookie in your browser?
Comment: didn't u see this line?
if (language != null && language != "") {
                    alert("Language is: " + language);
                }
Comment: Are you getting any Javascript errors? What is happening on your side?
Comment: the popup just never shows, im not running into errors, its like the method isnt being called at all....
Comment: Ok, when I try to replicate the code you posted, i noticed that you not calling createCookie() anywhere, and that setCookie is not defined. Can you post the complete snippet of code?
Comment: i have called createCookie in a previous session, and the cookie is there, it doesnt get called in my current code
Comment: @dotNETLady - You don't have enough rep yet, but comments belong under the question. I think you'll get *enough* rep for comments at 30-50 or so. Until then, I'd refrain from posting "comment"-like answers. `:)`
Comment: @JaredFarrish added details to question
Comment: @DeadManWalking: I would say you'd want to change the value to the one you selected in the list..
Comment: yes normally i would do that (set the cookie in onchange), but this A TEST is just to TEST if i can READ the cookie, which isnt working. i just need to be able to READ my cookie, so i can continue my programming.
Answer: May be the reason is hardcoded date?:
    document.cookie = 'language=en; expires=Thu, 2 Aug 2012 20:47:11 UTC;

Comment: the problem is READING the cookie, i have no problems creating

Why can't I read my cookie value?