Knowing that $i\frac{z-z_4}{z_2-z_3},i\frac{z-z_5}{z_3-z_1},i\frac{z-z_6}{z_1-z_2}\in \mathbb R$, determine $\min(|z-z_4|^2+|z-z_5|^2+|z-z_6|^2)$.

Question:
Consider complex numbers $z_1 = 1 + i, z_2 = 1 - 3i, z_3 = 4 + i$ and complex variable $z$. Knowing that there exist complex numbers $z_4, z_5, z_6$ such that $\dfrac{z_4 - z_2}{z_4 - z_3}, \dfrac{z_5 - z_3}{z_5 - z_1}$ and $\dfrac{z_6 - z_1}{z_6 - z_2}$ are real numbers, while $\dfrac{z - z_4}{z_2 - z_3}, \dfrac{z - z_5}{z_3 - z_1}$ and $\dfrac{z - z_6}{z_1 - z_2}$ are imaginary numbers, determine the minimum value of $T = |z - z_4|^2 + |z - z_5|^2 + |z - z_6|^2$.

[For context, this question is taken from an exam whose format consists of 50 multiple-choice questions with a time limit of 90 minutes. Calculators are the only electronic device allowed in the testing room. (You know those scientific calculators sold at stationery stores and sometimes bookstores? They are the goods.) I need a solution that works within these constraints. Thanks for your cooperation, as always. (Do I need to sound this professional?)
By the way, if the wording of the problem sounds rough, sorry for that. I'm not an expert at translating documents.]
█▓▒░(°◡°)░▒▓█ I wish I was kidding sometimes.
First of all, it should be obvious that for all real numbers $x \not\in \{0; 1\}$, $\dfrac{1}{1 - x}$ and $\dfrac{1}{\dfrac{1}{x} - 1}$ are also real. In this case, $\dfrac{z_4 - z_3}{z_2 - z_3}, \dfrac{z_5 - z_1}{z_3 - z_1}, \dfrac{z_6 - z_2}{z_1 - z_2} \in \mathbb R$ and $\dfrac{z_4 - z_2}{z_2 - z_3}, \dfrac{z_5 - z_3}{z_3 - z_1}, \dfrac{z_6 - z_1}{z_1 - z_2} \in \mathbb R$.
Should I just say that $\dfrac{z_4 - \dfrac{z_2 + z_3}{2}}{z_2 - z_3}, \dfrac{z_5 - \dfrac{z_3 + z_1}{2}}{z_3 - z_1}, \dfrac{z_6 - \dfrac{z_1 + z_2}{2}}{z_1 - z_2}$ are real numbers?... I'll keep them here for now.
Furthermore, since $|z_2 - z_3| = 5, |z_3 - z_1| = 3$ and $|z_1 - z_3| = 4$, (if you listen carefully, you can hear the ancient Egyptians quaking in their tombs), $$T = |z - z_4|^2 + |z - z_5|^2 + |z - z_6|^2 = -\left[25 \times \left(\dfrac{z - z_4}{z_2 - z_3}\right)^2 + 9 \times \left(\dfrac{z - z_5}{z_3 - z_1}\right)^2 + 16 \times \left(\dfrac{z - z_6}{z_1 - z_2}\right)^2\right]$$
Other miscellaneous observations include  $\Im(z_5) = 1, \Re(z_6) = 1$ and $$\dfrac{\Re(z_4) - \dfrac{5}{2}}{-3} = \dfrac{\Im(z_4) + 1}{-4} \implies z_4 = \left(3n + \dfrac{5}{2}\right) + (4n - 1)i \ (n \in \mathbb R)$$
Anyhow, that's all for now, I'll probably come back to this later.
As always, thanks for reading, (and even more so if you could help), have a great tomorrow, everyone~
By the way, the choices were $\dfrac{72}{5}, 3, \dfrac{72}{25}$ and $\dfrac{18}{25}$.
Answer: $\underline{\textbf{Preliminary Results}}$
PR-1
Given any $3$ distinct complex numbers, $a,b,c$ such that
$\displaystyle \frac{a-b}{a-c} = s \in \Bbb{R_{\neq 0}}$
where $(b-c) = re^{i\theta}$.
Then there exists $t \in \Bbb{R_{\neq 0}}$ such that
$(a-b) = tre^{i\theta}.$
Further, $(a)$ is somewhere on the infinite line that passes through points $(b)$ and $(c).$
Proof
$(a-b) = s(a-c) = s(b-c) + s(a-b) \implies (a-b)(1-s) = s(b-c).$
Since $a,b,c$ distinct, $s \neq 0$ and $s \neq 1.$
Let $\displaystyle ~t = \frac{s}{1-s}.$
Then $(a - b) = t(b-c) = tre^{i\theta}.$
If $t > 0$, then the argument of $(a-b)$ matches the argument of $(b-c)$, within a modulus of $(2\pi)$.
If $t < 0$, then $(a-b) = [r \times (-t)] e^{i(\theta + \pi)}.$

PR-2
Given any $4$ distinct complex numbers, $a,b,c,d$ such that
$\displaystyle \frac{a-b}{c-d} = is ~: ~s \in \Bbb{R_{\neq 0}}$
where $(c-d) = re^{i\theta}$.
Then, $(a-b) = sre^{i(\theta + \pi/2)}.$
Further, $(a)$ is somewhere on the infinite line that passes through $(b)$ and is perpendicular to the line segment connecting points $c$ and $d$.
Proof
$(a-b) = is(c-d) = e^{i(\pi/2)}sre^{i\theta}.$
If $s > 0$, then the argument of $(a-b)$ equals $(\theta + \pi/2)$, within a modulus of $(2\pi)$.
If $s < 0$, then $(a-b) = [r \times (-s)] e^{i(\theta + \pi/2 + \pi)}.$

Using PR-1, you have that

$(z_4)$ is on the infinite line connecting $(z_2)$ and $(z_3).$

$(z_5)$ is on the infinite line connecting $(z_3)$ and $(z_1).$

$(z_6)$ is on the infinite line connecting $(z_1)$ and $(z_2).$

Using PR-2, you have that

$(z)$ is on the infinite line that passes through $(z_4)$ and is perpendicular to the line connecting $(z_2)$ and $(z_3).$

$(z)$ is on the infinite line that passes through $(z_5)$ and is perpendicular to the line connecting $(z_3)$ and $(z_1).$

$(z)$ is on the infinite line that passes through $(z_6)$ and is perpendicular to the line connecting $(z_1)$ and $(z_2).$

Here, it helps to visualize the situation.  $\triangle(z_1z_2z_3)$ is a right triangle with vertices at $(1 + i), (1 - 3i),$ and $(4 + i)$.
Clearly, $z_4, z_5, z_6$ are inside line segments $(\overline{z_2z_3}), (\overline{z_1z_3}),$ and $(\overline{z_1z_2})$, respectively.
$z$, is located somewhere inside the triangle, and the line segments connecting $z$ with each of $z_4, z_5, z_6$ form perpendiculars to the triangle's sides.
So, the problem can be solved by assuming that $z$ has Cartesian coordinates $(x,y)$, with $1 < x < 4, ~-3 < y < 1$.  Based on the $(x,y)$ coordinate, the square of the distances between $z$ and $z_4, z_5,$ and $z_6$ will be established.
Then, $(x,y)$ will be chosen to minimize these distances.

The distance between $z$ and $z_6$ will be $(x - 1)$.
The distance between $z$ and $z_5$ will be $(1 - y)$.
The slope of $(\overline{z_2z_3})$ is $(4/3).$
Therefore, the slope of $(\overline{zz_4})$ must be  $(-3/4).$
Let the Cartesian coordinates of $(z_4)$ be given by $(e,f).$
Then, $\displaystyle ~\frac{y-f}{x-e} = -\frac{3}{4}~~ \text{and}~~ \frac{1-f}{4-e} = \frac{4}{3}.$
This implies that
$16 - 4e = 3 - 3f \implies 4e - 3f = 13.$
$-3x + 3e = 4y - 4f \implies 3e + 4f = 3x + 4y.$
This resolves to
$$e = \frac{9x + 12y + 52}{25}, ~~ f = \frac{12x + 16y - 39}{25}. \tag1 $$

Calculating
$$(x - e)^2 = \frac{256x^2 + 144y^2 + 2704 - 384xy - 1664x + 1248y}{625}.$$
$$(y - f)^2 = \frac{144x^2 + 81y^2 + 1521 - 216xy - 936x + 702y}{625}.$$
Therefore,
$$(x-e)^2 + (y-f)^2 = \frac{16x^2 + 9y^2 + 169 - 24xy - 104x + 78y}{25}.$$
Then, squaring the distance from $(x,y)$ to each of $z_6$ and $z_5$ and adding them gives
$$\frac{(25x^2 - 50x + 25) + (25y^2 - 50y + 25)}{25}$$
$$= \frac{25x^2 + 25y^2 + 50 - 50x - 50y}{25}.$$
Combining this with $(x-e)^2 + (y-f)^2$ gives
$$\frac{41x^2 + 34y^2 + 219 - 24xy - 154x + 28y}{25}. \tag2 $$
So, with $x$ constrained by $1 < x < 4$
and $y$ constrained by $-3 < y < 1$,
the challenge is to choose $x,y$ so as to
minimize the numerator in (2) above.
Let $D(x,y)$ denote the numerator in (2) above.
Holding $x$ fixed, you have that
$\displaystyle \frac{\partial[D(x,y)]}{\partial y} =
68y - 24x + 28.$
Holding $y$ fixed, you have that
$\displaystyle \frac{\partial[D(x,y)]}{\partial x} =
82x - 24y - 154.$
In both of the equations above, it is immediate that the partial 2nd derivatives will be positive.  So, computing $x,y$ to zero out both derivatives should produce the minimum.
This is achieved at $$(x,y) = \left(\frac{49}{25}, \frac{7}{25}\right).$$
Using (1) above, these values for $(x,y)$ result in
$$(e,f) = \left(\frac{73}{25}, \frac{-11}{25}\right).$$
So, the minimum sum of the squares of the distances is
$$\left(\frac{49}{25} - 1\right)^2 + \left(1 - \frac{7}{25}\right)^2 + \left(\frac{73-49}{25}\right)^2 + \left(\frac{7 + 11}{25}\right)^2$$
$$= \frac{72}{25}.$$

Addendum
I should point out some things that will make a difference in a timed test.
Normally, in a multiple choice setting, I would simply assume that the preliminary results were true, just to save time.  This means that I would proceed on that basis even though I wasn't sure that the conclusions were valid.
The choice of $(x,y)$ resulted in the square of the distance from $(x,y)$ to the hypotenuse to exactly equal the sum of the squares of the distances, to the two legs of the right triangle.
My knowledge of Real Analysis and Geometry is shallow in this area.  The result didn't surprise me.  However, I suspect that in the classroom setting, the student is supposed to know this in advance, and use this concept to shortcut the computations of $(x,y)$ and $(e,f)$.
In fact, the key idea would be to use this fact, compute $(x,y)$ alone (if possible), and then ignore $(e,f)$.  You would then simply take the sums of the squares of $(x,y)$ to the two legs of the right triangle, and then double it.
There is an additional shortcut achievable by meta-cheating.  It is clear from the initial visualization that the only plausible choices will be $(3)$ and $~\displaystyle \frac{72}{25}.$
So, you could bypass all other Math, and simply explore which of those two values results in the sum of the squares of $(x,y)$ to the two legs of the triangle equaling the square of the distance of $(x,y)$ to the hypotenuse.
In the meta-cheating world, this consideration immediately makes it game-over, although you do bypass the educational value of the problem.
Comment: Thanks for answering, that was an amazing answer~ For the second part of the problem, I actually have an easier way of going about it, (at least for me).
Let $A,B,C,D,E,F,M$ be the visual representation of complex numbers $z_1,z_2,z_3,z_4,z_5,z_6,z$ on the complex plane. We have that $$\begin{aligned}1=\dfrac{[MBC]+[MCA]+[MAB]}{[ABC]}&=\dfrac{d(M,BC)}{d(A,BC)}+\dfrac{d(M,CA)}{d(B,CA)}+\dfrac{d(M,AB)}{d(C,AB)}\\&=\dfrac{5MD}{12}+\dfrac{ME}{4}+\dfrac{MF}{3}\end{aligned}$$
Comment: (Had to split my response through two comments, sorry~) Then through the use of the Cauchy-Schwarz inequality, $$\begin{aligned}\overbrace{\left[\left(\dfrac{5}{12}\right)^2+\left(\dfrac{1}{4}\right)^2+\left(\dfrac{1}{3}\right)^2\right]}^{25/72}(MD^2+ME^2+MF^2)&\ge\overbrace{\left(\dfrac{5MD}{12}+\dfrac{ME}{4}+\dfrac{MF}{3}\right)^2}^{1}\\\implies|z-z_4|^2+|z-z_5|^2+|z-z_6|^2&\ge\dfrac{72}{25}\end{aligned}$$ And bam! [inserts miscellaneous onomatopoeia] Those preliminary results really helped me, thanks so much once again~


Node in EKS doesn't resolve DNS names of RDS (IP working)

Question: Once again I shall require help from Stack Overflow :).
We have a fresh public access endpoint EKS Cluster, an app inside the nodes that return something from the RDS.
The VPC of the cluster is VPC peering with the private VPC that holds the RDS. We also have Accepter DNS resolution enabled. The Accepter is the RDS VPC.
When SSH-ing into my worker nodes, and we telnet the RDS, it resolves it.
Initially, the Connection String was establish with the Endpoint. It didn't reach the database. I changed it to the IP of the RDS and it worked.
When doing with the DNS names, it takes:
1) lots of time to load,
2)

