What are some leading academic papers on Machine Learning applied to financial markets

Question: I am looking for some seminal papers regarding machine learning being applied to financial markets, I am interested in all areas of finance however to keep this question specific I am now looking at academic papers on machine learning applied to financial markets.
I come across the following paper which covers much of the theory behind extreme gradient boosting with a financial markets application, they were able to predict the direction of the market with 88% accuracy.
https://www.researchgate.net/publication/309492895_Forecasting_to_Classification_Predicting_the_direction_of_stock_market_price_using_Xtreme_Gradient_Boosting
R-bloggers did a post a few months ago on this exact same idea.
https://www.r-bloggers.com/forecasting-markets-using-extreme-gradient-boosting-xgboost/
Comment: Prediction in finance is notoriously difficult. If anyone knows any good ML models which can work out of sample, they certainly won't post papers on them until they become bad, they'd implement and extract the alpha whilst they work.
Comment: Thanks for your comment, I am not necessarily looking for papers on how to predict stock market movements and profitability but more towards the theory behind machine learning applied to finance and some leading authors in this area. Some areas might be credit risk modelling, banking, business solutions etc.
Comment: @TilefishPoele unless working in a niche, and need some branding in order to raise funds; but basically, yes you're right.
Comment: Despite the potential interest in this question among some members of our community, this kind of vague, open-ended, query for a list of things is quite definitely not the type we can handle here.
Answer: Deep Learning for mortgage risk
Risk and Risk Management in the Credit Card Industry: Machine Learning and Supervision of Financial Institutions
Mortgage and Housing Microdata: Database Construction and Challenges for Statistical Inference
Neural Networks in Finance and Investing: Using Artificial Intelligence to Improve Real World Performance
Comment: Thank you for this, this is what I am looking for, I will start reading the papers suggested.
Comment: No problem. Good luck with the models!
Comment: Autoregressive Convolutional Neural Networks for Asynchronous Time Series https://arxiv.org/pdf/1703.04122.pdf


Proof strategy for 4-Colour-Theorem

Question: Suppose you have a triangulated region in the plane, the triangulation consisting of $n$ triangles. Take an arbitrary triangle of this triangulation and call it $\Delta_i$ with $1\leq i\leq n$.
The neighbourhood of $\Delta_i$, i.e. all the triangles around $\Delta_i$ which share a vertex or an edge with $\Delta_i$, we call this neighbourhood $N_i$.

If we can prove that you can label the vertices of $\Delta_i$ and its neighbourhood $N_i$ with just 4 colours, i.e. such that all adjacent vertices have different colour: does the 4-Colour-Theorem follow?

My thinking is: yes it follows, because $\Delta_i$ was arbitrarily chosen in this triangulation. Therefore we can conclude the whole triangulation can be 4-coloured. And if 4 colours suffice for an arbitrary triangulation, then 4 colours also suffice for any plane graph.
Would this be a valid proof strategy for the 4-Colour-Theorem, or am I taking the wrong conclusion?
Comment: The cycle graph $C_n$ is $2$-colourable only if $n$ is even. So $C_{1001}$ is not $2$-colourable. But every neighbourhood is $2$-colourable, even if you define your "neighbourhoods" to consist of $100$ consecutive vertices; you don't need the third colour unless you go all the way around.
Comment: @bof Wow thanks a lot - this is a compelling example! I see your point. It is a great counterexample to what I had in mind! Is there a "canonical" way how to draw conclusions from neighbourhoods in a graph for the whole graph?
Answer: If your proof strategy worked, it would prove too much.
Define a locally planar graph on a surface such as the torus to be a graph which looks like a planar graph within any "small region". (By "small", we can mean the neighborhood of a triangle, or more generally the subgraph within some fixed constant distance of any vertex). Then if your proof strategy worked, it would show that all locally planar graphs are 4-colorable as well.
However, there are counterexamples on other surfaces: for example, here is a counterexample on the torus, taken from Locally planar toroidal graphs are 5-colorable by Albertson and Stromquist. (Opposite sides of the rectangle in this diagram wrap around.)