"Unable to retrieve Error: Timeout expired. The timeout period
  elapsed prior to obtaining a connection from the pool. This may have
  occurred because all pooled connections were in use and max pool size
  was reached."

Therefore I was wondering if any of you faced this issue and how you solved it? There seems to be a lot of fun regarding DNS resolution with EKS and I'm not exactly sure why the instance can resolve but not the pod.
Thank you for your help!
Comment: Edit: We added 53 outbound in NaCL and now we can't even resolve the ip of the cluster anymore
Comment: Did you add port 53 UDP on the inbound? I had a deployment with a target in my own private subnet and not enabling the incoming DNS response seemed to be the culprit. I'm not sure how exactly RDS's endpoint URL behaves in the context of a private subnet, but perhaps you can consider manually adding a DNS entry in a private hosted zone. We use that for our workloads and it's working just fine.
Answer: Okay so we found the answer!
It was SO LONG to find it, so i'm gonna save you that trouble if you happen to have the same problem/configuration than us.

You need port 53 outbound in NaCL and SG. That's the way kubernetes checks DNS. (DNS problem on AWS EKS when running in private subnets)
In the connection string, Data source, we previously had "Data Source=DNSName;etc". We changed it to "Data source=tcp:DNSName".

That was it
2 days for that.
:D
EDIT: I might add I faced the same problem in another environment/aws account (53 was the answer but slightly differently): Pods in EKS: can't resolve DNS (but can ping IP)


Any good or better or direct way to get the chunking result from a nltk Tree?

Question: I want to chunk the string to get the groups in a certain height. The original order should be kept and it should also be completly contain all the original words.
import nltk
height = 2
sentence = [("the", "DT"), ("little", "JJ"), ("yellow", "JJ"), ("dog", "NN"), ("barked","VBD"), ("at", "IN"), ("the", "DT"), ("cat", "NN")]

pattern = """NP: {
?<JJ>*<NN>}
VBD: {<VBD>}
IN: {<IN>}"""
NPChunker = nltk.RegexpParser(pattern)
result = NPChunker.parse(sentence)

In [29]: Tree.fromstring(str(result)).pretty_print()
                             S
            _________________|_____________________________
           NP                        VBD       IN          NP
   ________|_________________         |        |      _____|____
the/DT little/JJ yellow/JJ dog/NN barked/VBD at/IN the/DT     cat/NN

My approach is kind of brute force like below:
In [30]: [list(map(lambda x: x[0], _tree.leaves())) for _tree in result.subtrees(lambda x: x.height()==height)]
Out[30]: [['the', 'little', 'yellow', 'dog'], ['barked'], ['at'], ['the', 'cat']]

I thought there should exist some direct API or something I can use to do chuncking. Any suggestions are highly appreciated.
Comment: Nope. But just call `Tree.leaves()` and check `Tree.height`. You're doing it the right way =)
Comment: @alvas That's fine. But I don't get your point of the mention of that two methods. And the downvote by someone. :)
Comment: Not me though ;P
Comment: @alvas I thought it would be better to keep the string not only non-overlapping and grouped but also complete and in original order.
Comment: Then you not only want the leaves of the Tree object but the leaves of Tree or str? It's unclear what's the purpose. Could you give several more inputs / outputs?
Comment: @alvas Sure. Please see the updates.
Answer: Nope, there isn't any built-in function in NLTK to return Tree of a certain depth.
But you can use the depth-first traversal from How to Traverse an NLTK Tree object?
To be efficient, you can iterate depth-first and only recur if the depth is less than necessary, e.g.
import nltk
sentence = [("the", "DT"), ("little", "JJ"), ("yellow", "JJ"), ("dog", "NN"), ("barked","VBD"), ("at", "IN"), ("the", "DT"), ("cat", "NN")]

pattern = """NP: {
?<JJ>*<NN>}
VBD: {<VBD>}
IN: {<IN>}"""
NPChunker = nltk.RegexpParser(pattern)
result = NPChunker.parse(sentence)

def traverse_tree(tree, depth=float('inf')):
    """
    Traversing the Tree depth-first,
    yield leaves up to `depth` level.
    """
    for subtree in tree:
        if type(subtree) == nltk.tree.Tree:
            if subtree.height() <= depth:
                yield subtree.leaves()
                traverse_tree(subtree)

list(traverse_tree(result, 2))

[out]:
[[('the', 'DT'), ('little', 'JJ'), ('yellow', 'JJ'), ('dog', 'NN')],
 [('barked', 'VBD')],
 [('at', 'IN')],
 [('the', 'DT'), ('cat', 'NN')]]

Another example:
x = """(S
  (NP the/DT
      (AP little/JJ yellow/JJ)
       dog/NN)
  (VBD barked/VBD)
  (IN at/IN)
  (NP the/DT cat/NN))"""

list(traverse_tree(Tree.fromstring(x), 2))

[out]:
[['barked/VBD'], ['at/IN'], ['the/DT', 'cat/NN']]


Relationship between the diagonal elements of a Hermitian matrix and its eigenvalues

Question: CONVEX AND CONCAVE FUNCTIONS OF SINGULAR
VALUES OF MATRIX SUMS
This question comes from the proof of theorem $1$ linked above.
Assume $A,B,C=A+B$  are $n\times n$ Hermitian positive semidefinite  matrices with eigenvalues $\alpha _1\geqslant \alpha _2\geqslant \cdots \geqslant \alpha _n,\beta _1\geqslant \beta _2\geqslant \cdots \geqslant \beta _n,\gamma _1\geqslant \gamma _2\geqslant \cdots \geqslant \gamma _n$ respectively.
Since $A$ and $B$ are semidefinite, we may write $A = A_1A_1^{*}$,
$B = B_1B_1^{*}$, where $*$ denotes adjoint.
Then we have $$C=A+B=\left( \begin{matrix}
 A_1&  B_1\\
\end{matrix} \right) \left( \begin{array}{c}
 {A_1}^*\\
 {B_1}^*\\
\end{array} \right) .$$
Reversing the order of the factors in the last product, and using the fact
that this reversal leaves unchanged the nonzero eigenvalues, we get that
$$\left( \begin{array}{c}
 {A_1}^*\\
 {B_1}^*\\
\end{array} \right) \left( \begin{matrix}
 A_1&  B_1\\
\end{matrix} \right) =\left( \begin{matrix}
 {A_1}^*A_1&  {A_1}^*B_1\\
 {B_1}^*A_1&  {B_1}^*B_1\\
\end{matrix} \right) $$
has $\gamma _1,\cdots ,\gamma _n,0,\cdots ,0$ as its eigenvalues.
Making a block diagonal unitary similarity to diagonalize the blocks $A_1^{*}A_1$ and $B_1^{*}B_1$, we can get that $\alpha _1,\cdots ,\alpha _n,\beta _1,\cdots ,\beta _n$ are diagonal elements of a Hermitian matrix having $\gamma _1,\cdots ,\gamma _n,0,\cdots ,0$ as its eigenvalues.
Then the author writes $$\left( \begin{array}{c}
 \alpha _1\\
 \vdots\\
 \alpha _n\\
 \beta _1\\
 \vdots\\
 \beta _n\\
\end{array} \right) =S\left( \begin{array}{c}
 \gamma _1\\
 \vdots\\
 \gamma _n\\
 0\\
 \vdots\\
 0\\
\end{array} \right) $$
where $S$ is a $2n$ -square doubly stochastic matrix.
My question is how to determine the existence of $S$.
I think there should be some relationship between the diagonal elements of the Hermitian matrix and its eigenvalues.
Maybe it is a theorem or I am not thinking enough.
I would like to get some references or suggestions.
Thanks!
Answer: The relevant theorem is the "$\implies$" direction of the Schur-Horn theorem. As the proof in the Wikipedia page demonstrates, a suitable $S$ can be constructed directly using the spectral decomposition of your size-$2n$ Hermitian matrix.
Notably, the majorization inequalities and equality referred to in the statement of the Schur Horn theorem are equivalent to the existence of such a doubly stochastic matrix $S$.


Sum of $X_n$ independently distributed with $X_n\sim\text{Exp}(n)$

Question: Let $X_1, X_2, \dots$ be independently distributed with $X_n\sim\text{Exp}(n)$ and let $a_n>0$ for all $n\in\mathbb N$ with $\sum\limits_{n=1}^\infty \frac{a_n}{n}<\infty.$

Prove that $\sum\limits_{n=1}^\infty a_nX_n$ converges almost surely.

My first instinct was to use the Lindeberg-Feller CLT. But I want almost surely convergence. I can't use Kolmogorov's two-series theorem or Kolmogorov's three-series theorem because the $X_n$ are not i.i.d.
I know that $$\sum\limits_{n=1}^\infty \mathbb E[a_n^2X_n^2] = \frac 12\sum\limits_{n=1}^\infty \left(\frac{a_n}{n}\right)^2<\infty.$$
And $$\sqrt{n}\frac{S_n-\frac{\ln n}{n}}{\sqrt{\sum\limits_{n=1}^\infty \frac{1}{n^2}}}\overset{n\to\infty}{\implies}\mathcal N(0,1).$$
What can I do?
Comment: Isn't only independence required for Kolmogorov's three-series test?
Comment: Oh that is true ... Thank you @GiorgosGiapitzakis
Answer: We can use Kolmogorov's two-series theorem because only independence is necessary. So we have
$$\sum\limits_{n=1}^\infty\mathbb E[a_nX_n]=\sum\limits_{n=1}^\infty a_n\mathbb E[X_n]=\sum\limits_{n=1}^\infty\frac{a_n}{n}<\infty$$
because of the conditions we impose on the $a_n$. Now because $a_n>0$ we see that $$\sum\limits_{n=1}^\infty\mathbb V[a_nX_n]=\sum\limits_{n=1}^\infty a_n^2\mathbb V[X_n]=\sum\limits_{n=1}^\infty\frac{a_n^2}{n^2}\leqslant \left[\sum\limits_{n=1}^\infty\frac{a_n}{n}\right]^2 <\infty.$$
Therefore is follows, that $\sum\limits_{n=1}^\infty \frac{a_n}{n}$ converges almost surely.


If $A=\Gamma(X,O_X)$ and $Spec(A)=X$ then $Spec(A)=X$ as schemes.

Question: Let $X$ be a scheme and $A$ a commutative Ring. Assume that we have an isomorphism $A \rightarrow \Gamma (X, O_X)$ and the induced map $X \rightarrow Spec(A)$ is a homeomorphism.

Question: Is it true that then X is isomorphic to $Spec(A)$ as schemes?

I would suspect this to be true. I tried to check this on the stalks but we only have for each $\mathfrak{p} \subset A$ that $O_{X,x}=A_\mathfrak{p}=\Gamma(X,O_X)_\mathfrak{p}$. Unfortunately we dont know that the ring on the RHS is actually the stalk of $X$.
Comment: You have a natural bijection $Hom_{Sch}(X, Spec(A)) \rightarrow Hom_{Rings}(A, \Gamma (X, O_X)$ by taking global sections. This is for example an exercise in Hartshorne Chapter II 2.4
Comment: Have you tried using the (covariant) Yoneda lemma? It seems that your hypotheses imply that the covariant functors Hom($X,*$) and Hom(Spec($A),*$) from affine schemes to Sets are naturally isomorphic. While its true that the contravariant version of this would imply $X = Spec(A)$, the covariant version probably doesn't. However perhaps by additionally using the homeomorphism $X\rightarrow Spec(A)$ you can get the full result?
Comment: Related: https://math.stackexchange.com/questions/1848370
Answer: Here's one way to conclude (there might be simpler ways):
The morphism of schemes $X\to Spec(A)$ is a homeomorphism. By Lemma 28.44.2 here it is then an affine morphism. Since the target is affine, this implies that $X$ itself is affine, and then you're done.
Answer: Let us identify the underlying topological spaces of $X$ and $\operatorname{Spec}(A)$ and write $O_A$ for the structure sheaf of $\operatorname{Spec}(A)$.  So we have a topological space $X$ with two different sheaves of rings $O_X$ and $O_A$ that make it a scheme, with a map $O_A\to O_X$.  We will show that $O_X$ is a quasicoherent $O_A$-module.
Fix a point $x\in X$.  Take an $O_X$-affine open neighborhood $V$ of $x$; say $(V,O_X|_V)$ is isomorphic to $\operatorname{Spec}(B)$ for some ring $B$.  The composition $V\to X\to\operatorname{Spec}(A)$ induces a homomorphism $\varphi:A\to B$.  Now take an element $a\in A$ such that the distinguished open set $U=D(a)\subseteq\operatorname{Spec}(A)$ satisfies $x\in U\subseteq V$.  Note that the distinguished open subset $D(\varphi(a))\subseteq \operatorname{Spec}(B)=V$ has the same points as $D(a)$.  We conclude that $U$ is an open neighborhood of $x$ which is affine as a subscheme of both $X$ and $\operatorname{Spec}(A)$.  It follows that $O_X|_U$ is a quasicoherent $O_A|_U$-module: this is just the fact that if $f:Y\to Z$ is a map of affine schemes, $f_*O_Y$ is quasicoherent.
Since quasicoherence is a local property and $x\in X$ was arbitrary, we conclude that $O_X$ is a quasicoherent $O_A$-module.  Since $\operatorname{Spec}(A)$ is affine, this means it is determined by its global sections, so the assumption that $O_A\to O_X$ is an isomorphism on global sections implies it is an isomorphism of sheaves.  It follows that $X\to \operatorname{Spec}(A)$ is an isomorphism of schemes.
(Incidentally, the real work in this argument is being hidden in the (nontrivial!) fact that every quasicoherent sheaf on $\operatorname{Spec}(A)$ is determined by its global sections (i.e., that sheaves on affine schemes that are locally induced by modules are globally induced by modules).)


JPA / Hibernate - LazyLoading OneToMany duplicando registros

Question: Bom, tenho a seguinte estrutura:
public class FinCxaTransacaoGrupo {

    @Id
    @GeneratedValue(generator="gen-uuid")
    @GenericGenerator(name="gen-uuid", strategy = "uuid2")
    @Type(type="pg-uuid")
    @Column(name="id_fin_cxa_transacao_grupo")
    private UUID idFinCxaTransacaoGrupo;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="id_fin_cxa_transacao_destino")
    private FinCxaTransacao finCxaTransacaoDestino;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="id_fin_cxa_transacao_origem")
    private FinCxaTransacao finCxaTransacaoOrigem;

}

public class FinCxaTransacao {

    @Id
    @GeneratedValue(generator = "gen-uuid")
    @GenericGenerator(name = "gen-uuid", strategy = "uuid2")
    @Type(type = "pg-uuid")
    @Column(name = "id_fin_cxa_transacao")
    private UUID idFinCxaTransacao;

    @OneToMany(cascade=CascadeType.ALL, mappedBy = "finCxaTransacao")
    private List<FinCxaPlanoLcto> finCxaPlanoLctos = new ArrayList<>();

    @OneToMany(mappedBy="finCxaTransacaoDestino")
    private List<FinCxaTransacaoGrupo> finCxaTransacaoGruposDestino = new ArrayList<>();

    @OneToMany(mappedBy="finCxaTransacaoOrigem")
    private List<FinCxaTransacaoGrupo> finCxaTransacaoGruposOrigem = new ArrayList<>();

}

public class FinCxaPlanoLcto {

    @Id
    @GeneratedValue(generator="gen-uuid")
    @GenericGenerator(name="gen-uuid", strategy = "uuid2")
    @Type(type="pg-uuid")
    @Column(name="id_fin_cxa_plano_lcto")
    private UUID idFinCxaPlanoLcto;

    @ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
    @JoinColumn(name="id_fin_cxa_transacao")
    private FinCxaTransacao finCxaTransacao;

}

Query executada para encontrar o Grupo:
public FinCxaTransacaoGrupo buscarFinCxaTransacaoGrupoEstorno(UUID idFinCxaTransacao) {

    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<FinCxaTransacaoGrupo> query = cb.createQuery(FinCxaTransacaoGrupo.class);
    Root<FinCxaTransacaoGrupo> finCxaTransacaoGrupo = query.from(FinCxaTransacaoGrupo.class);
    query.where(cb.or(cb.equal(finCxaTransacaoGrupo.get(FinCxaTransacaoGrupo_.finCxaTransacaoDestino).get(
            FinCxaTransacao_.idFinCxaTransacao), idFinCxaTransacao),
            cb.equal(finCxaTransacaoGrupo.get(FinCxaTransacaoGrupo_.finCxaTransacaoOrigem).get(
                    FinCxaTransacao_.idFinCxaTransacao), idFinCxaTransacao)));

    query.distinct(true);

    query.select(finCxaTransacaoGrupo).distinct(true);
    return em.createQuery(query).getSingleResult();
}

A tabela FinCxaTransacaoGrupo contém um registro.
A tabela FinCxaTransacao contém um registro para finCxaTransacaoDestino e finCxaTransacaoOrigem;
a tabela FinCxaPlanoLcto contém dois registro para finCxaTransacaoDestino e um registro para finCxaTransacaoOrigem;
Lembrando que na estrutura, o FinCxaPlanoLcto é LazyLoading... Ao buscar finCxaTransacaoDestino.getFinCxaPlanoLctos() essa lista retorna com registros duplicados, ou seja, o retorno são 4 itens e no banco de dados contém apenas dois, sendo uma duplicação para cada registro.
Porém no objeto finCxaTransacaoOrigem.getFinCxaPlanoLctos() que contém apenas um registro no banco, essa lista retorna apenas um registro, sem duplicações...
Pesquisei diversos exemplos onde o pessoal soluciona usando Set ao invés de List para a relação OneToMany, isso soluciona o meu problema, mas em outras situações não me permite inserir valores duplicados quando necessário.
Gostaria de saber porque o JPA está duplicando os registros e se existe alguma solução?
Comment: Cara vou te dar uma sugestão de `debug`, adiciona um arquivo `properties` do `log4j` na pasta `resources` do seu projeto e ativa o log de `sql` full do `Hibernate`, para ver se esta executando dois `inserts`....
Answer: A solução que fiz para o meu problema foi converter a lista para um Set<> e depois adicionar novamente para a List e retorna-la. Sim  e considero uma gambiarra, assim que possível vou realizar a sugestão repassada e usar o log4j.
Grato.
Set finCxaPlanoLctos = new HashSet<>(finCxaTransacaoGrupoReturn.getFinCxaTransacaoDestino().getFinCxaPlanoLctos());
            finCxaTransacaoGrupoReturn.getFinCxaTransacaoDestino().getFinCxaPlanoLctos().clear();
            finCxaTransacaoGrupoReturn.getFinCxaTransacaoDestino().getFinCxaPlanoLctos().addAll(finCxaPlanoLctos);


Can I trigger a form submit from a controller?

Question: I'd like to do a traditional form submit from within a controller. The scenario is that I want to hit a route on my web server and redirect to its response, which I can do with a regular form in HTML, but I also want to do some validation on its fields when the submit button is pressed, and if the validation fails, I don't want to do the route.
I'm aware of ng-valid, but I only want the validation to take place when the button is hit.
Is there a way to conditionally do a form submit from within a controller?
Answer: You can add submit method to a FormController. I did so:
<form ng-form-commit action="/" name='payForm' method="post" target="_top">
    <input type="hidden" name="currency_code" value="USD">
    <button type='button' ng-click='save(payForm)'>buy</button>
</form>

.directive("ngFormCommit", [function(){
    return {
        require:"form",
        link: function($scope, $el, $attr, $form) {
            $form.commit = function() {
                $el[0].submit();
            };
        }
    };
}])

.controller("AwesomeCtrl", ["$scope", function($scope){
   $scope.save = function($form) {
     if ($form.$valid) {
         $form.commit();
     }
   };
}])