It can be shown that in any 4-coloring of any triangulation on any surface, if there are only two vertices of odd degree, they must have the same color. However, in the example above, there are two such vertices, and they are adjacent: so this graph has no 4-coloring.
Nevertheless, we can pick any triangle within this graph, and 4-color that triangle and its neighborhood (by the 4-color theorem). It is the global properties of this graph that ultimately stop us. To take your argument, and turn it into a proof of the 4-color theorem, you would have to show that in a planar graph, there cannot be a global obstacle.
Comment: this is an excellent answer! It is very clear, and the example is great. Thank you also for the useful reference link!
Comment: one final question: if my starting point is a region in the plane with a boundary (i.e. not boundaryless like a torus), does my argument still break? I fear it still breaks, as illustrated by the example of bof in the comments and by Brandon du Preez
Comment: The problem is that your argument doesn't do anything that would distinguish a triangulation of a region in the plane with a boundary from a triangulation of a torus. The question is not whether it's possible to 4-color the planar triangulation (we already know that the 4-color theorem is true), but whether your argument *proves* that it's possible. For that, at some point, you'd have to use some property that the planar triangulation has, but the toroidal triangulation does not.
Answer: Note that the property you stated only refers to "local" properties of the triangulation. However, the 4-color theorem is a global property (i.e. involving all parts of the triangulation at the same time). So in general it is not a valid logical inference.
Indeed, the 4-color theorem depends in an essential way on (global) topological information of the plane. So if you replace the plane with, say, a torus, it becomes the 7-color theorem. However, if your argument were true then you would prove the 4-color theorem on tori also, which is absurd.
Comment: thank you for your answer. Please let me know, what is missing in my argument? Because if all the neighbourhoods of $\Delta_i$ only need 4 colours, then the whole triangulation only needs 4 colours. Where does this argument "break"? - In other words, what exactly is the global topological information of the plane that interferes with my argument (or where is the gap in my argument relative to the global properties of the plane?
Answer: Trebor has already given an answer that more than suffices to show to that we shouldn't expect this method to work for map colouring, but it is worth pointing that similar difficulties arise even for general graph colouring.
The problems of colouring a graph optimally, and `extending' a colouring are quite different. I can have a graph $G$, with a subgraph $H$, and then find an optimal colouring of $H$ that cannot be extended to an optimal colouring of $G$. So by colouring $\Delta_i$ and its surrounds in what looks like an optimal way, you can inadvertently get stuck with something that cannot be part of a 4-colouring.
For a concrete example, in the picture below, we can colour $H$ optimally in 2 ways, one of which does not extend to an optimal colouring. Inside of $H$, there's no real way of telling apart these colourings.

Further, there is another difficulty. 4-Coloring a triangle and all its neighbors amounts to finding a 4-colouring of some arbitrary maximal planar graph of diameter 3 or less, which is still very, very difficult in general.
Comment: Very helpful example! Thank you for that.
Comment: Glad to be of help ^^
Answer: Your argument resembles a heuristic argument of another well-known historical case: can you bound the chromatic number of graphs with large girth (i.e. no short cycles)?  If you consider graphs with no cycles shorter than, say, 1001, can you give an upper bound on the chromatic number?  It's not unreasonable to think something like that might exist: if you take any 1000 vertices, they induce a forest, which is 2-colorable.  As @bof says in a comment, your argument would try to say that such a graph would then be 2-colorable, since the vertices were chosen arbitrarily.  For this to work though, you'd need to say something about how those patches of 1000 vertices, with their 2-colorings, can be made compatible with each other.  And that kind of argument is sound and common in coloring proofs: color part(s) of the graph, and finagle things until you can extend the coloring.
(It seems reasonable to hope that in the high-girth case, you could wrangle colors to match up well enough, but Erdős famously used the probabilistic method to show that we cannot: there are (enormous) graphs with arbitrarily large girth and chromatic number.)
Comment: Thank you for this interesting extra perspective! Interesting link (or non-link) between girth and chromatic number!

Proof strategy for 4-Colour-Theorem


Sum of squares of consecutive integers equals to a square

Question: I am not at all mathematics guy, just had a question. How can I find possible pairs of consecutive integers whose sum of squares equals to a square?
I understand equation will be something like:
x² + (x + 1)² = y²
x² + x² + 2x + 1 = y2
2x² + 2x + 1 = y²
where x, x+1 consecutive integers.
But, how can I mathematically find (x, x+1) pairs, example:
3² + 4² = 5²
20² + 21² = 29²
119² + 120² = 169²
from the equation? I am actually trying to write a program which will find these pairs without brute force. Please help me with the logic (maths).
Is there a possible way to find these pairs without "substituting x by every number from 1 to n and checking if y² is a perfect square"? I mean to avoid brute force or decrease brute force complexity, maybe like simplifying the equation 2x² + 2x + 1 = y² even more.
Comment: Please search if your question exists on [Approach0](https://approach0.xyz) before asking here. These numbers are called Pythagorean triples, named after Pythagoras' theorem ($a^2+b^2=c^2$).
Comment: @TobyMak  Well...is it obvious how to pass from the general form of a Pythagorean triple to one of the type the OP desires?  That is $a^2+(a+1)^2=c^2$?  I wouldn't think that was trivial...you still need to solve a Pell type equation.  See [here](https://mathworld.wolfram.com/TwinPythagoreanTriple.html) for instance.  Note that the discussion on that link also considers the triples in which the hypotenuse is $1$ greater than one leg.
Comment: @lulu  Below I have provided $3$ methods of generating $B-A=\pm1$ but you mentioned a hypotenuse-leg difference of $1$. Here is a bit of non-trivia you might find fascinating.

One easy way to generate triples where
$C-B=1$ or $C-A=2$ is to begin with a variation of Euclid's formula:

$$ A=(2n-1+k)^2-k^2\quad B=2(2n-1+k)k \quad C=(2n-1+k)^2+k^2$$
Using this formula;

$$n=1\implies C-B=1\qquad k=1\implies C-A=2$$
Comment: @poetasis  Oh, that's very nice, thanks!  Your posted solution is quite thorough as well (+1).
Comment: @lulu Nice, but this has been asked many times here.
Answer: There are at least $3$ ways of generating these. Note that these are so rare that the $20^{th}$ triple exceeds $15$ digits.
We begin with Euclid's formula shown here as:
$$ A=m^2-k^2\qquad B=2mk \qquad C=m^2+k^2$$
The $m,k$ values for
$\space A^2+(A\pm1)^2=C^2\space$ are
pell numbers
$$p\in\big\{0,1,2,5,12,29,70,169,\cdots\big\} \space e.g.$$
$$
F(1,0)=(1,0,1)\\
F(2,1)=(3,4,5)\\
F(5,2)=(21,20,29)\\
F(12,5)=(119,120,169)\\
F(29,12)=(697,696,985)\\
F(70,29)=(4059,4060,5741)\\
F(169,70)=(23661,23660,33461)\\
\vdots$$

The $n^{th}\space$ $(m,k)\space$ pair may be generated directly by the following formula.

\begin{equation}
 m_n= \frac{(1 + \sqrt{2})^{n+1} - (1 - \sqrt{2})^{n+1}}{2\sqrt{2}}\\
 k_n= \frac{(1 + \sqrt{2})^n - (1 - \sqrt{2})^n}{2\sqrt{2}}
 \end{equation}

These pairs may also be generated sequentially by
\begin{equation}
\quad m=k+\sqrt{2k^2+(-1)^k}
\end{equation}

The $A,B,C$ values may be generated without Euclid's formula by using the following formula with a seed [invalid] triple  $T_0=(0,0,1)$.
\begin{equation}
A_{n+1}=3A_n+2C_n+1\\
B_{n+1}=3A_n+2C_n+2 \\
C_{n+1}=4A_n+3C_n+2
\end{equation}
Answer: According to Euclid's formula, we have $$ a=m^2-n^2, b=2mn, c=m^2+n^2$$
You are asking for $$m^2-n^2=2mn\pm 1 $$ Upon adding $2n^2$ to both sides we get
$$(m-n)^2=2n^2\pm 1$$
Thus we choose positive integers $n$ such that one of $2n^2\pm 1 $ is a perfect square and solve $$ (m-n)^2=2n^2\pm 1$$ for $m$
For example:
$$n=1, 2n^2-1=1, (m-1)^2=1, m=2$$ which gives us $$(a,b,c)=(3,4,5)$$
$$ n=2, 2n^2+1=9, (m-2)^2=9, m=5$$ which gives us $$ (a,b,c)=(21,20,29)$$
With $n=5$ we get $$(a,b,c)= (119,120,169)$$
With $n=12$ we get $$(a,b,c)= (697,696,985)$$
And with $n=985$ we get $$(a,b,c)= (4684659,4684660,6625109)$$
Answer: Let $X=2x+1$ and let $Y=y$, then we get $$X^2-2Y^2=-1\tag{1}$$
The equation $X^2-2Y^2=-1$ is called as Pell's equation.
For details, see Pell equation.
All solutions are given as follows.
Let  $(X_{0},Y_{0})$ is a fundamental solution of $X^{2}-2Y^{2}=-1.$
Thus, all of the solutions are derived from $(X_{0}+Y_{0}\sqrt{2})^n$ where $n$ is an odd integer.
Clearly, we know  $(X_{0},Y_{0})=(1,1)$.
We take the integer part as $X$ and the coefficient of $\sqrt{2}$ as $Y$ as follows.
$(1+1\sqrt{2})^{3} = 7+5\sqrt{2} \implies (X,Y)=(7,5) \implies (x,y)=(3,5).$
$(1+1\sqrt{2})^{5} = 41+29\sqrt{2} \implies (X,Y)=(41,29) \implies (x,y)=(20,29).$
$(1+1\sqrt{2})^{7} = 239+169\sqrt{2} \implies (X,Y)=(239,169) \implies (x,y)=(119, 169).$
Thus, we can get the infinitely many integer solutions of equation $(1).$
<code>                          [x,y]
                          [3, 5],
                          [20, 29],
                          [119, 169],
                          [696, 985],
                          [4059, 5741],
                          [23660, 33461],
                          [137903, 195025],
                          [803760, 1136689],
                          [4684659, 6625109],
                          [27304196, 38613965],
</code>


data-equalizer not working on rowless columns

Question: I'm trying to design a page compatible with different display size, I have 6 elements to use and I want to show 3 on each line for large to landscape devices, 2 per line on medium and 1 per line on small devices. I have done this with the following structure:

so far so good, in the logic at least, the problem is when you have a very small text on some element, let's say that you have a very short text on the 3rd element and a 50-100 characters on the other elements. What happens in this condition on large+ screens is that the 4th and 6th elements are being placed belowthe 3rd and the data-equalizer stop working. The 5th element goes below the 1st and there is a space below the 2nd element.
As you can see I'm using only one row so that the content can rearrange depending on screen size, however this is not working for me, what am I doing wrong?
Answer: Found the answer on ZURB forum, here is what I was told to do:

Link to the answer: http://foundation.zurb.com/forum/posts/35716
Link to docs: http://foundation.zurb.com/docs/components/block_grid.html


Back to square 1...

Question: A friend of mine was telling me about one of the problems, which he described thus:

As you can see, the answer to the toy problem presented here is reportedly 13. However, I don't understand how they arrive at that number.
As I understand it, this diagram is a Markov chain and the problem can be solved by premultiplying the initial-state vector
$$
x_0 = [1,0,0]^T
$$
by the following (left) stochastic matrix
$$
T =
\begin{bmatrix}
0.5 & 0.75 & 0 \\
0.5 & 0    & 0 \\
0   & 0.25 & 1 \\
\end{bmatrix}
$$
(where $T_{ij}$ corresponds to the probability of a transition to state $i$ while in state $j$)
as many times ($k$) as it takes for the last entry in the state vector to be $\geq 0.5$. The answer is then $k+1$, because you need to add $1$ for the very first turn (the one that initially takes you to Square 1).
According to my reasoning, the answer should be 10, not 13. How did they arrive at 13?
Comment: Certainly related: ["Back to square one" problem](http://math.stackexchange.com/questions/980270/back-to-square-one-problem).  To the extent that a careful examination of the code shown is sought, this makes the Question off-topic for Math.SE, but note that "hitting times" can be calculated by the techniques discussed in the earlier Question.
Comment: @hardmath Thanks for the link; I'll give it a read. I've only included my code as a supporting explanation for my reasoning. I don't expect answerers to "debug" it for me. I just want to know where my reasoning is wrong.
Comment: I'm not voting to close.  I think a tailored explanation of why 13 is the answer to the "toy problem" is different enough to get a good Answer here.  Perhaps the code can be de-emphasized somehow, but I'm not too hung up on appearances.
Comment: I considered (but decided against) voting to close both for being a duplicate and for being off-topic.  As is, it's easy for a Reader to mistakenly think it's the first time the general problem is being raised here.
Comment: @hardmath The recurrence in the highest-voted answer to the question you link to doesn't make sense to me; it seems to be backward or something. In particular, we're looking for $f(n)$, not $f(0)$.
Comment: Okay, I'll take a look.
Answer: Multiplying an initial vector by the k-th power of the transition matrix you will only get the distribution of your state at step k. You need to learn/return to the basics of probability theory and Markov chains. I can recommend Grimmett and Stirzaker's book Probability and Random Processes.
Comment: It's a sound observation, but this would be better as a Comment since it doesn't attempt to explain why "the answer to the toy problem presented here is reportedly 13".
Comment: It answers to the question "Where did I go wrong" and points to a concrete literature where to learn basic notions such as the expectation.
Comment: I know that "multiplying an initial vector by the $k$-th power of the transition matrix you will only get the distribution of your state at step $k$". But shouldn't the smallest $k$ such that the probability to be on the last square be $\geq .5$, plus one, be the solution? Your answer is too handwavy... Can you explain why the solution to the toy problem is 13?
Comment: @Valentas:  The general problem has already been dealt with by a previous Math.SE Question (see link in Comments above).  I think the opportunity is there to provide a more detailed Answer to the specifics of the "toy problem".
Comment: @hardmath: agreed, sorry did not see the newest comments.
Answer: Here is the simple recursion solution:-
$$F(i) = 1+ \frac{F(i-1)}{p(i-1)} ,\,\ i= 0,1,2,3....n\\
    F(0)=0$$
According to given problem,
    $$F(3) = 1+ \frac{F(2)}{.25}$$
    $$F(2) = 1+ \frac{F(1)}{.5}$$
    $$F(1) = 1+ \frac{F(0)}{p(0)}=1$$
    So,$$F(2) = 1+ 1\cdot2 =3$$
    So,$$F(3) = 1+ 3\cdot4 = 13$$
Comment: Use Mathjax to format your equations.
Comment: Thanks @Aniket !, I'm new to the community......   Feel free to edit! :)

Back to square 1...


Expression of a smooth multivariable function around a point

Question: In Robert Wald's General Relativity, he states that

If $F: \mathbb{R}^n \to \mathbb{R}$ is $C^\infty$, then for each $a=(a^1, \dots, a^n) \in \mathbb{R}^n$ there exist $C^\infty$ functions $H_\mu$ such that for all $x \in \mathbb{R}^n$ we have
$$ F(x) = F(a) + \sum_{\mu = 1}^n (x^\mu - a^\mu)H_\mu(x) $$
Furthermore, we have
$$ H_\mu(a) = \frac{\partial F}{\partial x^\mu}\Bigr|_{x=a}$$

Where the superscripts $x^\mu$ indicate indices, not exponents.
Problem 2 at the end of the chapter then gives a hint to prove this by induction:

(Hint: For $n=1$, use the identity
$$ F(x) - F(a) = (x-a) \int_0^1 F'[t(x-a) + a]dt$$
then prove it for general $n$ by induction.)

I've seen other ways of proving the statement, but for the life of me I can't see how to prove it by induction. Any insight would be greatly appreciated!
Comment: It's crazy to do induction rather than the FTC altogether. But the author is thinking that the chain rule gives you a sum of $n$ terms and wants you to break it up into the sum of $n-1$ and a last term.
Comment: Look closer - this is about first order approximations in $n$ dimensions, not $n$-th order approximations in one dimension. Using induction on the number of dimensions is an easy way to apply the one-dimensional FTC to multiple dimensions. The superscripts here are indices, not powers.
Answer: The base case proceeds as follows. For a smooth function $F: \mathbb{R} \to \mathbb{R}$ and some $a \in \mathbb{R}$, we can construct $H(x) = \frac{F(x) - F(a)}{x-a}$ so that $F(x) - F(a) = (x-a)H(x)$ and $H(a) = \frac{d}{dx}F(x) \Bigr|_{x=a}$. Such an $H$ is smooth and well-defined on $\mathbb{R}$ because $F$ is smooth.
Now suppose the proposition is true for $n<k-1$. Given a smooth function $F: \mathbb{R}^k \to \mathbb{R}$ and some $a \in \mathbb{R}^k$, we can consider fixing the last coordinate $x^k = a^k$, letting us apply the inductive proposition
$$ F(x^1, \dots, x^{k-1}, a^k) = F(a) + \sum_{\mu=1}^{k-1} (x^\mu - a^\mu) H_\mu(x^1, \dots, x^{k-1})$$
Now if we define
$$ H_k(x) \equiv \frac{F(x) - F(x^1, \dots, x^{k-1}, a^k)}{x^k - a^k} $$
We find that $H_k$ is smooth and well-defined on $\mathbb{R}^k$ again because $F$ is smooth, and we recover the intended proposition
$$ F(x) - F(a) = \sum_{\mu=1}^{k-1} (x^\mu - a^\mu) H_\mu(x^1, \dots, x^{k-1}) + (x^k - a^k)H_k(x) = \sum_{\mu=1}^{k} (x^\mu - a^\mu) H_\mu(x)$$
and
$$ H_k(x) = \frac{\partial}{\partial x^k} F(x) \Bigr|_{x=a} $$
Comment: One problem I have with this proof is how the $H_\mu$ only depend on indices less than $\mu$. I feel like I may be making a subtle error, but can't find it.


Keyboard Localization of type Decimal Pad

Question: I am trying below code for keyboard localization which work in Swift3.
I have taken this code from below link:-
iPhone: Change Keyboard language programmatically
But it gives below error in Swift 4.
a) let language = type.getKeyboardLanguage()
for this line it gives error as:- Expression type '(_) -> _' is ambiguous without more context
b)In switch case for below code
switch self {
        case .one:
            return "en"
        case .two:
            return "ru"
        case .three:
            return ""
        case .four:
            return ""
        }

It gives error as Pattern cannot match values of type 'ViewController' for cases in Switch.
override var textInputMode: UITextInputMode? {

        let language = type.getKeyboardLanguage()
        if language.isEmpty {
            return super.textInputMode

        } else {
            for tim in UITextInputMode.activeInputModes {
                if tim.primaryLanguage!.contains(language) {
                    return tim
                }
            }
            return super.textInputMode
        }

    }
    func getKeyboardLanguage() -> String {
        switch self {
        case .one:
            return "en"
        case .two:
            return "ru"
        case .three:
            return ""
        case .four:
            return ""
        }

    }

Answer: You just need to define a type that your function is expected to return.
let language: SomeTypeHere = type.getKeyboardLanguage()

Cheers!
Comment: it is giving error to type. I have tried with below line:-
 let language : String = type.getKeyboardLanguage()
Still it is giving error as Expression type '(_) -> _' is ambiguous without more context.
Comment: Then you need to check where you define the type.getKeyboardLanguage() function.  You might have some  generics in there that cause this to not work in Swift4


Is every "almost" isomorphism an isomorphism?

Question: Let $f:A \mapsto B$, $g:B \mapsto A$ and $h:B \mapsto B$ be such that $g \circ f=\operatorname{id}_A$ and $f \circ g \circ h=\operatorname{id}_B=h \circ f \circ g$. Can we conclude $h=\operatorname{id}_B$? Are there any "naturally occurring" categories where this is false?
We certainly have that $f$ and $g$ are bimorphisms (i.e. simultaneously monomorphisms and epimorphisms), and that $h$ is an automorphism of $B$ (with $h^{-1}=f \circ g$).
In a balanced category such as $\mathbf{Set}$, every bimorphism would be an isomorphism, hence $f$ would have an inverse $f^{-1}$, and we could conclude $f^{-1}=g$ from $g \circ f=\operatorname{id}_A$, which would show $h=\operatorname{id}_B$.
The simplest way to construct a category where $h\neq\operatorname{id}_B$ seems to be to take $\operatorname{hom}(A,A)=\{\operatorname{id}_A\}$, $\operatorname{hom}(B,B)=\{\operatorname{id}_B,h\}$, $\operatorname{hom}(B,A)=\{g\}$ and $\operatorname{hom}(A,B)=\{f,h \circ f\}$. So there are categories where $h=\operatorname{id}_B$ is false.  What about a counterexample for the case $A=B$? Edit: Constructing a counterexample without first generating the set of all "valid" relations between $f$, $g$ and $h$ is difficult, because consequences/violations of associativity can easily be overlooked. But if we know the set of all "valid" relations, then we already know the answer.
I have the impression that none of the standard examples of non-balanced categories like posets, quivers, category of rings, or topological categories could provide an example where $h=\operatorname{id}_B$ is false. Is there a name for such an "almost" isomorphism between $A$ and $B$ as provided by $f$, $g$ and $h$, as well as a name for the categories where such "almost" isomorphism are always a real isomorphism?
Comment: A category with one object is a monoid. Consider the free monoid generated by letters f, g and h subject to the relations generated by gf=1 and fgh=1=hfg. Is h equal to 1?
Comment: @MarianoSuárez-Alvarez Even the relations $gf=1$ and $fgh=1$ seem sufficient to show $h=1$, if I follow the proof from your answer: $gh=1gh=gfgh=g1=g$, so $fg=fgh=1$ and $1=fgh=1h=h$.
Answer: Notice that $gh=1gh=gfgh=g1=g$, so that $fg=fgh=1$. It follows that $f$ and $g$ are inverse isomorphisms.
The relation $hfg=1$ has not been used here, so it can be omitted.
Comment: Notice that in your example, the composition $f\circ g$ has to be a morphism $A\to A$ and you decided that $\hom(A,A)$ only contains the identity.


Integral representation for $\log$ of operator

Question: How can one prove that
$$ (\log\det\cal A=) \operatorname{Tr} \log \cal{A} =
\int_{\epsilon}^\infty \frac{\mathrm{d}s}{s} \operatorname{Tr}
e^{-s \mathcal{A}},$$
for a sufficiently well-behaved operator $\cal{A}?$
How mathematically rigorous is the expression?
I'm looking at the $d=2$ Euclidean case, as discussed for $\cal{A}=-\Delta + m^2$ in paragraph 32.2.1 of the book Mirror Symmetry by Vafa et al.
Comment: Looks an awful lot like a Laplace transform.
Answer: First of all, I think  there should be a minus sign in front of $\Delta$ : $A= (- \Delta + m^2)$ so that it is positive.
Assume that $A$ has pure point spectrum as it happens for the operator you wrote in compact manifolds with dimension $n$ (there is a unique self-adjoint extension of the said $A$ when defining the initial domain to be the space of $C^\infty$ functions on that manifold). It is possible to prove that the eigenvalues diverge as fast as pictured by a known asymptotic formula due to Weyl:
$$\lim_{j \to +\infty}\lambda_j^{n/2}/j = C_n >0\qquad (1)$$
where eigenvalues are counted taking their (finite) multiplicity  into account: $$0 \leq ... \leq \lambda_j \leq \lambda_{j+1} \leq ...\to +\infty$$
So $e^{-tA}$ is trace class because  has non-negative eigenvalues $e^{-t\lambda_j}$ with finite multiplicity such that $\sum_j  e^{-t\lambda_j} < +\infty$ as you can prove form (1).
$$\int_{\epsilon}^\infty \frac{\mathrm{d}s}{s} \operatorname{Tr}
e^{-s A} = \int_{\epsilon}^\infty \frac{{d}s}{s}\sum_j  e^{-s\lambda_j} =
\sum_j \int_{\epsilon}^\infty \frac{{d}s}{s} e^{-s\lambda_j} $$
I have swapped the symbol of integral and that of sum, because, once-again (1) easily implies that the function $(j,s) \mapsto e^{-s\lambda_j}/s$ is (absolutely) integrable  in the product measure, so I could exploit Fubini-Tonelli theorem.
Since:
$$\ln \lambda = \lim_{\epsilon \to 0^+}\left(\int_\epsilon^{+\infty} \frac{e^{-\lambda t}}{t} dt + (\gamma -\ln \epsilon)\right)$$
we can write:
$$\int_{\epsilon}^\infty \frac{\mathrm{d}s}{s} \operatorname{Tr}
e^{-s A} = \sum_j \ln \lambda_j  +   \sum_j  O(\ln \epsilon)\:.$$
Up to a divergent part one has to renormalize, the  found result can be re-written as:
$$\int_{0^+}^\infty \frac{\mathrm{d}s}{s} \operatorname{Tr}
e^{-s A} = tr \ln A$$
Actually, the point is that $tr\ln A$ is not defined,for $A= (-\Delta +m^2)$ and needs to be regularized.
Comment: You're right, there is a small typo in the book: the covariant derivative should be $D_\mu=\partial_\mu -i e A_\mu$ such that $A_\mu$ is real, then the operator we get is $\phi^* \cal{A} \phi = - \phi^* D_\mu D_\mu \phi,$ which as you correctly pointed out is the negative of the laplacian, and has thus positive eigenvalues. Thanks for the nice answer
Comment: I had to search a while to find the relation between $\ln\lambda$ and the integral - it's not even on the lengthy Wikipedia page on the incomplete Gamma function. Do you use the Exponential integral $\mathrm{Ei}$ often?
Comment: Actually in the past I made research in heat kernel theory, zeta function regularization and all that and that integral relation I used was quite standard, I just searched through some old paper of mine containing these formulas. Yes, I remember that there is some relation with $Ei$...
Answer: Here is an absolutely non-rigorous start of an explanation.
Assume that all the eigenvalues $a_i$ of $\mathcal A$ are positive (which is the case of the inverse propagator you give), then
$$\int_\epsilon^\infty \frac{ds}{s}\operatorname{Tr} e^{-s\mathcal A}=\sum_i\int_\epsilon^\infty \frac{ds}{s}e^{-s a_i}=-\sum_i Ei(-\epsilon a_i),$$
where $Ei(x)$ is the Exponential integral.
Now, in the limit $\epsilon \to 0$ (that is assumed here ?), we get
$$-\sum_i Ei(-\epsilon a_i)=div.-\sum_i \ln a_i, $$
where $div.=-\sum_i (\gamma+\ln \epsilon)$ is a divergent contribution in the limit $\epsilon\to0$ ($\gamma$ is the Euler constant).
So, up to a sign and an infinite constant, we're good...
Comment: You could clean this up by noting that $e^{-s a}/s$ is $\int_{0}^a e^{-s a} - 1$, then flipping the order of integration. This gets rid of the Exponential integral, which I always like to do, and it involves talking an integral with respect to a constant, which I can't resist. Also should note that you don't need eigenvalues, just the diagonal elements $a_{nn} = \langle n | \mathcal{A} |n \rangle$, so you probably don't even need $\mathcal{A}$ to have eigenvalues/be Hermitian/whatever.
Comment: @webb: I don't really see the point of doing that, how does it help ? And I'm pretty sure that the eigenvalues are needed, or you have to tell me how you define the log of a matrix.
Answer: Hint: Try a Laplace Transformation.
Answer: Usually one starts these things by using $\operatorname{tr} \ln A = \ln\, \operatorname{det} A$.
Answer: @adam: "you have to tell me how you define the log of a matrix"
you define log of a matrix the same way you define, for instance, its exponential - via Taylor expansion, when it exists. Now, the nice thing about that is you get terms that are powers of the matrix (remember, trace of a sum of terms is the sum of traces). For these, if the matrix can be written as $A = UVU^{-1}$ you end up with $Tr(A^n) = Tr(UVU^{-1}\ldots UVU^{-1}) = Tr(UV^nU^{-1}) = Tr(V^n)$ where $V$ is diagonal (hopefully positive definite for the log to exist). This will clearly mean that $Tr(\log(A)) = Tr(\log(V))$ and since $V = diag\{V_i|i\in \overline{1,n}\}$ is diagonal it gives
$Tr(\log(V)) = Tr(diag\{\log(V_i)\}) = \Sigma_i \log(V_i) = \log(\Pi_i V_i) = \log(\det(V)) = \log(\det(A))$


Stream Icecast using Gstreamer

Question: I'm designing a program to stream an icecast server (radio.clarkson.edu). Ultimately it will be written in Python3, but for now I'm using gst-launch to test the pipeline. I've been working on Debian Jessie and using gstreamer-1.0. Using a file on Wikimedia, I was able to play pretty easily using:
url=https://upload.wikimedia.org/wikipedia/commons/0/0c/Muriel-Nguyen-Xuan-Korsakov-Flight-of-the-bumblebee.flac.oga
gst-launch-1.0 -v souphttpsrc location =$url ! decodebin ! audioconvert ! audioresample ! alsasink

Running the same commands with my stream, I get the output:
Setting pipeline to PAUSED ...
Pipeline is PREROLLING ...
/GstPipeline:pipeline0/GstDecodeBin:decodebin0/GstTypeFindElement:typefind.GstPad:src: caps = text/uri-list
Missing element: text/uri-list decoder
ERROR: from element /GstPipeline:pipeline0/GstDecodeBin:decodebin0: Your GStreamer installation is missing a plug-in.
Additional debug info:
gstdecodebin2.c(3977): gst_decode_bin_expose (): /GstPipeline:pipeline0/GstDecodeBin:decodebin0:
no suitable plugins found
ERROR: pipeline doesn't want to preroll.
Setting pipeline to NULL ...
/GstPipeline:pipeline0/GstDecodeBin:decodebin0/GstTypeFindElement:typefind.GstPad:src: caps = "NULL"
Freeing pipeline ...

I have tried too many other pipelines to put on one post, but I can answer any other questions.
Thank you
Answer: By now you probably have solved that problem, but still here's an idea: text/uri-list indicates that you didn't hand an actual stream to gstreamer, but rather a (textual) playlist that contains stream addresses. I guess gstreamer can't handle those, hence you need to parse them beforehand and then hand an actual audio stream address to it.
Comment: Actually I think I ended up using VLC, which had other problems. And then the project kind of fell apart, I graduated, and it has since been disassembled and recycled. Thanks for the answer though!

Stream Icecast using Gstreamer


Gradlew test not working

Question: The following command does not execute any test:
gradlew test :app:testDebug --continue

I must mention I need this line to use it in a Continuous Integration server. I have a few test classes (one for UI testing - espresso). All my tests inherit TestCase class
However, if I right-click the tests folder and choose run tests all the tests begin starting, but why this command does not work?
The logs:
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
..............................
:app:compileReleaseUnitTestSources UP-TO-DATE
:app:assembleReleaseUnitTest UP-TO-DATE
:app:testReleaseUnitTest UP-TO-DATE
:app:test UP-TO-DATE

Comment: What sort of error are you seeing? Try this: ./gradlew test :app:testDebug --continue
Comment: @davehenry - I posted the logs (no error, simply the tests won't run).
Comment: @AlexandruCircus Did you managed to fix this? I struggling with this issue as well. My Android test `./gradlew connectedAndroidTest` works fine, but the test in `src/test/java` doesn't run at all.
Comment: @wint Simply moved unit test classes from src/test/java into android default test folder, and used this command: "./gradlew test --continue". But this command will fail if no emulator or device was found, so in my bitrise workflow I added another step of starting an android emulator BEFORE performing the testing step.
Comment: Have you tried to perform `./gradlew test`?
Answer: You could use ./gradlew testDebug --stacktrace to only run debug tests

Gradlew test not working


How to show this inequality $\sum\sqrt{\frac{x}{x+2y+z}}\le 2$

Question: Let $x,y,z,w>0$ show that
$$\sqrt{\dfrac{x}{x+2y+z}}+\sqrt{\dfrac{y}{y+2z+w}}+\sqrt{\dfrac{z}{z+2w+x}}+\sqrt{\dfrac{w}{w+2x+y}}\le 2$$
I tried C-S, but without success.
Comment: what do you mean by C-S?
Comment: @Kiran  Cauchy-Schwarz inequality
Answer: My proof was total wrong. I am sorry.
I think the following reasoning helps.
Let $\frac{x}{x+2y+z}=\frac{a^2}{4}$, $\frac{y}{y+2z+w}=\frac{b^2}{4}$, $\frac{z}{z+2w+x}=\frac{c^2}{4}$ and $\frac{w}{w+2x+y}=\frac{d^2}{4}$, where $a$, $b$, $c$ and $d$ are positives.
Hence, we get that the system
$$
\left\{\begin{matrix}
(a^2-4)x+2a^2y+a^2z+0w=0\\
0x+(b^2-4)y+2b^2z+b^2w=0\\
c^2x+0y+(c^2-4)z+2c^2w=0\\
2d^2x+d^2y+0z+(d^2-4)w=0
\end{matrix}\right.
$$
has infinitely many solutions, which gives
$$
\det\left(\begin{matrix}
a^2-4&2a^2&a^2&0\\
0&b^2-4&2b^2&b^2\\
c^2&0&c^2-4&2c^2\\
2d^2&d^2&0&d^2-4
\end{matrix}\right)=0
$$ or
$$a^2b^2+b^2c^2+c^2d^2+d^2a^2+16=4(a^2+b^2+c^2+d^2)+a^2b^2c^2+a^2b^2d^2+a^2c^2d^2+b^2c^2d^2$$
and we need to prove that
$$a+b+c+d\leq4.$$
Let $a+b+c+d>4$ and $d=kd'$, where $k>0$ and $a+b+c+d'=4$.
Hence, $k>1$ and
$$a^2b^2+b^2c^2+k^2c^2d'^2+k^2d'^2a^2+16=$$
$$=4(a^2+b^2+c^2+k^2d'^2)+a^2b^2c^2+k^2a^2b^2d'^2+k^2a^2c^2d'^2+k^2b^2c^2d'^2$$ or
$$a^2b^2+b^2c^2+16-4(a^2+b^2+c^2)-a^2b^2c^2=$$
$$=k^2d'^2(a^2b^2+a^2c^2+b^2c^2-a^2-c^2+4)$$
and since $$4-a^2-c^2=4-\frac{4x}{x+2y+z}-\frac{4z}{z+2w+x}>4\left(1-\frac{x}{x+z}-\frac{z}{z+x}\right)=0,$$
we obtain
$$a^2b^2+b^2c^2+16-4(a^2+b^2+c^2)-a^2b^2c^2=$$
$$=k^2d'^2(a^2b^2+a^2c^2+b^2c^2-a^2-c^2+4)>$$
$$>d'^2(a^2b^2+a^2c^2+b^2c^2-a^2-c^2+4),$$
which is contradiction because we'll prove now that
$$a^2b^2+b^2c^2+16-4(a^2+b^2+c^2)-a^2b^2c^2\leq$$
$$\leq d'^2(a^2b^2+a^2c^2+b^2c^2-a^2-c^2+4).$$
We'll replace again $d'$ on $d$ and we need to prove that
$$a^2b^2+b^2c^2+c^2d^2+d^2a^2+16\leq4(a^2+b^2+c^2+d^2)+a^2b^2c^2+a^2b^2d^2+a^2c^2d^2+b^2c^2d^2$$ or
$$a^2b^2+b^2c^2+c^2d^2+d^2a^2+a^2c^2+b^2d^2+16\leq$$
$$\leq4(a^2+b^2+c^2+d^2)+a^2b^2c^2+a^2b^2d^2+a^2c^2d^2+b^2c^2d^2+a^2c^2+b^2d^2.$$
By AM-GM $a^2c^2+b^2d^2\geq2abcd$.
Id est, it remains to prove the following inequality.
Let $a$, $b$, $c$ and $d$ be positive numbers such that $a+b+c+d=4$. Prove that:
$$a^2b^2+b^2c^2+c^2d^2+d^2a^2+a^2c^2+b^2d^2+16\leq$$
$$\leq4(a^2+b^2+c^2+d^2)+a^2b^2c^2+a^2b^2d^2+a^2c^2d^2+b^2c^2d^2+2abcd,$$
which is true, but my proof of this nice inequality is still very ugly.
Comment: Thanks,Nice,can you find $\sum_{cyc}\sqrt{\dfrac{x}{ax+y+z}}\le4\sqrt{\frac{1}{a+2}}$\
Comment: Find $a$ range such inequality hold
Answer: By C-S:
$(LHS)^2\le \sum_{cyc}a(b+2c+d) \sum_{cyc}\frac{1}{(a+2b+c)(b+2c+d)}$
$\sum_{cyc}a(b+2c+d) \sum_{cyc}\frac{1}{(a+2b+c)(b+2c+d)}\le 4 \ \  \iff \ \ (a-c)^2(b-d)^2\ge 0$


Reference Request: First Eigenvalue of Elliptic Operator

Question: Let $S^2$ be the 2-sphere equipped with some Riemannian metric. Let $\Delta$ denote the Laplace-Beltrami operator. Let $f\geq 0$ be a smooth, non-negative function such that $f(x)>0$ at some $x\in S^2$. Consider the linear second order differential operator $L=-\Delta+f$.
I am interested in the eigenvalues of this operator. Specifically, I would like to show that for all the eigenvalues $\lambda$  we have $\lambda \geq \lambda_0 >0$.
Assuming $u$ is an eigenfunction with eigenvalue $\lambda$, assuming appropriate regularity, and integrating by parts, we have
$\lambda ||u||_{L^2}=\int_{S^2} uLu=\int_{S^2}\left( |\nabla u|^2 + fu^2 \right) \geq 0$
showing $\lambda \geq 0$. I think I can use Theorem 8.38 in Gilbarg-Trudinger which says that the minimum eigenvalue is simple and has a positive eigenfunction. In our case this then shows the first eigenvalue is positive. However, this book deals with domains in $\mathbb{R}^n$ rather than Riemannian manifolds, but I assume that all the results can be translated to the manifold setting. I'd just like confirmation that this is indeed the case.
Many thanks!
Answer: Yes, it is the case. I think there are two different ways to approach this problem. I think the second one is more direct if you already know the behavior of the operator $-\Delta$ (without the potential $f\,$). Let's start by applying some spectral analysis (this is why I prefer the second approach).
First of all, note that $-\Delta+f$ is essentially self-adjoint in $C_0^\infty(S^2)$ and self-adjoint in $H^2(S^2)$. Thus, its spectrum is non-empty and it is contained in $\mathbb{R}$. Moreover, there is a basic result in Spectral Theory saying that: Let $T$ be a self-adjoint operator. Then, the spectrum of $T$ is contained in $[M,\infty)$ if and only if $T$ is semi-bounded from below by $$
\langle Tu,u\rangle \geq M\Vert u\Vert^2, \qquad \forall u\in D(T).
$$
Thus, we can derive a first piece of information following your procedure. In fact, by integration by parts, it is easy to prove that spectrum of $-\Delta+f$ is contained in $[0,\infty)$.
Now, let's try to follow a different approach. First of all, let's recall Poincare's inequality (valid for $S^2$) $$
\int_M \vert \nabla g\vert^2 \geq \lambda_1\int_M \vert g\vert^2,
$$
where $\lambda_1$ is the first eigenvalue of $-\Delta$. Thus, following you procedure again, integrating by parts and applying Poincare's inequality, we see that the first eigenvalue $\lambda_1^\star$ of $-\Delta+f$ satisfies $\lambda_1^\star\geq \lambda_1$ (due to the positivity of $f\,$). Thus, if you already know that $\lambda_1>0$, we conclude the property we are looking for.


How to explain ANOVA output from a multiple regression?

Question: If I do a multiple regression such as:
df<-data.frame(y1=rnorm(100,2,3),
y2=rnorm(100,3,2),
x1=rbinom(100,1,0.5),
x2=rnorm(100,100,10))

fit<-lm(cbind(y1,y2)~x1+x2,data=df)
> anova(fit)
Analysis of Variance Table

            Df  Pillai approx F num Df den Df Pr(>F)
(Intercept)  1 0.75423  147.306      2     96 <2e-16 ***
x1           1 0.00720    0.348      2     96 0.7069
x2           1 0.00928    0.450      2     96 0.6391
Residuals   97
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

I am wondering how to explain this ANOVA object where two models have different responses and the same set of predictors.
Answer: The x2 line looks at the added information by adding x2 to the model above and beyond the intercept and x1; the x1 line looks at adding x1 to the intercept (ignoring x2) and the intercept line compares fitting an intercept to having the mean be 0.
In all cases the test is of whether the term aids in predicting all of the response variables jointly (assumes a multivariate normal distribution of the $y$s conditional on the $x$s).
This link may be helpful as a starting place to learn more about the Pillai trace statistic and other options.


Net present value given cash flows for 2 different projects

Question: Project P requires an investment of $4000$ at time $0$. The investment pays $2000$ at time $1$ and $4000$ at time $2$.
Project Q requires an investment of X at time 2. The investment pays $2000$ at time $0$ and $4000$ at time $1$.
The net present values of the $2$ projects are equal at an investment rate of $10$%. Calculate X.
$4000+\frac{2000}{1.10}+\frac{4000}{1.10^2}=2000+\frac{4000}{1.10}+\frac{X}{1.10^2}$
$\therefore X=4220$
But the answer is $5460$
Answer: Be careful of whether you have to invest or whether you are paid.
Solve for $x$:
$$-4000+\frac{2000}{1.1}+\frac{4000}{1.1^2}=2000+\frac{4000}{1.1}-\frac{x}{1.1^2}$$


How access in ruby a JSON attribute within inline string variable?

Question: Is it possible to do smth. like this:
puts "DEBUG: #{@search_params[0]["param"]}"
puts "DEBUG: #{@search_params[0][\"param\"]}"
puts "DEBUG: #{@search_params[0]['param']}"
puts 'DEBUG: #{@search_params[0]['param']}'

where
@search_params = [{param: "abc"}, {param: "def"}]

but in that way, that @search_params[0]["param"] will be substituted to a JSON argument param in a JSON document @search_params?
P.S. puts "DEBUG: #{@search_params[0].param}" and puts "DEBUG: #{@search_params[0][:param]}" do not work.
Answer: You should use like below :
@search_params = [{param: "abc"},{param: "def"}]
puts "DEBUG: #{@search_params[0][:param]}"
# >> DEBUG: abc

You have symbol key :param,not the string.
Comment: is it possible to define so: `@search_params = [{"param": "abc"}, {"param": "def"}]`?
Comment: @static **NO**.Type the same in your IRB,you will get the answer.. :)
Comment: @static see the fourth paragraph here - http://www.ruby-doc.org/core-2.0.0/Hash.html


How to do dynamically a Altorouter

Question: I used Altorouter in PHP, and I try to dynamic my router.
I have an architecture specific with folders, sub-folders, sub-sub-folders.
I have try to do this
//dynamic routage for root main pages
$router->map( 'GET', '/[:pageName]', 'HomeControler::pageRedirect');

//dynamic routage for subfolder pages
$router->map( 'GET', '/[:folder]/[:pageName]', '
HomeControler::subPageRedirect');

That's working, but I just matching with folder / page.
I wont doing this method for all sub-folders.
How can I detect folders, sub-folders, automatically ?
And In my controller,
I control the folders like that ?
// Dynamic mapping to pages
public static function pageRedirect($pageName) {
    self::redirectTo(dirname(__FILE__) . "/../../front/$pageName.php");
}

And I do condition if he doesn't find in this pages ?
Comment: Are you going to have dynamic folders with files?
Comment: What do you mean with "dynamic folders with files"?
Comment: Will your code  create some dynamic folders with files which you will need to map with the urls at runtime?
Comment: Yes when I will create folders, subfolders or files, I mapping them and write a correctly URL
Comment: If you gonna have fixed number of folders and subfolders then you just don't need to add additional code to map those urls with folder and files , You should statically define those.
Comment: @RopAliMunshi Thx a lot for your answers. I'm a newbie in PHP and I don't understand correctly what you mean. Then you suggest to not replace my code with a dinamycally mapping ?
Comment: Yes if you already know how many folder or sub-folders you gonna have.
Comment: But if a non-programmer wants to create many folders, subfolders and pages tomorrow, that's will not mapping alone right ?
Answer: You could do
 $router->map('GET', '/[*:target]', 'yourController')

This will map any request to your controller. How you interpret target in your controller is up to you (looking in folders etc.).

How to do dynamically a Altorouter


Storing variable names in list

Question: I have the following the list:
lst_gws = ["gw1", "gw2", "gw3"]

gw1 = ["gw1-123", "gw1-234"]
gw2 = ["gw2-445", "gw2-332"]
gw3 = ["gw3-257", "gw3-321"]

Is it possible to loop through the list and print out the value of each of them, something like:
for i in lst_gws:
    print i

but printing the actual value and not the name.
Comment: If you ever find yourself storing strings which correspond to variable names, consider storing them in a dict instead.
Answer: You can do:
for i in lst_gws:
    print(locals()[i])

which would print them out as intended (locals() allows you to access any local variables):
>>> lst_gws = ["gw1", "gw2", "gw3"]
>>>
>>> gw1 = ["gw1-123", "gw1-234"]
>>> gw2 = ["gw2-445", "gw2-332"]
>>> gw3 = ["gw3-257", "gw3-321"]
>>> for i in lst_gws:
...     print(locals()[i])
...
['gw1-123', 'gw1-234']
['gw2-445', 'gw2-332']
['gw3-257', 'gw3-321']

Answer: How about using a dict?
lst_gws = {
    "gw1" : ["gw1-123", "gw1-234"],
    "gw2" : ["gw2-445", "gw2-332"],
    "gw3" : ["gw3-257", "gw3-321"],
}

for name in lst_gws:
    print lst_gws[name]

Answer: You can access the local and global variable dictionary with locals() and globals().
They are dictionaries where the key is the name of the variable and the value is its value...
x = 3
y = 2
z = [1, 2, 3]
vars = ["x", "y", "z"]

for name in vars:
    print(locals()[name])

Storing variable names in list


Tapping 3 times on one leg and 4 times on another leg in 4 beats. What is it called and how to do it?

Question: I'm new to the "music scene". Well, at least the more technical parts of it.
In ninth grade, our music teacher taught us how to do a tapping/drumming thing where we tap 3 times on one leg and 4 times on the other in 4 beats.
What is this called? How to do it?
Comment: More fun with [7:11](https://www.youtube.com/watch?v=U9CgR2Y6XO4) :)
Comment: A pretty great extreme example of Polyrhythms is basically anything by Meshuggah, if you're able to endure extreme metal :P e.g. [Perpetual Black Second](https://www.youtube.com/watch?v=sJGF_5L0bBY) starts with 7/8 over 4/4, then 9/8 over 4/4 and at a point goes 13/8, 14/8, 13/8, 10/8 all over 4/4. There are much better songs but that was a fun one to analyze.
Comment: While we are at it, here's [the mother of all polyrhythms](https://www.youtube.com/watch?v=EkFNdi8gIMY), Dance of Eternity by Dream Theater, beatboxed by a kid with the rhythms on flash cards.
Comment: @Ian I love that tune! But the polyrhythms in that tune aren't that prevalent; the extreme amount of time signature changes is what makes it unique. Well, that and the unusual harmonies in it and the awesomeness with which it was composed. Go DT!
Comment: An easy way to do this is to listen to it played - my go-to reference for a 3:4 polyrhythm is the christmas song [Carol of the Bells](https://en.wikipedia.org/wiki/Carol_of_the_Bells).  Almost everyone has heard it, and if you keep it in your head it's easy to tap out the 3s on one hand and the 4s on the other.
Comment: @J... I was shown it using the phrase "nice cup of tea"; the cadence is about right, at least the way people say it in my regional accent.
Comment: Two one-and-a-half-lets!
Answer: Polyrhythm. It's good thing to learn to do. 4 against 3 is nice, before that you should normally try 3 against 2.
Normally it's hard to do at the start. I had to break it down, splitting the beats. For 3 against 2 you need to split the pattern into 6, for 4 against 3 into 12. I made two grids to show how:

It takes a bit of practice but it is very good for your time feel as a musician to learn to tap these. Normally you use two hands, one doing each line, or a hand and a foot. It helps if you use two "instruments" (whatever comes to hand) that have quite different tones. (And soon you'll have people around you saying "will you stop that tapping" ...)
Comment: Or polymeter? It depends.
Answer: There is a common mnemonic for learning the 3:4 poly-rhythm.  Apologies for the minor profanity, but it goes like so:
Get two people, call them "3" and "4" and give them the following instructions:

3: You're watching a baseball game and your team is in the field, and you're hoping the outfielder can throw the ball to the first-baseman, so you repeat the following phrase over and over: "Pass! God! Catch!"
4: Someone has offered to sell you the Hoover Dam, but you think he's probably a scam artist, so what do you do?  "Pass the dam up" - repeat this phrase over and over again, try to take the same amount of time as the other person.

Both phrases include the word "Pass", so they should say that at the same time.  If you get the timing right, you'll get the following somewhat impolite request at the dinner table:

"Pass the goddamn ketchup".

The natural way of saying of that phrase is basically a perfect 3:4 poly-rhythm.
Comment: I've always heard the mnemonic "pass the bread and butter" but this one makes more sense as a combination of two separate rhythms.
Comment: @JiK Not easily, as I'm at work and don't have any recording equipment, nor am I sure how one would go about uploading a sound clip to SE.  I'll admit that this mnemonic is a bit America-centric, what with the baseball and the Hoover Dam and the ketchup, but I feel like even in most foreign accents it could still fit the 3:4 rhythm.  (I did not invent this, by the way, this is just the way I learned it years ago.)
Comment: _"The natural way of saying of that phrase is basically a perfect 3:4 poly-rhythm."_ I'm not a native English speaker, so I don't know, but I have a hard time believing this. Could you record it?
Comment: The natural way of saying this is not even particularly close to a 3:4 polyrhythm, and I find some of these verbal mnemonics a little dangerous because of this sort of misconception. These mnemonics work because speaking them over the polyrhythms aids memory recall. It is relatively easy to speak them over the polyrhythm because of the stress patterns, but if you hear someone speak those stress patterns in the middle of natural speech, the rhythm they speak it with will vary wildly depending on many factors. They are not a substitute for first precisely counting the rhythm out.
Answer: Overlaying two different evenly-spaced subdivisions with no immediate common factor, is called polyrhythm:
https://en.wikipedia.org/wiki/Polyrhythm

Polyrhythm is the simultaneous use of two or more rhythms that are not readily perceived as deriving from one another, or as simple manifestations of the same meter.

When starting out for the most common polyrhythms involving 2/3/4, if you subdivide down to eighth notes or triplet eighths as the common factor you can find where each larger beat will land.
You can conceptualize 3-over-4 as a case of 3-over-2 with the 2's subdivided once more (which only requires a divisor of 6-per-bar to map them together), and this older question addresses the 3-over-4 case specifically with notation:
How to count polyrhythm 3 against 4 in common time?
(When you get into wackier polyrhythms involving 5s and 7s over base-2's, this mathematical fractions method becomes useless and you start going by feel and true limb independence. But that takes a while of practice internalizing how the basic 3-vs-2 polyrhythms feel, and playing stuff in odd meters with 5's or 7's instead of just 3/4 and 4/4)
Comment: Does your first definition take cross-rhythms into account? https://en.wikipedia.org/wiki/Polyrhythm#Cross-rhythm  I think you can find a common denominator for cross-rhythms, and that's the basic pulse. In the grid example pictured on the Wikipedia page the grid cell is a common denominator, yet it's a polyrhythm, according to Wikipedia's classification.
Comment: True, more accurate would be the major beat pulse, not necessarily a full bar (since hemiolas are by far the most common polyrhythm and they're often crammed into smaller time units than a full measure). Edited.
Answer: The late drum teacher Charles Dowd called this the Rhythm of Life. [I assumed this was in reference to a song utilizing this rhythm.] He taught it in the context of an Afro-Cuban-style pattern on drum set:

The two top-line patterns are equivalent, but it is the bass drum (lower line) that names the underlying pulse. If one instead plays the 2nd pattern with dotted eighth notes on the bass drum, it becomes the 1st pattern, but now thought of in 3/4 time. The perceived change between time signatures comes from changing from 3 to 4 on the bass drum.
Eventually, this is most rewarding when one plays, say, the 2nd pattern with hi-hat on quarters and changes bass drum to dotted eighths. [This makes the 4 over 3 happen between both feet.] Then continue to play the top-line pattern on bell of cymbal and finally include a clave-style rhythm with left hand.
Comment: No idea how true this is, but I have heard that this kind of polyrythm is specially common in African music.
Answer: Splitting up a 4 against 3 pattern into 12 equal parts doesn't really work except at a very slow tempo. You just need to get train your brain (and hands) to do different things at the same time.
A good way to learn to do this is set a metronome to a slow tempo corresponding to one "beat" per bar. Start by tapping with each hand separately for several bars. Then alternate one bar with each hand, and finally put both hands together.
Three against two or three against four is fairly simple. Here's a snippet of organ music where you have 3 against 2 both with your left hand, simultaneously with 5 in your right hand, and 4, 6, 5 and 7 with your feet, on successive beats.
Trying to count out "7 against 5 against 3" by splitting up to beat into 105 tiny parts isn't a practical idea!
Drummers ought to be able to keep four different rhythms going at the same time - one with each hand and one with each foot.
Answer: A small contribution to your "What is it called?" question:
I have heard this type of rhythm described as the "dog-gone" rhythm in a lesson from Bob Brozman, the guitar player, here:
http://www.bobbrozman.com/tip_rhythm.html
Comment: I think maybe the relevant term is ['hambone'](https://en.wikipedia.org/wiki/Juba_dance)


FSLex example solution?

Question: I've been using C/lex for a long time and would like to use F#/fslex now.
I'm comparably well off in C# and in the process of learning F#.
The only thing is that I can't see any project example or template where fslex is properly included in the Visual Studio build process.
Does anyone know where I can find one?
Lots of Greetings!
Volker
Answer: Unfortunately, there is no built-in item template for .fsl files, because FsLex is a part of PowerPack (so Visual Studio cannot expect that it will be installed). It would be definitely useful to have some template that could be installed with PowerPack!
Anyway, if you're looking for a sample project that uses FsLex (and has .fsl files as part of the project), then you can take a look at the F# source code (distribtued with the Visual Studio 2008 MSI/ZIP package). The project that contains .fsl is FSharp.Compiler.fsproj and on my installation, it can be found in C:\Programs Files\FSharp-22.214.171.124\source\fsharp\FSharp.Compiler. Surprisingly, it includes a lexer for the F# language itself :-).
To add FsLex item to the MSBUILD project (which is also Visual Studio project), it uses the following:
<FsLex Include="..\lex.fsl">
  <OtherFlags>--lexlib Internal.Utilities.Text.Lexing</OtherFlags>
  <Link>lex.fsl</Link>
</FsLex>
<Compile Include="lex.fs" />

In case you also needed FsYacc, here is an example (also from FSharp.Compiler.fsproj):
<FsYacc Include="..\pars.fsy">
  <Module>Microsoft.FSharp.Compiler.Parser</Module>
  <Open>Microsoft.FSharp.Compiler</Open>
  <OtherFlags>--internal --lexlib Internal.Utilities.Text.Lexing
              --parslib Internal.Utilities.Text.Parsing</OtherFlags>
  <Link>pars.fsy</Link>
</FsYacc>
<Compile Include="pars.fs" />

Note that you need the FsYacc/FsLex command to invoke the custom tool, but also the Compile command which tells the compiler to include the produced fs file when building the project.
Answer: I'm using the free VS Shell until I finally threaten myself enough to finally buy the full VS, and unless I'm doing something wrong, (and I probably am) none of the normal solutions seem to work for me.  What I do is add the following pre-build events to the project properties:
"C:\Program Files (x86)\FSharpPowerPack-126.96.36.199\bin\fslex.exe"  "$(ProjectDir)\Lexer.fsl"
"C:\Program Files (x86)\FSharpPowerPack-184.108.40.206\bin\fsyacc.exe" "$(ProjectDir)\Parser.fsy" --module Parser

That seems to work well enough for me.  Errors all go to the output window.  If you're on a 32-bit machine, you would remove the (x86) from those paths.
Comment: This is certainly working, although I wish there was proper integration where VS figures out the dependencies correctly.
Answer: Doing a little research it looks like they need to be separate.  I found the following at this blog post ( http://blogs.msdn.com/chrsmith/archive/2008/01/18/fslex-Sample.aspx ) by Chris Smith:

Although you can add an F# Lex Specification file from the Visual Studio Add-In, to run fslex you will need to break to the command line. Fslex.exe is located in your F# distribution's 'bin' directory.

Hope that helps.
Comment: Hm, I see.
I was hoping that there's an item template for a .fsl file with an associated build step and such.
Thanks anyway, I'll first get the VS2010 release and then see how far I can get.

FSLex example solution?


Quadratic Equation relation between roots

Question: If the ratio of the roots of the equation $x^2+px+q=0$ are equal to the ratio of the roots of the equation $x^2+bx+c=0$ , then prove that $p^2c=b^2q$
Let $\alpha \& \beta$ be the roots of first equation then $\alpha + \beta = -p \& \alpha \beta = q$ Let $ \gamma \& \delta$ be the roots of the other equation then $\gamma + \delta = -b ; \gamma \delta =c$  As per the question $ \frac{\alpha}{\beta}=\frac{\gamma}{\delta}$  How to proceed further.
Answer: As you pointed out, $\alpha+\beta=-p$ and $\alpha\beta=q$.
Divide $(\alpha+\beta)^2$ by $\alpha\beta$.  This is allowed, since if one of the roots of each equation is $0$, the result holds trivially. We get
$$\frac{\alpha}{\beta}+2+\frac{\beta}{\alpha}=\frac{p^2}{q}.$$
Similarly,
$$\frac{\gamma}{\delta}+2+\frac{\delta}{\gamma}=\frac{b^2}{c}.$$
Since $\dfrac{\alpha}{\beta}=\dfrac{\gamma}{\delta}$, it follows that $\dfrac{p^2}{q}=\dfrac{b^2}{c}$.
Comment: *Divide $\alpha+\beta$ by $\alpha\beta$.  We get $\frac{\alpha}{\beta}+\frac{\beta}{\alpha}=-\frac{p}{q}$*... No we do not (and I am sure you will find the way so that we do).
Comment: @Did: Thanks, wrong symmetric function.
Comment: thanks a lot....all of you for support.
Answer: Let  $ \frac{\beta}{\alpha}=\frac{\delta}{\gamma}=t$
So, $$\alpha+\beta=-p\implies \alpha+\alpha t=-p\implies \alpha(1+t)=-p;
\alpha\beta=q\implies \alpha\cdot \alpha t=q$$
Similarly, and  $$\gamma(1+t)=-b,\gamma\cdot \gamma t=c$$
On division, $$\frac{ \alpha(1+t)}{\gamma(1+t)}=\frac pb \text{ and }\frac{\alpha\cdot \alpha t}{\gamma\cdot \gamma t}=\frac qc$$
or $$\frac  \alpha\gamma=\frac pb \text{ and }\frac{\alpha^2}{\gamma^2}=\frac qc \text{ if }t(t+1)\ne0$$
Then, equating values of $\left(\frac \alpha \gamma\right)^2, \frac qc=\left(\frac pb\right)^2\implies p^2c=b^2q$
If $t=0,q=0$ and $c=0\implies p^2c=0=b^2q$
If $t+1=0,t=-1,p=0$ and $b=0\implies p^2c=0=b^2q$


Programatically Submitted Form With 'file' Field Throws Notice

Question: This seems to actually be a problem in Drupal itself. In /modules/file/file.field.inc the function file_field_widget_form has a line like this near the bottom (just before the return statement):
$elements['#file_upload_description'] = theme('file_upload_help', array('description' => '', 'upload_validators' => $elements[0]['#upload_validators']));

The issue is a small if condition a few lines back which looks like this:
if (($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta < $field['cardinality']) && empty($form_state['programmed'])) {
    $elements[$delta] = $element;
    ...
    some more stuff
}

Since I am submitting my form programatically with drupal_form_submit, it adds in $form_state['programmed'], thus the if condition fails, $elements[0] does not exist and I get the error
Notice: Undefined offset: 0 in file_field_widget_form()

My form is submitted by a custom routine (in a custom module) that looks a bit like this:
foreach ($field_data as $k => $detail) {
    $field_key = _get_field_keys('field_' . $k);
    $field_key = $field_key[0];

    $node -> {'field_' . $k}[$node -> language][0][$field_key] = $detail;
    $form_state['values']['field_' . $k] = $detail;
}

drupal_form_submit("{$node->type}_node_form", $form_state, $node);

The form state before I call drupal_form_submit looks like this:
Array
(
    [values] => Array
        (
            [title] => some title
            [name] => admin
            [op] => Save
            [field_person] => 88
            [field_lead_type] => 1
            [field_lead_details] => some stuff
    )

)
What is the fix? I'd rather not mess with core modules. Is there something I can do to my own code to resolve the problem?
Comment: show us where you call drupal_form_submit(). Show us the $form_state your submitting.
Comment: @tenken I don't think that makes much difference as the issue will occur from anywhere drupal_form_submit is called so long as the form being submitted to has a file field in it. I updated the question anyway though.
Answer: ok, why are you not submitting a File (or FID) along with your form_state? I don't understand your problem, because I do this all the time (even with files).
Drupals file widgets usually use like Ajax to upload a file in the background and the form takes a FID in $form_state to process your forms if it has files attached.
When I asked you what the $form_state was I meant:

what are you sending to drupal.
what does drupal typically send as the $form_state when that form is sent through the user interface, because you're just trying to do that programmatically.

I dont think you know the answer to (2) above, because you cant get this to work right. You showed me what you're sending for (1). Here is a tutorial on using Firefox's Firebug plugin to view the submitted POST form state values for a drupal form. You want to drupal_form_submit form state to have the exact same parameters passed to it. In firebug you simply press Persist in the Net tab and you can capture URL requests.
So I'm saying goto the form in the website and submit it using your browser and Firebug to see what it expects to be passed.
You may ask how you get a FID for a file, you simply upload it using php before submitting the form and pass along its $file->fid. See this community documentation comment here how to do that.
You're just posting a simple HTTP Form, I really doubt Drupal is doing anything wrong.
Comment: Your advice seems incorrect. The reason I am not submitting an fid (in this particular case) is because it is an optional field.

Following your advice, I added in the extra values that go with the attachment field type, but the warning persisted.

Please look in the file I mentioned and you will see that the error will occur regardless of whether I add in the extra stuff in field_state. The 'real' drupal form goes through the exact same process as my programmed form _except_ for when it reaches the aforementioned check. My form fails that check because it has been made programatically.
Comment: I should not that it _does_ work, the node is created and everything. I just get this notice, which I think is annoying and obviously indicates either, a mistake on my part, or an oversight by who ever wrote file_field_widget_form in file.field.inc


Unable to run elasticsearch with weblogic server

Question: I am using elasticsearch 7.2.0 with weblogic 184.108.40.206 server. Facing classloading issues.
I have setup weblogic server 126.96.36.199 and elastic search 7.2.0. Facing runtime error when searching.
All the elasticsearch jars are included in the domain/lib directory.
Comment: Can you post errors and stack trace showing the issue please.
Answer: I found the issue.. there was a conflict with old and new versions of lucene-core jars used by elasticsearch. Both were present in the library. After removing the old version, elasticsearch works fine


Conditionally choosing view templates based on data from HTML5 localStorage

Question: Run
myApp.run(function(){
    if(!(window.localStorage.storage1)){
        window.localStorage.setItem('storage1', null);
});

Home View

On transition to some state I update the storage1 to {"someKey" : "someValue"}
Now in the home view, when storage1 is set to null (actually the string "null") then part1 of the view should be shown and when storage1's value is updated to a dictionary data type then view part2 should be shown. But it does not. I virtually tried everything. I compared typeof, cast it explicitly, changed the default value given to the storage1 but nothing seems to work.
Answer: Angular expressions are evaluated in the context of the scope. See https://docs.angularjs.org/guide/expression
In the controller for the Home View you will need to set something in the scope based off of what is in localStorage, and then use that in your ng-if expression.
Comment: Oh god! I don't know why I was trying to type check an object which angular expressions did not have access to. May be I was frustrated and did not think what I was doing. Actually when I woke up today morning I came to know what I was doing. Came now to correct it. May be I should have taken a walk before asking it here.


What the meaning of( f) and % in the schedule

Question:
Hello
Could u tell me please what f and % refer to ?
Thank you
Answer: f is the frequency, i.e. the number of students in that category.
% is the percentage of students in that category.
For example, dividing $3$, $51$, and $6$ by their sum gives you $0.05$, $0.85$, and $0.1$, respectively.


Differential equations of a plate with spherical mass load?

Question: I would like to know the equations describing a plate surface being curved and stressed by a mass (you know, like a ball on a stretched sheet). I'm just curious :). I feel a bit confused about tensor and similar, so please explain everything (or just draw out the equations with a bit of comment, if you don't feel like that... )
P.S. The properties of the plate's material depend on some value, right? And, what's Young modulus? Does it appear in the equations?
Comment: That is a lot of questions with very little working shown on your side! For example one can quickly search Young's modulus, as it is a rather big experiment done on the limits of material stretching. So do a bit more reading and then come back and we can iterate the model. that is my opinion only though :)!
Comment: Ok! Keep in touch, I'll come back as I know more! :) Thanks very much!
Answer: I think it can be described by the biharmonic PDE with the thin plate spline as its fundamental solution in $\mathbb{R}^3$. Could you confirm this against (advanced) textbooks on elasticity and mathematical methods in physics and post your account of it, please?
Comment: I found this [link] (http://www.geometrictools.com/Documentation/ThinPlateSplines.pdf), but I don't if it can be useful. I'm sorry, my textbook doesn't tell about this...
Comment: Ok, I had some lessons online and now I can confirm that you were right! Thank you very much!
Comment: Great, @user12373. Could you share the link, please, I'd love to take that online lesson myself?
Comment: That's here: [link](www.pdetolearn.com/user/lessons/15_Thin%plate.htm), but I think is down, now... If ever they'll make it online again, you'll find a section with the most important PDEs in Phisics and Engeneering, and a customized study plan to choose from, free.


How to hide menu item from high level roles but show for low level

Question: I have 3 roles on site:

anonymous user
authenticated user
admin

I created a new page:
function learning_menu()
{
    $items = array();

    $items['learning'] = array(
        'page callback'    => 'learning_output',
        'access callback' => 'learning_access',
        'type' => MENU_CALLBACK,
        );

    return $items;
}

I manually created a menu item for this page in the top menu. This item should be displayed only for authenticated users, but not admins. Unfortunately, admin as also an authenticated user. So I had to use a trick to disallow access to this page to admins using this access callback:
function learning_access()
{
    global $user;

    $n = count($user->roles);
    if ($n === 1)
    {
        $data = array_values($user->roles);
        if ($data[0] === 'authenticated user')
        {
            return true;
        }
    }

    return false;
}

It works but when I uploaded this module to server, I was unable to manually add a menu item for this page. Because admin doesn't have access to it.
How can I allow an admin to access this page? In the same time the menu item shouldn't be shown for him.
Comment: hmm yaa.. but this some thing like deadlock situation. Hide that Menu using https://www.drupal.org/project/menu_item_visibility
Comment: Then you can do another thing, remove 'access callback', but in the page callback function write your condition and make drupal_access_denied for admin user
Comment: @Nagarjuna In this case the menu item will be shown.
Comment: @Nagarjuna This module won't help. Because even if I just tick authenticated user, it will still show for the admin. Because admin is an authenticated user.
Comment: @Nagarjuna I think, the only way is to attach a hook to the function that generates menu and check this item there.
Comment: why cant u directly hide 'admin' user using that module? Jus curious..
Comment: @Nagarjuna I don't see, where it allows to hide the item for a role. It just allows to show.
Comment: Then Can you give a shot on this module https://www.drupal.org/project/roles_for_menu or https://www.drupal.org/project/menu_per_role
Comment: @Nagarjuna Roles for menu module worked. Please, post it as an answer so I could close the question.
Answer: As per the discussion above,
Remove 'access callback' => 'learning_access', add drupal_access_denied() in page call back
function learning_menu() {
  $items = array();

  $items['learning'] = array(
    'page callback' => 'learning_output',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function learning_output() {
  global $user;

  $n = count($user->roles);
  if ($n === 1) {
    $data = array_values($user->roles);
    if ($data[0] === 'authenticated user') {
      drupal_access_denied();
    } else {
      //YOUR code Here
    }
  }
}

And Use Roles for Menu module to hide the learning menu.

This module allows you to restrict access to menu items based on user
  roles. It is used when you don't want to copy your whole menu just
  because for one specific role you want to hide one menu item.
The module will add a fieldset with options for restricting access or
  gaining access to menu link for a specific role/roles
Comment: No need to add access_denied into the page callback. I added `'access arguments' => array('access content'),` into the menu item.
Comment: Cool Cheers. :)


Geographic regression

Question: I'm working on a project to estimate real estate and started with some classique techniques, such as linear regression etc. The obtained results are already going in the good direction, but to get some more precise results, I've started to lookup some more advanced models.
First I've looked into a spatial autoregressive model, but these models are a bit hard to use if we want to predict new values, or am I wrong?
The next one is the kriging technique. In general, these models use only two coordinates and one prediction value (like temperature or height). In my project I'm using way more variables to predict the outcome.
My question is which technique/model I would best look into to obtain some better results.
Answer: I prefer autoregressive models to kriging, because I feel there is more of an economic rationale behind their use. Others are free to disagree!
Autoregressive models may be difficult to use/understand/apply, but if there is spatial correlation in your data (and there almost certainly is in home price data), linear regression models are biased and hypothesis tests on them are invalid. In fact, you will probably get less precise estimates, but it is better to be accurate and imprecise than highly precise but off the mark.
I highly recommend the spdep package for R by Roger Bivand. It's relatively easy and quick to use, and it intersects well with the nomenclature used by LeSage and Pace in their excellent book.

Geographic regression


Rules - Send mail to all addresses in email field of specific content type

Question: I have a content type (school) with an unlimited email field (field_email).
Now on creation of another node (page), I would like to send to all emails stored in the "field_email" of all school nodes an email.
I started by created a rule with the "rules" module but i cannot figure out how to pull the data from a separated node (school).
Could someone point me in the right direction?
Comment: Want to try programmatically?
Answer: You can use Views Rules module. For achieve this goal first you have to create a view to get all mail values of content type (school) and than its result provide to rules using this module. For more information go through the documentation of Views Rules module.


Reference on Time Series Parameter Estimation

Question: I'm trying to learn techniques for estimating the parameters of standard time series (AR, ARMA, GARCH, etc.), and can't seem to find a solid resource online.  Specifically, I'd like one that addresses the estimate of standard errors of such estimates as well.  An example of what I'd like to learn is from my question here.  I'd like some references to texts/online resources that explain these issues well.
Comment: You really need to tell us more or less what do you know, for instance, do you expect an applied or mathy book?
Answer: You didn't so far tell us more or less what level of book do you expect. For a book with emphasis on the theoretical underpinings of time series analysis, I would start with maybe Hamilton, or a good econometrics book, maybe  Hayashi.  If you want something more applied, so tell us.


T-test of two groups of a 15 groups experiment

Question: I'm a biologist, so for most of you my question is gonna be the dumbest one. I made an experiment with triplicates and performed anova and tukey's test, but the later was not significant. What I would like to know is if I perform a T-test between to groups of samples (different treatments) I will be forcing a different result. Why?
Thank you in advance!
Comment: It will be hard to give a good answer without having more details on the nature of your measurements and which hypotheses that you were trying to test with the experiments. Some types of data are better handled with some type of transformation before running anova, etc. Also, if you had a specific hypothesis about differences between 2 particular groups from the beginning before you ran the experiments on all the groups, that's different from testing for differences between groups that you discovered in your analysis of the results of the experiments.
Comment: Sure! I am evaluating if there is any difference in a product yield of fermentation according to enzyme doses. I have 15 treatments with triplicates for each one. Firstly, I tried an ANOVA followed by Tukey's test, but it was not significant. After, I thought to use T-test between 2 treatments that I've considered important, but it sounds wrong to me.
Comment: Are these 15 different enzymes, 15 different "doses" of the same enzyme, or some combination of different enzymes and doses? What controls are there?
Comment: These are a combination of different doses and enzymes (14 treatments + 1 gold standard enzyme + dose as "control")
Comment: Was the ANOVA itself significant (e.g., F-test)?
Comment: The ANOVA was significant. I used R and agricolae package for HSD Tukey.
Answer: With a significant F-test in ANOVA, you have reason to believe that there are some significant differences among the treatments. So you can proceed with testing of between-treatment differences.
Your choice of the Tukey test for between-teatment differences might have been OK if you had no idea which comparisons you cared about, but that's not the case here. You have a "gold standard" treatment as a control, and what you presumably care the most about is whether any of the other treatments are better than that gold standard and thus are worth pursuing in detail as a replacement. That is comparing multiple treatments against a single control, for which the classic test is Dunnett's.
The advantage of Dunnett's test could be dramatic in this situation with 15 treatments in total. In correcting for the multiple comparisons being made, Tukey's test has to take into account all the possible ways you could do pairwise comparisons among 15 treatments: 105 comparisons. To avoid Type-I error for this whole family of 105 tests, Tukey's test thus requires a very large difference to claim "significance." In Dunnett's test you are only making 14 comparisons against the single control, so smaller differences can be deemed "significant" than in the Tukey test with the same protection against Type-I error. My guess is that Dunnett's test might provide defensible "significant" findings with your data.
It also matters how you are intending to use the results of these experiments. If you are using these results to guide follow-up studies better to document and explore the advantages of some new enzyme or dose, then you could just consider this work a pilot study, not worry excessively about statistical significance at this point, and depend on later, more detailed experiments to document both the practical and statistical significance of the new treatment(s) of interest. If you are instead intending to publish these results on their own, then ANOVA followed by appropriate multiple testing is required. One might, however, then wonder about why you didn't further pursue the interesting leads suggested by these initial experiments.
For your specific question about separating out specific t-tests, if you really, truly and honestly had one particular combination of new enzyme and dose that you wanted to compare against the "gold standard" before you did the experiments, or a small number of such pre-defined comparisons among treatments, then you might be OK in doing  t-tests for those particular comparisons (with a Bonferroni or other correction for multiple testing with more than one comparison). But if the results of these experiments in any way informed your choice of which comparisons to make, then you need to use an appropriate multiple-comparison test.
Going forward, consider this as an example of how a larger experimental design is not always better when you have to take multiple comparisons into account.
Comment: I did not use Dunnet because it's not a true control, I mean the gold standard uses different types of enzymes than my treatments. In addition, the "control" passes by a pretreatment that the others conditions don't. Could I still use Dunnet?
Comment: @user2501348  It doesn't matter whether the "gold standard" is a "true control" or not. What matters is the structure of the comparisons that are important to you. If you want to see whether any of the new treatments differs from the "gold standard," then Dunnett's test with the "gold standard" as reference makes sense. If you want to examine all 2-way comparisons of the 15 treatments, then Tukey's or some similar test is required. That decision has to be based on your (and your reviewers') understanding of the underlying subject matter.


How should one work with missing digital staff on entry level keyboard?

Question: I am currently trying to find a good entry level keyboard for getting back to learning to play after 20 years. I had a few years of grade school classes playing a brass instrument and some self taught time with a keyboard when I was an adolescent.
A lot of the entry level keyboards have a 'notation' section (as they call it) on the digital display which I worry might actually be a bit of a crutch to learning to mentally transpose sheet music to finger placement.  I was pretty reliant on this feature when I was teaching myself 20 years ago, so I am naturally looking for a keyboard which has it now too.
However, the keyboard I am wanting to get (for other reasons) does not have this notation section which has me reflecting if I really should even allow myself to have something that may actually be a crutch to learning.  Though with so many entry level keyboards having it, I am also wondering if it's a good thing to have available and if relying on it is just fine.
In a formal education setting, would an instructor generally shun reliance on the digital notation display?  Or is it a good learning tool?  Bit of both?
Image below shows an example of what this notation looks like on the display (left side):
Comment: Please do not...  this would apply to any entry level keyboard which does not have this type of digital display.   The primarily question is about whether such a display is somewhat harmful to learning to play.  The Yamaha motivations are clearly not a focus of the broader question being asked.  I have not found any practice related questions that discuss the benefit / harm of a digital staff.
Comment: Can the displays handle sharps vs flats correctly? I think they can't do that really. I've seen some kids rely on speech recognition on smartphones. Terrible. I mean, very nifty, because you don't have to know how to write. It was always too complicated anyway - good riddance! ;)
Comment: @piiperiReinstateMonica Hmm I suspect it would not handle them correctly, which is to say I won't know if the music specified C♯ or D♭.   That is a good point.
Comment: @Wisteso I recommend you rewrite the question to focus on that aspect. Your core concern is perfectly stated in your comment, but does not come across clearly in the question itself.
Comment: @Wisteso I've retracted my close vote.
Comment: Sadly, there are no shortcuts. On the upside, since there are no shortcuts, it's the same path for everyone. Learning to read the music and play the right keys the hard way is the best way to learn.
Comment: I'm voting to close this question because as written, it's asking 1) for speculation on Yamaha's motivations, which would be better directed to Yamaha, and 2) it asks for practice strategies, which are addressed in many other questions and answers here.
Comment: @Aaron I've revised the question per your comments.  Removed references to specific keyboard and focused on the narrower scoped question.
Answer: You are not doing anything fundamentally wrong but relying on something like this for more than a short period of time can be detrimental to the development of your playing and reading skills. First, I would assume a display like that pays no mind to keys so accidentals may not be interpreted correctly. Secondly, you are turning a 2 step process of looking at a note on a chart and playing it to a 3 step process, adding the step of looking at the display to see if the note you  played matches the note on the paper. In the long run you will be better off working on making the connection directly from paper to fingers and focusing on the sound to tell you if something is right or wrong.
Remember, music has been around for thousands of years but none of this technology existed 50 or 60 years ago. Musicians managed to get by before the advent of electronics. Let's use technology to our benefit but not as a crutch. Let's make sure we are the ones doing the actual learning and playing.
Comment: Thank you for the response.  I did edit the original question per Aaron's comments, but your response precisely addresses my broader question.
Comment: @Wisteso My pleasure, I think my answer still fits your edited question. Welcome to MPT and ask away about anything relevant to this site and what you're trying to learn and accomplish, there are a lot of very knowledgeable people here to help.
Answer: There's nothing WRONG about consulting that sort of display.   But - like an earlier generation's sticky labels 'naming' the notes of a piano keyboard - it's a stage you need to get past pretty quickly.   The music you'll want to play is distributed as notation.  Deal with it!
Comment: I suspected this might be the case.  Downside of being self taught is not having an instructor to push away from developing reliance on crutches.
Answer: It's not particularly difficult to learn to read music. One starts with somewhat simple stuff and then adds stuff as needed. Ordinary music notation is quite flexible and quick to read with a bit of practice. Teoria has lots of good stuff as do other sites. https://www.teoria.com/
Reading music allows one access to a vast amount of stuff. Also one can share music with people across language borders (and apparently across time as we still perform music from the 1300s and before.)
The most important thing to remember is that (with the usual staff notation) pitch is represented vertically and time goes horizontally.


Posição de um cavalo no jogo de xadrez

Question: Estou aprendendo C.
Meu professor da faculdade pediu para fazer um programa que leia a posição de um cavalo no jogo de xadrez e imprima TODAS as possibilidades de movimento.
Eu estou quebrando a cabeça pra saber como eu vou saber a letra e o número que o usuário pediu?
Comment: Use um array para mapear o tabuleiro, para a posição que o usuário pediu use uma variável simples já que o intuito é você mapear as possibilidades do movimento de uma peça. Ha e boa sorte na matéria de processamento paralelo se vocês tiverem no curso (;
Comment: Obrigado pela resposta.
Comment: https://pt.meta.stackoverflow.com/questions/8388/
Answer: // criar o tabuleiro
char tabuleiro[8][8];

// Pede ao usuário informar a posição da peça que deseja mover
printf("Digite a linha onde esta sua peca: ");
scanf("%d", &linAtual);
printf("Digite a coluna onde esta sua peca: ");
scanf("%d", &colAtual);

// Pede ao usuário informar para onde deseja que a peça vá
printf("Digite a linha desejada: ");
scanf("%d", &linDes);
printf("Digite a colun desejada: ");
scanf("%d", &colDes);

// Você pode usar essas informações do usuário pra localizar e mover a peça
char peca = tabuleiro [colAtual][linAtual];
tabuleiro [colAtual][linAtual] = " ";
tabuleiro [colDes][linDes]= peca;

Então cara vc vai ter que pensar em como diferenciar as peças(dá pra ter uma ideia pelo código acima) e também vai ter que definir as regras de movimentação (muito if e  else) boa sorte.
Answer: Eu fiz um algorítmo relacionado à torre do xadrez. A saída mostra o mapa de movimentos que ela pode realizar.
#include <stdio.h>

int main(){

    int linha = 0, coluna = 0;
    int i, j;

    printf("Movimentos de uma Torre no xadrez!\n");

    printf("Digite a linha em que a Torre se encontra: ");
    scanf("%d", &linha);

    printf("Digite a coluna em que a Torre se encontra: ");
    scanf("%d", &coluna);

    printf("    1 2 3 4 5 6 7 8\n   -----------------");

    for (i = 1; i <= 8; i++){

        if (i != linha){

            if (coluna == 1){

                printf("\n%d | x - - - - - - -", i);
            }

            if (coluna == 2){

                printf("\n%d | - x - - - - - -", i);
            }
            if (coluna == 3){

                printf("\n%d | - - x - - - - -", i);
            }

            if (coluna == 4){

                printf("\n%d | - - - x - - - -", i);
            }

            if (coluna == 5){

                printf("\n%d | - - - - x - - -", i);
            }

            if (coluna == 6){

                printf("\n%d | - - - - - x - -", i);
            }
            if (coluna == 7){

                printf("\n%d | - - - - - - x -", i);
            }

            if (coluna == 8){

                printf("\n%d | - - - - - - - x", i);
            }

        }

        else if (i == linha){

        printf("\n%d | x x x x x x x x", i);

        }

    }

    return 0;

}

Comment: Se o autor da pergunta quisesse saber quais todas as posições da torre ele teria escrito *Gostaria de saber como obter todas as possibilidade de movimento de uma torre partir de dada posição* mas ele pediu a posição do cavalo então entregue a ele ao autor da pergunta o que ele pediu ou não entregue nada, mas atenha ao que foi perguntado.

Posição de um cavalo no jogo de xadrez


$\nu$ is a measure if $\nu(A)=\int_A f\ d\mu$ and $f:X\to [0,\infty]$ is $\mu$-measurable?

Question: I found a result (without proof) given as an exercise in one of my measure theory texts.It says:
Proposition
Let $(X,\mathcal S,\mu)$ be a measure space and $f:X\to [0,\infty]$ be a measurable function,define $\nu(A)=\int_A f\ d\mu$,then $\nu$ is a measure.
First of all,I want some hints to prove this result.Next I want to know why this theorem is of so much importance,what are the applications of this result and how can I use this result in problems to construct certain measures.
Comment: Just show that it satisfies the properties required of a measure. It is useful for constructing other measures such as probability measure with density.
Answer: Clearly, we have $\nu(\varnothing) = 0,$ and $\nu(A) \ge 0$ for all $A \in \mathcal S$. Now consider a countable collection $(A_n)_n$ of pairwise disjoint sets in $\mathcal S$. We have
$$\nu\left(\bigcup_{n}A_n\right) = \int_{\bigcup_{n}A_n} fd\mu = \int_{A_n} \sum_n f \boldsymbol 1_{A_n} d\mu,$$
where $\boldsymbol 1_{A_n}$ is the characteristic function of the set $A_n$. Now to finish the argument, try to show that you can switch $\int$ and $\sum$ and then conclude.
This kind of measure is widely used in probability theory and is the basis of the Radon-Nykodym theorem:

The Radon–Nikodym theorem involves a measurable space $(X,\mathcal S )$ on which two $\sigma$-finite measures are defined, $\mu $  and $\nu .$ It states that, if $\nu \ll \mu$ (that is, $\mu(A) = 0$ implies $\nu(A) = 0$), then there exists a $\mathcal S$-measurable function $ f:X\to [0,\infty )$, such that for any measurable set $A\subseteq X$,
$$\nu (A)=\int _{A}f\,d\mu.$$

Consider for example $(\Omega, \mathcal S, \mathbb P)$ a probability space and $X: \Omega \to \mathbb R$ a random variable (i.e. a measurable function). Now consider the pushforward measure $\mathbb P_X$ (called the distribution of the random variable), which is a probability measure on $(\mathbb R, \mathcal M)$ (where $\mathcal M$ is the set of Lebesgue-measurable subset of $\mathbb R$), defined by
$$\mathbb P_X(A) = \mathbb P(\{\omega \in \Omega: X(\omega) \in A\}), \quad \forall A \in \mathcal M.$$
Note that we clearly have $\mathbb P_X \ll \mathbb \lambda$, the Lebesgue-measure on $\mathbb R$, because $X$ is a measurable function. Therefore, by Radon-Nykodym, there exists $f: \mathbb R \to \mathbb [0,\infty)$ such that
$$\mathbb P_X(A) = \int_A f d\lambda.$$
For example, for the normal distribution we have
$$f(x) = \frac{1}{\sqrt{2\pi \sigma^2}} e^{-\frac{(x - m)^2}{2\sigma}}.$$
This allows us to compute probabilities very easily.
Comment: Your answer is much more detailed. (+1)
Comment: @Falcon How come we "clearly have $\mathbb{P}_X \ll \lambda$"? I don't think measurability of $X$ is sufficient for this; we would need some form of [Luzin N property](https://en.wikipedia.org/wiki/Luzin_N_property) for this. Or am I missing something?
Answer: For countable additivity of disjoint measurable sets $\{E_{i}\}_{i=1}^{\infty}$, let $$g_{n}=\sum_{i=1}^{n}f\cdot\mathbf{1}_{E_{i}}$$.
Then $g_{n}\uparrow\uparrow f\cdot\mathbf{1}_{\bigcup_{i=1}^{\infty}E_{i}}$ and are non-negative measurable functions
So $$\nu(\bigcup_{i=1}^{\infty}E_{i})=\int_{\bigcup_{i=1}^{\infty}E_{i}}f\,d\mu=\int_{X}f\cdot \mathbf{1}_{\bigcup_{i=1}^{\infty}E_{i}}\,d\mu$$
$$\int_{X}f\cdot \mathbf{1}_{\bigcup_{i=1}^{\infty}E_{i}}\,d\mu=\int_{X}\lim_{n\to\infty}g_{n}\,d\mu$$
(By Monotone Convergence theorem)
$$=\lim_{n\to\infty}\int_{X}g_{n}\,d\mu=\lim_{n\to\infty}\sum_{i=1}^{n}\int_{E_{i}}f\,d\mu=\sum_{i=1}^{\infty}\nu(E_{i})$$.
To provide a motivation for this theorem, recall the definition of a probability density function. That is consider $(\Omega,\mathcal{F},\mathbb{P})$
As random variables are measurable functions , you have $X^{-1}(A)\in\mathcal{F}\,\forall\,A\in\mathcal{S} $
Then for a random variable $X$ with pdf $f$, you have $\mathbb{P}(\omega\in\Omega\,,X(\omega)\in A)=\int_{A}f\,d\lambda$.
That is you integrate over set to get the probability measure of "event" that the random variable takes values in that set. For more info look at the Radon Nikodym Theorem (Royden page 382) .
Comment: If $X$ is a random variable and $f$ a pdf, $f$ is defined on $\mathbb R$ not $\Omega$, so it should be integrate with respect to the Lebesgue measure, not $\mathbb P$.
Comment: oops, lol . I'll edit it