Answer: Did you try to use the ng-submit directive on your form? You may return true/false after your validation.
Controller
app.controller('MainCtrl', ['$location', function($scope, $location) {
  $scope.submit = function(user) {
    var isvalid = true;
    // validation
    if (isvalid) {
        $http.get('api/check_something', {}).then(function(result) {
            $location.path(result.data);
        });
        return true;
    }
    return false; //failed
  }
});

Html (you must not have an action attribute)
<form name="formuser" ng-submit="submit(user)">
    <input type="text" ng-model="user.firstname" />
    <input type="text" ng-model="user.lastname" />
    <button type="submit">Submit</button>
</form>

Comment: I had that thought, but I needed to specify an action.
Comment: This is opposite of what OP asks. This adds a sort of a 'hook' before html form submission is triggered. OP asks about how to trigger that form submission from angular controller, not how to add a hook to already running submission.
Answer: This is 'not the Angular' way to do it but you can submit the form using vanilla javascript. For example you can give the form an id and do:
document.getElementById('myForm').submit()
or if you have a submit button you can click it:
document.getElementById('myForm-submit').click()
I found that the first one did not keep the data bindings (I was using it on a project with a JQuery widget that had no Angular alternative), but the second one kept the bindings. I assume this has to do with how the JQuery widget was written.
You can see more about triggering forms with vanilla JS here:
How to submit a form using javascript?
Comment: this will not trigger ng-submit
Answer: $scope.payForm.$setSubmitted();

Sets the form to its $submitted state. This will also set $submitted on all child and parent forms of the form
https://docs.angularjs.org/api/ng/type/form.FormController#$setSubmitted
Answer: How about just out-right disabling the submit button until the form is valid:
<button type="submit" ng-disabled="form.$invalid">Submit</button>

Take a look at this similar question I had:
AngularJS Form Validation with Directives - "myform.$valid" not quite right for me
Answer: Expanding from @ReklatsMasters's answer, if you want to change a value before submitting the form, you could do like so...
<form ng-form-commit action="/" name='payForm' method="post" target="_top">
    <input type="hidden" id="currency_code" name="currency_code" value="USD">
    <button type='button' ng-click='save('GBP', payForm)'>buy</button>
</form>

.directive("ngFormCommit", [function(){
    return {
        require:"form",
        link: function($scope, $el, $attr, $form) {
            $form.commit = function($newCurrency) {
                $el[0].querySelector('#currency_code').value = $newCurrency;
                $el[0].submit();
            };
        }
    };
}])

.controller("AwesomeCtrl", ["$scope", function($scope){
   $scope.save = function($newCurrency, $form) {
     if ($form.$valid) {
         $form.commit($newCurrency);
     }
   };
}])


SQL - Como listar apenas os registros que apresentam mais de uma tabela filha

Question: Eu preciso listar os nomes de funcionários que possuem dois ou mais filhos (são listados duas ou mais vezes) no seguinte select, mas não faço ideia de como.
select f.NomeFunc as "Funcionário", d.NomeDep as "Filhos"
from Funcionario f
inner join Dependente d
on f.ID_Func = d.ID_func

Alguma dica?
Comment: Utilize a cláusula GROUP BY / COUNT juntamente com a cláusula HAVING. A propósito, me parece que utilizou erroneamente a expressão "tabela filha" em sua pergunta.
Answer: Para você chegar neste resultado, conforme foi comentado, você precisa primeiro fazer um agrupamento e depois usar o HAVING para filtrar os resultados. Sua consulta ficaria da seguinte forma:
select f.NomeFunc as "Funcionário"
from Funcionario f
inner join Dependente d
on f.ID_Func = d.ID_func
GROUP BY f.NomeFunc
HAVING COUNT(*) > 1


convergence in law exercise

Question: I have this exercise
Let $(Xn)$ be a sequence of r.v whose distribution is defined for $n \in N^*$ by
$P\left(X_n=1-\frac{1}{n}\right)= P\left(X_n= 1+\frac{1}{n}\right) =  \frac{1}{2}$
Study its convergence in law.
======================================
The solution that I find but can't understand
For any $\epsilon > 0$ there exists an integer $N = N(\epsilon)$ such that for $n > N$ we have $\frac{1}{n} < \epsilon $ and then :
$\mathbb{P} (|X_n -1| < \epsilon) =\frac{1}{2} +\frac{1}{2}= 1$
Therefore, $\mathbb{P}(|X_n - 1| < \epsilon)  \rightarrow 1$ when $n \rightarrow  \infty $ which shows that the sequence (Xn) converges in probability to the certain r.v. $X = 1$, and thus also in law since the limit is a constant.
However, $\mathbb{P}(X_n = 1) = 0$ for any integer n and thus $\mathbb{P}(X_n = 1) \rightarrow 0$ when
$n \rightarrow \infty$ while $\mathbb{P}(X = 1) = 1$. Thus, one must be careful in using sufficient conditions for convergence in law
======================================
My questions are :
1-how did they find that $\mathbb{P} (|X_n -1| < \epsilon) =\frac{1}{2} +\frac{1}{2}= 1$.
2-Which sufficient condition is not checked .
Answer: 1- $\mathbb P(\lvert X_n -1 \rvert \leq 1/n) = 1$. Hence given $\varepsilon>0$, we have $\mathbb P(\lvert X_n-1\rvert <\varepsilon)\to 1$.
2- Convergence in probability implies convergence in distribution, and the converse is true in the special case $X_n \Rightarrow c$, for some constant $c$. Here, what they are talking about is how $\mathbb P(X_n = 1) = 0$, yet $\mathbb P(X_{\infty}=1) = \mathbb P(1=1)=1$. This is okay because $X_n \Rightarrow X_{\infty}$ means $F_{X_n}(x) \to F_{X_{\infty}}(x)$ for every point of continuity $x$ of the distribution function of $X_{\infty}$. Here, because $\mathbb P(X_{\infty}=1) >0$, $1$ is a point of discontinuity of the distribution function of $X_{\infty}$.
Comment: Thank you for your answer, if you can explain to me,  why do have $p(X_\infty=1)>0 $, and  why 1 is a point of discontinuity @Andrew Zhang
Comment: @bntaous I am using $X_{\infty}$ to denote the limit, which is 1. So $\mathbb P(1 = 1) = 1>0$. For any random variable $X$, the distribution function $F_X$ is discontinuous at $x$ if and only if $\mathbb P(X= x)>0$.
Comment: Thank you for your help  @Andrew Zhang

convergence in law exercise


Controls on form private?

Question: Can I access the control variables on a form?  Eg:
MyForm form = new MyForm();
form.button1.Visible = True;   // why doesn't this work?

Comment: Have you tried it?  This strikes me as a question that would take less time to test than it took to type into StackOverflow...
Comment: can't see a reason why this question is closed
Answer: You need to set public or internal modifier of control via Modifier property windows or open designer.cs and set the access modifier.
Comment: Good to see someone has just answered the question instead of engaging in all this negativity.
Answer: bool SearchAllChildren = true;
(this.Controls.Find("button1", SearchAllChildren )[0] as Button).Visible = true;

you can set SearchAllChildren to false so that it returns only controls on the form not nested controls (Controls in Other Controls)
Comment: Does this work even if the control is `private`?
Comment: Yes @CJ7 it does work on `private` controls too.

Controls on form private?


How to Configure WebForm to Allow Users to Choose Which CiviCRM Campaign to Contribute to?

Question: Our non-profit currently has a basic donation page via a CiviCRM Contribution page. We would like to add the ability for the user to select which campaign the contribution is directed to.
The Webform CiviCRM Integration Module seems like a necessary component. When configuring a webform, you may direct the contribution to a pre-existing contribution page, but without the ability to expose this to the user. I also looked at apply the Webform Conditional module, but did not see anything that would lead to my desired outcome.
I appreciate any insights in how to create a donation page which provides the user the option to select CiviCRM campaigns.
Comment: Note that webform_conditional is only for webform v3. Webform v4 has the conditional features built-in.
Answer: You can actually do this without Webform-CiviCRM if you like:

Set up your campaigns in CiviCampaign
Create a new profile to add a field to (or from the Profiles page, click "Fields" beside an existing profile to add a new field there)
Add a new "Campaign" field to the profile you are working in (this will list all active campaigns in the profile)
Add the profile to the Contribution Page in question (note: if you added the field to an existing profile it may already be on the Contrib Page)
Answer: You do not need the webform-civicrm module for this, you can use a profile to expose the campaign field to the contribution form. This will add a select dropdown to your form that lists all active, current campaigns.
But if you wish to use webform-civicrm integration, the feature exists there as well. It has the advantage over profiles in that you can configure which campaigns show up in the list, and even rename them on the form if you wish to create more descriptive "user-friendly" names for them.
To add the field, choose "user select" on the contribution campaign field in the civicrm tab of the webform. To configure its options, go back to the webform tab and click "edit" on the campaign field.


Throttle download traffic in apache for all users

Question: Lets say I subdomain called largefiles.domain.com This is on a dedicated server and I can change any configuration. Server runs Apache/2.2.3 (CentOS)
How do i restrict all file downloads to just 10Kbps for every file downloaded from the webserver? What is the easiest solution to implement this for the entire subdomain?
Answer: I would go for mod_bw:
Example: Limit every user to a max of 10Kb/s on a vhost :
<code><Virtualhost *>
  BandwidthModule On
  ForceBandWidthModule On
  Bandwidth all 10240
  MinBandwidth all -1
  Servername www.example.com
</Virtualhost>
</code>
Comment: The documentation says:
ForceBandWidthModule [On|Off]
    By default, the mod wont catch every request.
    If you enable it, every request will be processed by the mod.
Comment: Does not work with AJP.
Answer: mod_cband should fix this for you.
See this nice tutorial: http://www.howtoforge.com/mod_cband_apache2_bandwidth_quota_throttling


Generating a depth map from a point cloud using Python

Question: I am working on a project where I need to generate depth images from a point cloud. While I have come across examples in the literature that explains how to create a point cloud from a depth map, I'm specifically looking for guidance on the reverse process.
Can someone please provide insights or suggestions on how to create a depth map from a point cloud with Python programming language? Any relevant information, techniques, or resources would be greatly appreciated.
Comment: This question is too broad for Stack Overflow. "I want to do X" is not a question. Please ask a _specific_ question. Having attempted to solve your problem yourself usually helps in formulating a good question. See [what's on-topic here](/help/on-topic), [ask], the [question checklist](//meta.stackoverflow.com/q/260648/843953), and how to provide a [mre].
Comment: While I understand the concern raised by @PranavHosangadi, My question is not more general than other questions asked her. Please see https://stackoverflow.com/questions/64094463/how-can-i-generate-a-point-cloud-from-a-depth-image-and-rgb-image
Comment: If you want to do the reverse maybe you can try projection simply?
I had projection related answer: https://stackoverflow.com/questions/43644656/converting-3d-point-cloud-to-a-2d-gridmap-on-python/73913607#73913607
Answer: First of all, you need the intrinsic matrix of the camera. You can find fx, fy, cx, and cy values from the camera intrinsic matrix.
Example intrinsic matrix:
<code>    # [ Fx, 0,  Cx,  Fx*-Tx ]
    # [ 0,  Fy, Cy,  0      ]
    # [ 0,  0,  1,   0      ]
</code>
Here is an example of creating a point cloud from a depth map.
<code>    # read the depth image here and define intrinsic values

    fx = FX_DEPTH
    fy = FY_DEPTH
    cx = CX_DEPTH
    cy = CY_DEPTH

    x = (u - cx) / fx
    y = (v - cy) / fy
    z = image[v, u]
    x *= z
    y *= z
    z = z
    print(f"x: {x} y: {y} z: {z}")
</code>
But you are looking for a Python example of the reverse process. Here is the code of the reverse process:
<code>    # read a point from the point cloud and define intrinsic values

    fx = FX_DEPTH
    fy = FY_DEPTH
    cx = CX_DEPTH
    cy = CY_DEPTH

    u = (x / z) * fx + cx
    v = (y / z) * fy + cy
    w, h = image.shape
    image[v, u] = z
    print(f"Position: {u} {v} Value:{image[u, v]}")
</code>
You can create the depth map if you iterate this code piece for all points.


Angular mat-table inline filter with drop down

Question: How to get a drop down in the inline filter with unique values from the grid. For example my JSON returns 100 rows of Person object. That has 5 columns. I want to filter all these columns. I want 3 columns to be text box and other 2 columns to be drop down. Here in the example there are 4 rows, I want to display only the 3 unique values (i.e. 'Dog', 'Cat' and 'Lizard') in the Pet filter and that should be a drop down. (Note: don't want to display 'Dog' twice the drop down). And upon selection of a value from the drop down, the table should refresh accordingly. Similarly for Active column where it should have only 2 values (i.e. true and false) in the drop down.
Stackblitz example
createFilter(): (data: any, filter: string) => boolean {
    let filterFunction = function(data, filter): boolean {
      let searchTerms = JSON.parse(filter);
      return data.name.toLowerCase().indexOf(searchTerms.name) !== -1
        && data.id.toString().toLowerCase().indexOf(searchTerms.id) !== -1
        && data.colour.toLowerCase().indexOf(searchTerms.colour) !== -1
      //&& data.active.toLowerCase().indexOf(searchTerms.active) !== -1   ??? How to write this ???
        && data.pet.toLowerCase().indexOf(searchTerms.pet) !== -1;
    }
    return filterFunction;
  }

Comment: To the person who asked to Close - Sir/Madam I see you Close all my questions. Can you please tell me what wrong in this question?
Answer: Got the answer. updated stackblitz example
this.petList = Array.from(new Set(this.people.map(ele=>ele.pet)));

<ng-container matColumnDef="pet">

      Pet
      <mat-form-field class="filter" floatLabel="never">
        <mat-label>Search</mat-label>

        <mat-select  placeholder="Select" [formControl]="petFilter">
            <mat-option value="">Select</mat-option>
            <mat-option *ngFor="let item of petList" value="{{ item | lowercase }}">
                {{ item }}
            </mat-option>
        </mat-select>

      </mat-form-field>

    {{person.pet}}
  </ng-container>


How can I create new Task( async( ) => { return new T( ); } );?

Question: I need to create a function which will return a task that will be executed at another time.
I would like for that task to return a value (preferably through awaiting it).
I would also like to be able to await methods/functions within that task.
When I try to create a simple conceptual function which should do what I want, I get a red-line error message :
private static Task<object> FooGet( ) {
    return new Task<object>( async ( ) => {
        await asyncBar( );
        return new object( );
    } );
}

The error reads : Cannot convert lambda expression to type 'object' because it is not a delegate type
As soon as I remove the async keyword from the lambda, everything's hunky dory.
How can I fix this? Can I even fix this?
Answer: I found the answer after digging a bit more. In case someone runs into this precise issue the answer already exists.
Shorthand :
private static Task<object> FooGet()
{
    return new Task<object>(async () =>
    {
        await asyncBar();
        return new object();
    });
}

becomes
private static Task<object> FooGet()
{
    return ((Func<Task<object>>)(async () =>
    {
        await asyncBar();
        return new object();
    }))();
}

Comment: Since you have added to another answer, I think it is perfectly OK to get upvotes. However if you are determined not to receive them, you can always add an answer as community wiki, which mostly removes your ownership from the post.
Comment: @halfer I... have literally no idea what you are talking about. Can I have some context, please?
Comment: See the edit I made to your answer - you asked people to upvote another answer and explicitly not your own. I edited that out since I felt it was excessive meta-commentary, but in any case I thought you were being rather unfair to yourself, and that your own question merited upvotes if people wish to give them.
Comment: @halfer The world literally.
Answer: you need to explicitly cast it to Func<Task<object>> or if you want to keep things more readable you could refactory this as
private static Task<object> FooGet( ) {
    return new Task<object>(innerTask);
}

private async static Task<object> innerTask() {
    await asyncBar( );
    return new object( );
}

private static async Task asyncBar( ){
}


SAP Fiori: Show 'My Leave Requests' in days instead of hours

Question: When requesting a leave in Fiori the pop up shows the away time in hours instead of days:
Is there a possiblity that instead of for example 15,00 hours the pop-up shows 2 days?
Answer: Beware that many stuff in Fiori applications can also be customized by customizing your default SAP application. If your default in leave request is in hours, then that is what this Fiori app will show. Change it to days and that will be what Fiori will show.
In case you have a specific requirement to make this deviate solely in the app, then indeed you need either an extension point or create a custom implementation.
Here some additional links:

Preffered method
Old-fashioned
Comment: great links @Mattti.b :-)
Answer: From what it looks like, you are asking to change a standard, delivered app?
If so, it is only possible to change it, if an Extension Point is provided at the desired place and then adapt the extended code. Check the documentation for App Extensibility: My Leave Requests.
In any case, if you haven't gone through the documentation for the app itself, with the possible customizations, check the My Leave Requests Fiori app documentation
Comment: Is is possible to completely replace a view or controller. This will however mean that your app cannot easily be upgraded. With the extension point that is ensured.


Como verificar quantas vezes aparece o número 2 dentro de uma matriz?

Question: Meu objetivo neste algoritmo é encontrar quantas vezes aparece o número 2 dentro de uma matriz 8x3.
Meu resultado até o momento está assim:
from collections import Counter
import time
import numpy as np

m = int(input('Quantas linas? '))
n = int(input('Quantas colunas? '))

input("Será aceito somente números entre -20 e 10.\n ... \nPrecione a tecla ENTER para continuar!\n")
time.sleep(2)

matrizA = list()
for c in range(1, m + 1):
    linha = list()
    for i in range(1, n + 1):
        while True:
            try:
                valor = int(input(f'Digite o {i}º elemento da {c}ª linha: '))
                break
            except ValueError:
                print('\033[31mValor INVÁLIDO! Digite apenas valores inteiros!\033[m')
        linha.append(valor)
    matrizA.append(linha)

matriz = np.array(matrizA)
print(f'\033[32mA matriz gerada é:\n{matriz}\033[m')

c = Counter(matrizA)
print(c[2])

Eu consegui fazer a matriz e tentei usar o import Counter para retornar o resultado da repetição do número 2 dentro da matriz. Porém o resultado não saiu como eu queria.
Answer: Sua matrizA é na verdade uma lista de listas: é uma lista na qual cada elemento é outra lista (e essas sim tem números).
Então basta percorrer as "linhas" (na verdade, as listas), e depois percorrer os elementos de cada linha e ver se o valor é 2:
cont = 0
for linha in matrizA:
    for num in linha:
        if num == 2:
            cont += 1

Mas para obter a contagem de um único elemento você também pode usar o método count:
cont = 0
for linha in matrizA:
    cont += linha.count(2)

E por fim, pode usar sum (que soma uma série de valores) juntamente com uma  generator expression, bem mais sucinta e pythônica:
cont = sum(linha.count(2) for linha in matrizA)

Answer: Pode utilizar a biblioteca numpy, por exemplo:
np.count_nonzero(matriz == 2)

Answer: Não conheço muito de bibliotecas Python, mas se o seu objetivo for apenas descobrir quantas vezes um determinado número aparece dentro de uma matriz, você pode criar a função abaixo;
def Repete(matriz, identificador):
    repetiu = 0
    for indice in range(0, len(matriz)):
        repetiu+=1 if matriz[indice] == identificador else repetiu

    return repetiu

Espero que isso tenha ajudado de alguma forma.


Countrows in multiple column based on partial text value

Question: For a project I need to be able to count the number of rows in a file, based on a text value in one of eight defined columns.
I want to count a row when one of the "Linked Issues" columns contains a text value that starts with "THGRW-".
I tried using the COUNTROWS function combined with FILTER for only one column, which looks like this:
Episode without SM =
COUNTROWS(FILTER('Sheet1', 'Sheet1'[Linked Issues.1] >= "THGRW-000"))
For multiple columns I wanted to just sum (using the + operator) the countrows functions, but already this function for a single column does not give me a result.
I attached a screenshot of what the sheet looks like.
Answer: You can do something like this where you pipe predicates that form an OR. You will need to type out a lot, here is a snippet:
Count =
VAR _string = "THGRW-"
RETURN
COUNTROWS (
    FILTER (
        Tbl,
        LEFT( Tbl[Linked Issues.1], 6 ) = _string
         || LEFT( Tbl[Linked Issues.2], 6 ) = _string
         ...
         || LEFT( Tbl[Linked Issues.8], 6 ) = _string
    )
)

Comment: Hi Marcus, when I try this I get a (blank) result if I add the measure to a card visual. Count =
VAR _string = "THRGW-"
RETURN
COUNTROWS (
    FILTER (
        'Sheet1',
        LEFT( 'Sheet1'[Linked Issues.1], 6 ) = _string
        || LEFT( 'Sheet1'[Linked Issues.2], 6 ) = _string
...
        || LEFT( 'Sheet1'[Linked Issues.7], 6 ) = _string
        || LEFT( 'Sheet1'[Linked Issues.8], 6 ) = _string
    )
)
Comment: You need to write the expressions for columns 3-7 based on this snippet.
Comment: I did, so for every column I changed the 'x' in 'Sheet1'[Linked Issues.x]. The code does not give any errors, but still returns a blank.
Comment: I see. The formula should work just fine. Check your external filters?
Comment: Found the issue, which is a typo: The string should've been 'THGRW-'. But still have another: It counts for the first column (which in my source file results in 50, which is correct. But if I check for column 2 to 8, the formula still returns a blank.
Comment: Aha! My bad. There is no reason the formula should return a blank for your other columns. It should count all rows where at least one of your defined columns start with this string. If the data is poorly cleaned you may get wrong results.
Answer: Your screenshot makes me think you missed a step in PowerQuery. Instead of having "LinkedIssues1", "LinkedIssues2"... etc, you should have just (Key, LinkedIssue) as your table and then you just do the count from there.


How do I change my guild slash commands to global commands?

Question: I would like to switch my guild commands to global commands. They were usable in one specific guild, but now I would like all the servers my bot is in to use these commands. I have provided my code below:
client.once('ready', () => {
    console.log('All set and ready to go!')
    let guild = process.env.GUILD

    const start = new SlashCommandBuilder()
        .setName('start')
        .setDescription('Start a new game lobby')
        .addStringOption(options => options
            .setName('game')
            .setDescription('The kind of game you want to start')
            .setRequired(true)
            .addChoices(
                {
                    name: 'Never Have I Ever',
                    value: 'nhie'
                },
                {
                    name: "Would You Rather",
                    value: 'wyr'
                }
            )
        )

    client.application.commands.create(start, guild)

    const end = new SlashCommandBuilder()
        .setName('end')
        .setDescription('Ends the current game')

    client.application.commands.create(end, guild)
})

Answer: To register commands globally, you need to convert your SlashCommandBuilder into JSON format and then pass it into the create function.
client.application.commands.create(start.toJSON());

Replace 'start' with the constant name declared for each SlashCommandBuilder. Please note that there might be a delay in deploying commands globally as it can take some time.


From HWND to control

Question: Im using the FindWindow method from user32.dll to find a window and get the handle, but is it possible to get the form control from the handle? and the use it like an ordinary form? Example:
int myhwnd = FindWindow(null, "MyWindow");
form myform = SomeMagic.GetFormFromHandle(myhwnd);
myform.Visible = false;

or do I have to continue to use the methods in user32.dll to send a message to the window?
Answer: If it's a managed window (you've created it with System.Windows.Forms, and it has inherited from System.Windows.Forms.Control) you can get a reference to the Control object with
Control.FromHandle(myIntPtr);

Then you just get the parent of the control until you get the form.
If not, you can't get a Control object, what you can do though is to is to create a NativeWindow, and assign the IntPtr handle to the object with the AssignHandle. That will at least give you some access to the WndProc, and similar, but that's it.
Answer: Have you tried Control.FromHandle()? Forms are (inherit from) Controls. If you hit a nested control, you'll have to search up through its parents until you hit your Form.
This assumes there actually is a Form somewhere, and you've just used the user32 methods to locate its HWND.
Answer: It's very difficult to wrap a Form class around Win32 window handle. There is no full fledged implementation provided by Microsoft. So, you have to use Native functions only to communicate with a given handle.
Answer: If the window belongs to your application you can use Control.FromHandle Method. Otherwise you will have to continue using win api. For example to hide the window you need to call ShowWindow Function.

From HWND to control


How to manage containerized applications settings?

Question: I have a bunch of containerized java applications on OpenShift server. Each has an applications.properties file where described the url's to databases and http servers.
So if I want to change one of that urls, I have to change 20+ application.properties files and redeploy 20+ applications.
How to sipmlify app properties management?
Answer: I suggest to integrate applications with config server, e.g. it can be zookeeper. In case of spring cloud applications see spring-cloud-zookeeper-config, so it provide abilities to configure application settings individually or with common settings.
In addition, it provide multitenancy capabilities via different namespaces:
<code>spring:
  cloud:
    zookeeper:
      config:
        enabled: true
        root: config/${spring.application.namespace}
</code>


Integrate out (covariance) matrix in Normal-Wishart distribution

Question: In Gelman's Bayesian Data Analysis Chapter 3.6, he introduces the multivariate normal with unknown mean and variance, with the priors
$\Sigma\sim \text{Inv-Wishart}_{\nu_0}(\Lambda_0^{-1})$
$\mu\rvert \Sigma \sim N(\mu_0, \Sigma/\kappa_0)$
and the joint prior
$p(\mu, \Sigma)\propto \lvert \Sigma\rvert^{-((\nu_0+d)/2+1)}\exp\Big(-\frac{1}{2}\text{tr}(\Lambda_0\Sigma^{-1})-\frac{\kappa_0}{2}(\mu-\mu_0)'\Sigma^{-1}(\mu-\mu_0)\Big)$
Gelman then states that the (posterior) marginal is multivariate $t$ without elaboration.
In a paper that I found (A Bayes Approach for Combining Correlated Estimates - Seymour Geisser), Geisser had the following steps, also without elaboration (notations, parameterisation and context are different from Gelman, but a similar integration step is involved).
$p(\mu, \Sigma^{-1})\propto \Big\lvert \Sigma^{-1}\Big\rvert ^{(n-d-1)/2}\exp\Big(-\frac{1}{2}\text{tr}\Big(\Sigma^{-1}\sum_{j=1}^n (\mathbf{x}_j-\mu\mathbf{e})(\mathbf{x}_j-\mu\mathbf{e})'\Big)\Big)$
Integrating out $\Sigma^{-1}$ yields
$p(\mu)\propto \Big\lvert \sum_{j=1}^n(\mathbf{x}_j-\mu\mathbf{e})(\mathbf{x}_j-\mu\mathbf{e})'\Big\rvert ^{-n/2}$
The result can be further massaged to yield the $t$ density, but my question is specifically on the integration step only. The result $p(\mu)$ looks simple but I'm not sure how it's carried out.
Question: How do I obtain the marginal distribution of $p(\mu)$ by integrating out $\Sigma$? Any references to similar matrix integrations will be great. Thank you in advance!
Answer: First, notice that, if you use some properties of the trace operator,
\begin{align*}
p(\mu, \Sigma) &\propto \lvert \Sigma\rvert^{-((\nu_0+d)/2+1)}\exp\Big(-\frac{1}{2}\text{tr}(\Lambda_0\Sigma^{-1})-\frac{\kappa_0}{2}(\mu-\mu_0)'\Sigma^{-1}(\mu-\mu_0)\Big) \\
&= \lvert \Sigma\rvert^{-((\nu_0+d)/2+1)}\exp\Big(-\frac{1}{2}\text{tr}(\Lambda_0\Sigma^{-1})-\text{tr}\left(\frac{\kappa_0}{2}(\mu-\mu_0)(\mu-\mu_0)'\Sigma^{-1}\right)\Big) \\
&= \lvert \Sigma\rvert^{-((\nu_0+d)/2+1)}\exp\Big(-\frac{1}{2}\text{tr}\left\{\Lambda_0 + \kappa_0(\mu-\mu_0)(\mu-\mu_0)' \right\} \Sigma^{-1}\Big) \\
&= \lvert \Sigma\rvert^{-\left(\frac{[\nu_0+1] + d+1}{2}\right)}\exp\Big[-\frac{1}{2}\text{tr}\left( \Psi \Sigma^{-1} \right)\Big] \\
&= \lvert \Sigma\rvert^{-\left(\frac{\nu_1 + d+1}{2}\right)}\exp\Big[-\frac{1}{2}\text{tr}\left( \Psi \Sigma^{-1} \right)\Big]
\end{align*}
if you set $\Psi$ matrix to $\Lambda_0 + \kappa_0(\mu-\mu_0)(\mu-\mu_0)' $ and $\nu_1 = \nu_0 + 1$. So if you integrate with respect to $d \Sigma$, which is kind of misleading because all of the elements aren't unique, you'll get
$$
p(\mu) \propto \int \lvert \Sigma\rvert^{-\left(\frac{\nu_1 + d+1}{2}\right)}\exp\Big[-\frac{1}{2}\text{tr}\left( \Psi \Sigma^{-1} \right)\Big] d \Sigma = \frac{\Gamma_p(\nu_1/2) 2^{\nu_1p/2} }{\text{det}[\Psi]^{\nu_1/2}}.
$$
Technically, $d \Sigma$ is short hand for integrating with respect to the diagonal and the lower-half elements of $\Sigma$. This is because you're integrating over the space of positive definite, symmetric matrices. I can skip a lot of the details because I am just recognizing the Inverse-Wishart density and then looking up the normalizing constant on Wikipedia.
Edit:
Just re-reading your question now and it looks like you're more interested in the marginal posterior. This is the marginal prior. You can use the same move, but I'll add the details in a little bit.
Edit Number 2:
There are a few extra difficulties that I wanted to mention with the recognition of the $t$ density. This site doesn't have many answered questions like this, so I figured I could do it all out.
\begin{align*}
p(\mu) &\propto \text{det}\left(\Lambda_0 + \kappa_0(\mu-\mu_0)(\mu-\mu_0)'\right)^{-\frac{\nu_1}{2}} \\
&= \text{det}[\Lambda_0]^{-\frac{\nu_1}{2}} \text{det}\left(1 + \kappa_0(\mu-\mu_0)' \Lambda_0^{-1} (\mu-\mu_0)  \right)^{-\frac{\nu_1}{2}} \tag{*} \\
&\propto \text{det}\left(1 + \kappa_0(\mu-\mu_0)' \Lambda_0^{-1} (\mu-\mu_0)  \right)^{-\frac{\nu_1}{2}} \\
&= \text{det}\left(1 + \frac{1}{\nu_1 - p}(\mu-\mu_0)' \left[\frac{1}{[\nu_1 - p] \kappa_0}\Lambda_0\right]^{-1} (\mu-\mu_0)  \right)^{-\frac{[\nu_1-p]+p}{2}} \\
&\propto t_{\nu_1 - p}\left(\mu_0, \frac{1}{[\nu_1 - p] \kappa_0}\Lambda_0\right).
\end{align*}
where the line marked by the * follows by the matrix determinant lemma.
You might think that it's weird you lost a few degrees of freedom, but you can convince yourself it's true if you check the variance is what it should be. The variance of a $t_{\nu_1 - p}\left(\mu_0, \frac{1}{[\nu_1 - p] \kappa_0}\Lambda_0\right)$ is
$$
\frac{1}{[\nu_1 - p] \kappa_0}\Lambda_0 \frac{\nu_1 - p}{\nu_1 - p-2} = \frac{1}{[\nu_1 - p-2] \kappa_0}\Lambda_0
$$
which is the same as the one we find with the law of total variance:
$$
E\left(\text{Var}\left[\mu \mid \Sigma \right]\right) = E[\Sigma]/\kappa_0
= \Lambda_0 \frac{1}{\kappa_0[\nu_0 - p - 1]}.
$$
Comment: Thank you! This is a sufficient answer. In my case, I simply did not recognise the integrand as a known distribution which leads to the integration result being the normalising constant. Your steps made it very clear, cheers!


Proper backquoting and variable capture with labels+macrolet within defmacro

Question: I'm writing a small special-purpose language in Common Lisp using a defmacro. I cannot figure out the proper backquote procedure to have a variable defined in a top-level let statement, shadowed in a nested macrolet, and returned in a nested labels, all point to the same symbol.
Here's some small example code that shows the problem:
(defmacro with-keylang (&body body)
  (let ((keyblank-size-x (gensym)))
    `(let ((,keyblank-size-x 42))
       (labels ((keyblank-size-x ()
                  ,keyblank-size-x))
         (macrolet ((with-keyblank-size-x (size-x &body body)
                      `(let ((,',keyblank-size-x ,size-x))
                         ,@body)))
           ,@body)))))

CL-USER>
(with-keylang
  (print (keyblank-size-x)))

42
42

All is well so far.
CL-USER>
(with-keylang
  (with-keyblank-size-x 24
    (print (keyblank-size-x))))

;Compiler warnings :
;   In an anonymous lambda form: Unused lexical variable #:G123171

42
42

There's the problem. I want the symbol representing keyblank-size-x to be shadowed with the value 24, and this is not happening.
I have a feeling that the ,', backquote pattern isn't proper for this case, as this quotes the symbol representing keyblank-size-x, and is therefore not eq. But if I try ,,, it doesn't work, and I get this interesting compiler error:
While compiling WITH-KEYBLANK-SIZE-X :
Illegal reference to lexically defined variable #:G123192.
   [Condition of type CCL::COMPILE-TIME-PROGRAM-ERROR]

EDIT:
The keyblank-size-x variable was lexically scoped, and I wanted dynamic scope for this particular case. So here's the rewrite declaring the keyblank-size-x variable to have dynamic scope:
(defmacro with-keylang (&body body)
  (let ((keyblank-size-x (gensym)))
    `(let ((,keyblank-size-x 42))
       (declare (special ,keyblank-size-x))
       (labels ((keyblank-size-x ()
                  ,keyblank-size-x))
         (macrolet ((with-keyblank-size-x (size-x &body body)
                      `(let ((,',keyblank-size-x ,size-x))
                         (declare (special ,',keyblank-size-x))
                         ,@body)))
           ,@body)))))

And the test code:
CL-USER>
(with-keylang
  (with-keyblank-size-x 25
    (with-keyblank-size-x 21
      (print (keyblank-size-x)))
    (print (keyblank-size-x)))
  (print (keyblank-size-x)))

21
25
42
42

Comment: rebinding the variable has no effect, since the LABELS defined function has a different lexical binding for that.
Answer: If we fully expand the code (here using the Walk command in LispWorks):
(LET ((#:G19508 42))
  (LABELS ((KEYBLANK-SIZE-X () #:G19508))
    (MACROLET ((WITH-KEYBLANK-SIZE-X (SIZE-X &BODY BODY)
                 `(LET ((#:G19508 ,SIZE-X))
                    ,@BODY)))
      (LET ((#:G19508 24))
        (PRINT (KEYBLANK-SIZE-X))))))

Rebinding #:G19508 has no effect and can't have. The function keyblank-size-x has a different lexical binding. This is just the usual effect of lexical binding.


How many odd days are there in 1600 years ? I calculated it but I guess the result is wrong?

Question: I had to calculate the number of odd days in 1600 years. I have read the answer to be equal to 0. But I don't get it to equal to 0.
This is the way I am calculating the number of odd days in  1600 years :
<code>1600 years = 24 x 16 = 384 leap years   (100 years = 24 leap years)
(because 100 years have 24 leap years)
1 leap year = 2 odd days (52 weeks + 2 odd days)
384 leap years = 384 x 2 = 768 odd days --(A)
1600 years = 1600 - 384 = 1216 ordinary years
1 ordinary year = 1 odd day (52 weeks + 1 odd day)
1216 ordinary years = 1216 x 1 = 1216 odd days--(B)

Total number of odd days = (A) + (B) = 768 + 1216 = 1984 odd days in 1600 years

and 1984 is not divisible by 7 !
</code>
Am I making a mistake ? If yes,what is it ?
Comment: what is an odd day?
Comment: Is today an "odd day", for example? Why/why not?
Comment: @Khromonkey In a year there a 365 days. It means 52 weeks + 1 odd day
Comment: My attempt at making sense is that an "odd day" is a day of the week that occurs an odd number of times. In a non-leap year with 52weeks+1day, six of the seven days of the week occur 52 times (an even number), while one of them occurs 53 times (an odd number). So the number of "odd days" in a year is the number of {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday} that occur an odd number (53) of times. [I haven't thought about 1752 when the Gregorian change happened. :-)]
Comment: @HenningMakholm I guess I had the incorrect knowledge.I knew odd day as 52 weeks + 1 .
Answer: Remember that a year divisible by $400$ is a leap year.  Although $2100$ will not be a leap year. $2400$ will be.
So in $400$ years there are precisely $97$ leap years.
And yes, the calendar repeats every $400$ years, so the number of days in $1600$ years is divisible by $7$. For $400$ years, to the $(400)(364)$ days,  just add $400+100-3$ (ordinary advance by $1$ day, plus 100 for the leap years sort of, minus $3$ for the multiples of $100$ that are not multiples of $400$).  Then multiply by $4$. So for $1600$ we get $4(500-3)$ "additional" days. Your $1984$ was essentially computed correctly, except that we need $4$ additional days for the $4$ multiples of $400$.
Comment: As this answer shows, there are 497 odd days in 400 years, which is divisible by 7, so the days of the week repeat every 400 years.
Comment: 97 every 400 years, you meant to say.
Comment: can you please make your answer clearer. It will be helpful if you spot the mistake I have made
Answer: While your definition of "odd days" is unclear to me, what I get is that if the number of days is a multiple of $7$, the number of odd days is $0$. In the following I'll therefore show that the number of days indeed is a multiple of $7$.
The rule for leap years is:

If the year is divisible by $400$, it is a leap year.
Otherwise, if it is divisible by $100$, it is not a leap year.
Otherwise, if it is divisible by $4$, it is a leap year.
Otherwise, it is not a leap year.

This means, the leap year rule has a $400$ year period. Therefore if we want to know how many days there are in $1600$ years, we can calculate the days in $400$ years, and multiply by $4$.
Now the number of days in $400$ years is $400\cdot 365 + \text{number of leap years}$. Now to calculate the number of leap years in $400$ years, we go through the above list in reverse order:

Years divisible by $4$ are generally leap years, there are $400/4=100$ of them.
However this way we have also counted the years divisible by $100$ (because they are all divisible by $4$). There are $400/100=4$ of them, which we therefore subtract, so we get $100-4=96$.
However now we have also removed the years divisible by $400$, of which there's one in $400$ years. Therefore we have to add that one back, so we end up with $97$ leap years in $400$ years.

Therefore $400$ years have altogether $146\,097$ days. Now it is not hard to check that this number indeed is a multiple of $7$. Therefore there are no odd days in $400$ years, and thus also not in $1600$.
Answer: In $400$ years there would be $100$ leap years, but $3$ of them are suppressed. An ordinary year has one "odd day", and a leap year has an extra "odd day". Therefore there are $497$ odd days in $400$ years, which is divisible by $7$. A fortiori there remains no "odd day" in $1600$ years.
Answer: Every 4th century is a leap year and no other century is a leap year. Therefore there will be 96 + 1=97 leap year and 303 ordinary years. So the equation becomes 303*1 +97*2 =497 odd days or 0 odd days.
Answer: @Sahil u r making a mistake in finding no. of leap years in 1600 years.. here is my solution..
as every 100 yrs has 24 leap years. so
• first 300 yrs-24*3 leap yrs
• 4th 100 yrs-24+1 leap yrs because 400th year is also a leap yr as it is divisible by 400
• next 300 yrs-24*3 leap yrs
• 8th 100 yrs-25 leap yr
• next 300 yrs-24*3 leap yrs
• 12th 100 yr-25 leap yrs
• next 300 yrs-24*3 leap yrs
• 16th 100 yrs-25 leap yrs
so now total no. of leap yrs in first 1600 yrs becomes=24*3*4+25*4=388
so no. of non leap yrs=1600-388=1212
so total no. of odd days in 1600 yrs=388*2+1212=1988
which is divisible by 7.
So there're 0 odd days in 1600 yrs.
Answer: It is easy. Just remembr the answer. :)
Just joking.
Here is my simple solution:
As each 4th century's a leap year & no other century is a leap year,  there will be 96 + 1=97 leap year and 303 ordinary years. So we get  303x1 + 97x2 =497 odd days or 0 odd days.
Hope it helped.
Afterall, better late than never, huh?
Answer: If the number is divisible by $400$ then zero odd days.
In $1200$ or $1600$ years, you will find $0$ odd days.
In $100$ years, you will get $5$ odd days.


redundant load balancer for Tomcat

Question: I have three Tomcat webservers in a VMWare cluster.
In the first place we thought of using Apache as a load balancer in physical server but this would be a SPOF.
I have searched around and I found this discussion but I would need some more info. Does it make sense to include the two (or more) HAProxy servers as virtual machines and not run them on physical servers? Can this active-passive configuration be configured using Apache? I have searched around and I found many active-passive configurations for Apache BUT as Web Server, not as a load balancer.
Answer: Without a lot of experience with Apache as a reverse proxy/load balancer I don't see any immediate reason for why it wouldn't work.
That said, I've been using several virtual HAProxy pairs for almost a decade now and am very happy with that product.
From version 2.5, multithreading is very well integrated into HAProxy, so it's trivial to scale if your traffic requires more than one core worth of capacity.
To provide a virtual IP with a primary and backup server I have installed keepalived which uses VRRP to ensure the vIP fails over to the backup proxy when it goes down.

redundant load balancer for Tomcat


AIC & BIC of PyMC mixture model

Question: I am using PyMC to fit some data to a straight line. The data have outliers, so I adapted some code (third example at the link) written by Jake Vanderplas for his textbook. The method uses a vector variable qi to encode whether each individual data point belongs to the foreground model (which we are fitting to the line) or the background model, which we don't care about.
class lin_fit_ol(object):

    '''
    fit a straight line to one independent variable
        (`xi`, with zero errors) and one dependent variable
        (`yi`, with possibly heteroscedastic errors `dyi`)
    Outliers in `yi` are permitted

    Intended to be a complement to a straight-line fit, for model
        testing purposes

    Modified from Vanderplas's code
        (found at http://www.astroml.\
        org/book_figures/chapter8/fig_outlier_rejection.html)
    '''

    def __init__(self, xi, yi, dyi, value):

        self.xi, self.yi, self.dyi, self.value = xi, yi, dyi, value

        @pymc.stochastic
        def beta(value=np.array([0.5, 1.0])):
            """Slope and intercept parameters for a straight line.
            The likelihood corresponds to the prior probability of the parameters."""
            slope, intercept = value
            prob_intercept = 1 + 0 * intercept
            # uniform prior on theta = arctan(slope)
            # d[arctan(x)]/dx = 1 / (1 + x^2)
            prob_slope = np.log(1. / (1. + slope ** 2))
            return prob_intercept + prob_slope

        @pymc.deterministic
        def model(xi=xi, beta=beta):
            slope, intercept = beta
            return slope * xi + intercept

        # uniform prior on Pb, the fraction of bad points
        Pb = pymc.Uniform('Pb', 0, 1.0, value=0.1)

        # uniform prior on Yb, the centroid of the outlier distribution
        Yb = pymc.Uniform('Yb', -10000, 10000, value=0)

        # uniform prior on log(sigmab), the spread of the outlier distribution
        log_sigmab = pymc.Uniform('log_sigmab', -10, 10, value=5)

        # qi is bernoulli distributed
        # Note: this syntax requires pymc version 2.2
        qi = pymc.Bernoulli('qi', p=1 - Pb, value=np.ones(len(xi)))

        @pymc.deterministic
        def sigmab(log_sigmab=log_sigmab):
            return np.exp(log_sigmab)

        def outlier_likelihood(yi, mu, dyi, qi, Yb, sigmab):
            """likelihood for full outlier posterior"""
            Vi = dyi ** 2
            Vb = sigmab ** 2

            root2pi = np.sqrt(2 * np.pi)

            logL_in = -0.5 * np.sum(
                qi * (np.log(2 * np.pi * Vi) + (yi - mu) ** 2 / Vi))

            logL_out = -0.5 * np.sum(
                (1 - qi) * (np.log(2 * np.pi * (Vi + Vb)) +
                            (yi - Yb) ** 2 / (Vi + Vb)))

            return logL_out + logL_in

        OutlierNormal = pymc.stochastic_from_dist(
            'outliernormal', logp=outlier_likelihood, dtype=np.float,
            mv=True)

        y_outlier = OutlierNormal(
            'y_outlier', mu=model, dyi=dyi, Yb=Yb, sigmab=sigmab, qi=qi,
            observed=True, value=yi)

        self.M = dict(y_outlier=y_outlier, beta=beta, model=model,
                      qi=qi, Pb=Pb, Yb=Yb, log_sigmab=log_sigmab,
                      sigmab=sigmab)

        self.sample_invoked = False

    def sample(self, iter, burn, calc_deviance=True):
        self.S0 = pymc.MCMC(self.M)
        self.S0.sample(iter=iter, burn=burn)
        self.trace = self.S0.trace('beta')
        self.btrace = self.trace[:, 0]
        self.mtrace = self.trace[:, 1]

        self.sample_invoked = True

    def triangle(self):
        assert self.sample_invoked == True, \
            'Must sample first! Use sample(iter, burn)'

        corner(self.trace[:], labels=['$m$', '$b$'])

    def plot(self, xlab='$x$', ylab='$y$'):
        # plot the data points
        plt.errorbar(self.xi, self.yi, yerr=self.dyi, fmt='.k')

        # do some shimmying to get quantile bounds
        xa = np.linspace(self.xi.min(), self.xi.max(), 100)
        A = np.vander(xa, 2)
        # generate all possible lines
        lines = np.dot(self.trace[:], A.T)
        quantiles = np.percentile(lines, [16, 84], axis=0)
        plt.fill_between(xa, quantiles[0], quantiles[1],
                         color="#8d44ad", alpha=0.5)

        # plot circles around points identified as outliers
        qi = self.S0.trace('qi')[:]
        Pi = qi.astype(float).mean(0)
        outlier_x = self.xi[Pi < 0.32]
        outlier_y = self.yi[Pi < 0.32]
        plt.scatter(outlier_x, outlier_y, lw=1, s=400, alpha=0.5,
                    facecolors='none', edgecolors='red')

        plt.xlabel(xlab)
        plt.ylabel(ylab)

    def ICs(self):
        self.MAP = pymc.MAP(self.M)
        self.MAP.fit()

        self.BIC = self.MAP.BIC
        self.AIC = self.MAP.AIC
        self.logp = self.MAP.logp
        self.logp_at_max = self.MAP.logp_at_max
        return self.AIC, self.BIC

So, when we calculate the BIC and AIC using this model, we get very large values (since there are lots of points). This makes total sense. However, this disfavors having many data points, which irks me. Plus, the large AIC and BIC would make a casual observer believe that the other model (which fits poorly as a result of the outliers) is actually the better model.
Am I missing a subtlety of the BIC and AIC here, or is a harsh reality of using mixture models that you always have to use a bunch of extra binary parameters to denote the membership of your datapoints?
Comment: I don't usually use AIC or BIC when comparing models of different data sets. Both criteria depend on the sample size so they, as you observe, increase with the sample size. I tend only to use them when comparing different models for the same data set. I agree it seems strange to use AIC or BIC as a sort of cost function when deciding whether to include or exclude a data point in your model.
Answer: I recommend the book "Introduction to statistical learning"
On page 212 you find the formulas for AIC and BIC. In each of these formulas the sample number is in the denominator. Hence, the result should not be influenced by the number of samples. At least not in that obvious way.

AIC & BIC of PyMC mixture model


How do I find the "file path" for a file in an AWS s3 bucket?

Question: I am trying to find the file in an s3 bucket using it's file path. How would I find that file path? Can I query a bucket for a particular file?
Comment: What do you mean by "query a bucket for a particular file"? What are you wanting to use for the search (eg filename, size, date)? If it's the filename, how are you getting the filename? Objects in Amazon S3 have a `Key`, which is the full filename including the path, so it's unusual to only have the 'filename' portion.
Answer: You can test for the presence of an object in a bucket using the HeadObject API. You would supply the bucket name and the object's key to that API.
To get a list of all objects under a bucket, you can use the ListObjectsV2 API. You would supply the bucket name and an optional key prefix to that API.
Both are available in your AWS SDK of choice under a similar name, such as headObject or head_object.
Answer: Objects in S3 are stored by key. Often the key includes slashes, which function like path separators, but they really aren't. So to get a particular file you would need to include the full key ("path" and name).


emacs automatically open in mac

Question: I was setting up with emacs on my macbook. In order to open the emacs from command line, I was follow other's suggestion to add an emacs script to my /usr/bin.
Now I can open graphic emacs from command line, but the problem is that every time when I open the terminal, the emacs is automatic run. I don't know why this happened.
Here is the script I added:
#!/bin/sh
/Applications/Emacs.app/Contents/MacOS/Emacs "$@"
I also use chmod +x /usr/bin/emacs after the script was added.
Please tell me what cause the problem happens.
Comment: Did you add anything to your `.bash_profile`?
Comment: I didn't add anything to the profile. It just automatically launched. I'm using zsh
Answer: If your using the standard OS X terminal, look under preferences->profile and the shell tab and make sure there isn't something set in the run on startup option.
If your using another terminal, such as iTerm, check the profiles.
Comment: I'm pretty sure there is nothing in startup option. I tried both in my OS X terminal and iTerm and they both have this problem.
Comment: OK, given that it is happening in both, my guess would be it has to be something in your .bash_profile or possibly your .bashrc (assuming your running bash - substitute whatever the startup files are for your shell if not bash). Perhpas post these two files and we can see if there is something obvious.

emacs automatically open in mac


does the src field in an ip route entry have any effect on forwarding traffic?

Question:
does the src field in ip route have any affect on forwarding traffic? or is it only significant for output traffic?
what is the significance of an ip route entry that specifies both dev and src, where src does not belong to dev (but rather to a different device in the system)?
Answer: When adding a route to a multihomed host, you might want to have control over the source IP address your host is sending from when starting communications using this route. This is what src is for.
Therefore to answer your question by point :

No, it has no effect on forwarding traffic, it is only for local generated traffic.
You can use bot dev and src to double-check if the src IP entered corresponds to the correct dev interfaces. If the source IP mentioned is not on the device specified you will get an error.
Comment: [root@localhost ~]# ip r add 22.214.171.124 via 10.0.2.1 dev enp0s3 src 18.104.22.168
RTNETLINK answers: Invalid argument
[root@localhost ~]# ip r add 188.8.131.52 via 10.0.2.1 dev enp0s3
[root@localhost ~]# ip r
default via 10.0.2.2 dev enp0s3  proto static  metric 100
18.104.22.168 via 10.0.2.1 dev enp0s3
10.0.2.0/24 dev enp0s3  proto kernel  scope link  src 10.0.2.15  metric 100
[root@localhost ~]# ip r add 184.108.40.206 via 10.0.2.1 dev enp0s3 src 10.0.2.15
[root@localhost ~]# ip r

Centos7/rhel7 detects it as an error .
Comment: actually when the `src` is *not* an address of `dev`, there is no error.

moreover, i found a comment in `understanding linux network internals` that briefly addresses this (`35.7.2. Preferred Source Address Selection`) but it doesn't go into detail about when/how to make use of this.

i encountered such a configuration in a legacy system i'm working on, and was wondering about the reason for it.
Comment: You can force a foreign src address by tuning the kernel a bit to allow bindings on non local IP's . How ever this is used on special situation like VRRP, LVS, etc ... or when you just need to generate traffic with a specific IP for audits and tests(but expect no return traffic!)


Disable user field on profile edit page

Question: I've got a logintoboggan (http://drupal.org/project/logintoboggan/) module and my login is an email adress, so I dont want to have a "Name: " field on my profile edit page.
But when i just call in my theme preprocess page:
<code>$vars['form']['account']['name']['#required'] = FALSE;
</code>
or unset() the field I've got an error:

Username field is required.

How can I disable validation of this field? Thanks!
Answer: The username field is a required field in the <code>{users}</code> table so it has to be there one way or another.
A way round it might be to remove the "Change own username" permission for authenticated users at http://mysite.com/admin/user/permissions. I can't remember if the field will still display on the user edit form but either way it won't be editable.

Disable user field on profile edit page


How to load camera scanner?

Question: I'm getting the following error:
Warning: Attempt to present <VNDocumentCameraViewController_InProcess: 0x109e216c0> on <[myapp]> whose view is not in the window hierarchy!

when calling my function:
public func scanDocument() {

        let scannerViewController = VNDocumentCameraViewController()
        scannerViewController.delegate = self
        present(scannerViewController, animated: true)
    }

How can I make this work?
Comment: Where are you calling `scanDocument()` from?
Comment: @nanibir I am calling scanDocument from another class, via a button. When I click the button I get the error.
Answer: You can only call present from a view controller which is already in the view hierarchy. So make sure the view controller you have the scanDocument function in is already presented / pushed / made visible first.

How to load camera scanner?


Full Page Livewire is not allowing page access after close of a modal

Question: So I'm working on creating a full page livewire route, the route is working and the page loads correctly. On my page I have a livewire component that allows Jetstream modal-dialog to open a form. This is great and the associated forms open as expected and can be clicked outside to close or the close button clicked.
However after doing this I cannot do anything on my page. The pointer doesn;t change and I am unable to do anything with the page until i reload the page. Obviously thats not desirable and defeats the whole point of using livewire for the page. My add component actually opens one of 6 modals on the page so perhaps this can be refactored? on my standard non livewire pages this issue does not happen!
The code is lengthy and for brevity I will show the AddButton component and the ManageClientModal component although the other modals work in the same way.
AddButton.php:
<?php

namespace App\Http\Livewire\Tools;

use Livewire\Component;

class AddButton extends Component
{
    public bool $showUser     = false;
    public bool $showClient   = false;
    public bool $showMerchant = false;
    public bool $showJob      = false;
    public bool $showHoliday  = false;

    public function mount()
    {
        $this->showUser     = auth()->user()->can( 'manage users' );
        $this->showClient   = auth()->user()->can( 'manage clients' );
        $this->showMerchant = auth()->user()->can( 'manage merchants' );
        $this->showJob      = auth()->user()->can( 'manage jobs' );
        $this->showHoliday  = true;
    }
    public function render()
    {
        return view('livewire.tools.add-button');
    }

    public function showUserModal( $user_id, $delete )
    {
        $this->emit('showUserModal', $user_id, $delete);
    }

    public function showClientModal( $client_id, $delete )
    {
        $this->emit('showClientModal', $client_id, $delete);
    }

    public function showMerchantModal( $merchant_id, $delete )
    {
        $this->emit('showMerchantModal', $merchant_id, $delete);
    }

    public function showJobModal( $job_number, $delete )
    {
        $this->emit('showJobModal', $job_number, $delete);
    }

    public function showHolidayModal( $holiday_id, $delete )
    {
        $this->emit('showHolidayModal', auth()->id(), $holiday_id, $delete);
    }

}

and add-button.blade.php:

            <button type="button" class="bg-transparent hover:bg-blue-500 text-blue-700 font-semibold hover:text-blue-400 py-2 px-4 border border-blue-500 hover:border-transparent rounded">
                {!! config( 'ecl.ADD_SUCCESS' ) !!} {{ __( 'Add' ) }}
            </button>

                Add Actions

            @if( $showJob )
                {!! config( 'ecl.JOBS' ) !!} {{ __( 'Add A Job' ) }}
            @endif
            @if( $showClient )
                {!! config( 'ecl.CLIENTS' ) !!} {{ __( 'Add A Client' ) }}
            @endif
            @if( $showMerchant )
                {!! config( 'ecl.MERCHANTS' ) !!} {{ __( 'Add A Merchant' ) }}
            @endif
            @if( $showUser )
                {!! config( 'ecl.USERS' ) !!} {{ __( 'Add A User' ) }}
            @endif
            @if( $showHoliday )
                {!! config( 'ecl.PLANE' ) !!} {{ __( 'Add A Holiday' ) }}
            @endif

    @livewire('modals.manage-job', ['showButton' => false])
    @livewire('modals.manage-client', ['showButton' => false])
    @livewire('modals.manage-merchant', ['showButton' => false])
    @livewire('modals.manage-user', ['showButton' => false])
    @livewire('modals.add-holiday', ['showButton' => false])

my ManageClient.php:
<?php

namespace App\Http\Livewire\Modals;

use App\Models\Client;
use Livewire\Component;

class ManageClient extends Component
{
    public bool   $showingModal = false;
    public bool   $showButton = true;
    public int    $delete = 0;
    public string $header;

    protected $listeners =[
        'refresh' => '$refresh',
        'showClientModal' => 'showClientModal'
    ];

    public function render()
    {
        return view('livewire.modals.manage-client');
    }

    public function submit()
    {
        if ( $this->delete === 0 ) {

            $this->adder = false;
        } else {
            //$this->adder = $this->adder;
        }

        $this->hideModal();
    }

    public function showClientModal( $clientId, $delete )
    {
        $this->delete = $delete;
        $this->client_id = $clientId;
        if ( $clientId > 0 ) {
            $client = Client::find( $clientId );
            $this->header         = 'Edit the Client';
            $this->adder          = false;
        } else {
            $this->header         = 'Add a Client';
            $this->adder          = true;
        }
        if ( $delete ) {
            $this->header = 'Delete this Client';
        }
        $this->showingModal = true;
    }

    public function hideModal()
    {
        $this->showingModal = false;
    }
}

and the manage-client.blade.php:

     @if($showButton)

    @endif
    <form wire:submit.prevent="submit()">
        <x-dialog-modal wire:model="showingModal" maxWidth="2xl" class="flex items-center">

            <x-slot name="title">
                {{ $header }}
            </x-slot>

            <x-slot name="content">
                @if( $delete === 0 )

Client Information

                                Please complete the fields to manage the Client.

                @else

Click Yes if you would like to remove the following client or No to leave it alone:

{{ $title }}

 A deleted comment cannot be restored!

Are you sure you want to delete this comment?

                @endif
            </x-slot>

            <x-slot name="footer">
                @if ( $delete === 0 )
                    <x-button class="mx-2" type="submit">
                        {{ __('Submit') }}
                    </x-button>

                    <x-secondary-button wire:click="$set('showingModal', false)" wire:loading.attr="disabled">
                        {{ __('Cancel')  }}
                    </x-secondary-button>
                @else
                    <x-button class="mx-2" type="submit">
                        {{ __('Yes') }}
                    </x-button>

                    <x-secondary-button wire:click="$set('showingModal', false)" wire:loading.attr="disabled">
                        {{ __('No')  }}
                    </x-secondary-button>
                @endif
            </x-slot>

        </x-dialog-modal>
    </form>

Just to reiterate, the issue is not with the route as the page loads and works as expected until a modal is opened and then closed. Even submitting does this and seems to leave a transparent overlay over the whole page! I have considered that maybe some refresh from the AddButton would fix this and have tried using javascript but the only way to get access to the page after handling any Modal is to reload the page!
Answer: I guess you don't really hide your modal, you just remove the show class in the modal. I think you need to emit an hideModal event.
public function hideModal()
{
   $this->showingModal = false;
   $this->emit('hideModal', 'your-modal-id');
}

Then, in your parent component, you add a javascript:

Comment: This helped but ulimately made no difference. I ended up dropping it as being a full page livewire component and everything works. Probably come back to this but got plenty of other things to do on this project and as this has taken 2 days it is time to move on...


Rolling Some Dice...Look But Don't Touch

Question: Does anyone have any thoughts on passing full objects as variables as opposed to only pointers to the functions of the full object?
For example, I have a Dice object with two methods:

RollDice(), randomizes the dice count
GetCount(), retrieves the value

Now, I need to utilize the dice for more than just player moving, other objects need to be able to look at the Dice as well. Now, it seems wrong to me to pass the whole Dice object to these other objects, since then those objects would 'technically' be able to re-roll the Dice. Is it good or bad programming to pass only the GetCount function pointer to these other objects? Essentially saying "I'm not giving you the Dice, but I'll show you how to read them.".
Thoughts?
Comment: What programming language? Also, if you don't want to pass a function pointer to a `GetCount` function, why not just pass the value of the di(c)e as a number?
Comment: @Matt - I'm working on this in C#
Comment: I appreciate everyone's insight on this problem.
Answer: It seems that its an excellent oportunity to use the OBSERVER PATTERN (GoF);
<code>public class Dice
{
    private List<IDiceObserver> observers;
    public void RegisterObserver(IDiceObserver observer)
    {
        this.observers.Add(observer);
    }

    private Int32 count;
    public Int32 Count
    {
        get
        {
            return this.count;
        }
        private set
        {
            this.count = value;
            foreach (IDiceObserver observer in this.observers)
                observer.DiceRolled(new DiceParameters(this.count));
        }
    }

    public void RollDice()
    {
        this.Count = new Random(DateTime.Now.Millisecond).Next();
    }

    public Dice()
    {
        this.observers = new List<IDiceObserver>();
    }
}
</code>
Do you need any further explanation on pattern, or other classes implementations????
Comment: Observer may not know the Dice class if you imagine them in a bigger context, for example, a Game class, wich has a Dice object, and a list of Players, I would implement the responsability for registering the Players as DiceObservers as a Game instance method called InitializeGame(), where I would loop through each player and call the method this way; myDice.RegisterObserver(player). Understand my point?
Answer: Why don't you pass them an integer?  This means they are decoupled from the dice.
If you are using dependency injection to inject the dice into service objects for each move, then create an interface that only contains the GetCount() method.
Comment: There is the one problem with this approach that I didn't make clear.  I could pass the dice value to the objects that need it, but it would require me to keep track of everything that needs the value and to make sure they are all updated on every roll.  I am looking to allow the objects to 'query' the dice only on occasion as needed.
Comment: The objects interested in the dice value should then take as a constructor argument interface IDiceCount.  This has one method on it for GetCount().
Answer: You can create a wrapper class for dice to make them immutable. The wrapper can be implemented either by delegation or by subclassing and overriding RollDice(). Then pass a wrapper object instead of a mutable Dice object when you want to guarantee that it won't change.
Comment: Do you mean extending Dice with an immutable implementation that stubs out RollDice? In my opinion this break the Liskov Substitution Principle because RollDice no longer has the behaviour expected by the calling class.
Comment: @Martin - You make a valid point. I think the delegation architecture is much cleaner for something like this.
Comment: @Martin - after more reflection, I think that with a slight change the subtype proposal works cleanly: make the (mutable) Dice class the subclass of the immutable one. I don't think that breaks LSP provided the superclass does not specify that it is immutable but merely provides no means to roll the dice.
Comment: That definitely solves that particular problem :) "Require no more, promise no less". I personally prefer my solution below, because I think it more closely models the real world, but yours is a fine solution.
Comment: @Martin - I agree. Your solution is more elegant.
Answer: Sounds like your Dice object should have a DiceValue or FaceValue attribute. You could pass this value instead of passing the dice themselves. This controls access to dice behaviour, and also avoids the primitive obsession code smell which would result from passing just the integer value of the face. It also keeps your dice value more abstract, so you could later use values other than numbers, such as special face values, etc.


What's the de facto standard for running a node.js server in production?

Question: How should I daemon-ize and "watchdog" it, auto-start on reboot, redirect console output to a log file?
Answer: Used forever as a daemon tool in past projects. It'll automatically restart your node.js scripts if they crash. Also, it can start and manage multiple node processes and maintain a log file for each of them individually. However it doesn't start the scripts on reboot.
Read a couple of times that people were using Upstart to make the initial launch of forever, but i've never used it myself, never had the need to start on boot.
Answer: This is the one of the job of initd or upstart. May be you can use inetd too if it is ok to start it on demand.