How can it be proved that the limit definition and series definition of $e$ are equivalent, how do they model continuous growth?

Question: The limit definition of $e$ gives the best intuition toward how $e$ can model continuous growth.
$$\lim\limits_{n \to \infty} \left( 1 + \frac1n\right)^n$$
Let n represent n moments of growth that scale the initial value by $ 1 + \frac1n $.
The key to me seems to be that the $\Delta x $ approaches 1 but does not reach it. This allows for the best approximation $\Delta x = 1 $ at each moment. In other words, at each moment of growth the value x experiences $\Delta x = 1 + \frac1n $, or as $n \to \infty$... $$\lim\limits_{n \to \infty} 1 + \frac1n = 1 $$
Growth with n = 2 moments:
$1 \times 1\frac12 \times 1\frac12 $ = 2.25
insight: If 2 moments of growth occur to x where $\Delta x = 1\frac12$, this amounts to discrete growth by $\Delta x = 1\frac12$ twice.
Growth with three moments:
$1\times 1\frac13 \times 1\frac13 \times 1\frac13 $ = 2.35
insight: If 3 moments of growth occur to x in where $\Delta x = 1\frac13$, this amounts to discrete growth by $\Delta x = 1\frac13$ three times.
Growth at seven moments:
$1\times \frac17 \times 1\frac17  \times 1\frac17 \times 1\frac17 \times 1\frac17 \times 1\frac17 \times 1\frac17 $ = 2.55
insight: If 7 moments of growth occur to x in this period where $\Delta x = 1\frac17$, this amounts to discrete growth by $\Delta x = 1\frac17$ seven times.
$\lim\limits_{n \to \infty} \left( 1 + \frac1n\right)^n $ is a definition of $e$ as it models n moments of growth occurring where at each instant the initial value is scaled by a factor $\lim\limits_{n \to \infty} 1 + \frac1n = 1 $.
To me this seems intuitive to a small extent. If we want to grow continuously we scale by an infinitely small increase an infinite number of times and this converges onto the number $e$. Why it must converge is mysterious to me, and besides seeing a proof I can't intuit to something that is satisfying.
Now there is also the Taylor series representation of $e$
$$ \sum_{n=0}^\infty \frac1{n!} = 1 + 1 + \frac12 + \frac1{3\times2\times1} + \frac1{4\times3\times2\times1} ... $$
Speaking loosely it seems to get $e$ you can sum a whole and itself, with $ \frac12$ that whole, and $ \frac13$ of $ \frac12$ of that whole and so on...and I have no intuition for this.
Again, the Taylor Series converges to $e$ but I don't see the same intuition for how this can model continuous growth. Furthermore, with my limited math skills I wouldn't know how to prove:
$$\lim\limits_{n \to \infty} \left( 1 + \frac1n\right)^n = \sum_{n=0}^\infty \frac1{n!}$$
My 3 questions I am seeking to answer are
1. By what application or intuition can it be seen that $ \sum_{n=0}^\infty \frac1{n!} $ models continuous growth?
2. What are some proofs that:
$$\lim\limits_{n \to \infty} \left( 1 + \frac1n\right)^n = \sum_{n=0}^\infty \frac1{n!}$$
3. Is euler's number inextricably linked to time as $\pi$ is to the circle?
When discussing $e$ it seems necessary to talk of periods of continuous growth $ p = kt $ being represented by $ e = e^p $ where $ p = 1 $ in the fundamental case. I do not know how to think of $e$ without seeing it as one period of continuous growth proven to be $e$ by the convergence of the intuitive definition I gave. I cannot see this same inextricable link to a period in the Taylor Series nor in other definitions of $e$.
Thanks for any comments, I have been trying to wrap my head around $e$ at the most fundamental level for a long time so that I can more deeply understand differential equations.
How was it arrived upon that e best modeled continuous growth? Was it an experimental observation or was it a proof that convinced mathematicians and scientists that $e$ embodies the idea of continuous growth i.e. growth at all instances?
I have so many questions about Taylor Series and $e^{i\theta}$ I'm trying to answer as well..
Best Wishes,
Comment: If you introduce $\exp(x)=\sum_{n=0}^\infty \frac{x^n}{n!}$, then it is not that hard to determine that $\frac{d}{dx} \exp(x)=\exp(x)$. Thus, the rate of change of how much stuff you have is exactly equal to how much stuff you have, which is exactly like compounding interest. The thing that might not be so obvious is that $\exp(x)$ is actually $e^x$, and in particular $\exp(1)=e$. Does that help?
Comment: As for #2, the proof is not so easy, but the main idea is to use the binomial theorem on $(1+1/n)^n$. You find that it is $\sum_{k=0}^n \frac{{n \choose k}}{n^k}$. This boils down to $\sum_{k=0}^n \frac{n(n-1)\dots(n-k+1)}{k! n^k}$. The discrepancy between the two is because $\frac{n(n-1)\dots(n-k+1)}{n^k}$ is not $1$. But it's pretty close, except when $k$ gets pretty close to $n$. It is close enough for the two expressions to agree as $n \to \infty$.
Comment: see http://math.stackexchange.com/questions/365029/intuitive-proofs-that-lim-limits-n-to-infty-left1-frac-xn-rightn-ex/1824964#1824964 @ian for an unified proof of $\exp(x) = \lim_n (1+x/n)^n =  \sum_{k=0}^\infty \frac{x^k }{ k!} $, and the fact that $\exp(x) = e^x$ reduces to proving that $\ln(x) \overset{def}= \int_1^x \frac{dt}{t}$ is a logarithm (i.e. $\ln(xy) = \ln(x)+\ln(y)$) in some base $e$ such that $\ln(e) \overset{def}= 1$. for $e^{ix} \overset{def}= \sum_{k=0}^\infty \frac{(ix)^k }{ k!} = \cos(x) + i \sin(x)$ I recommend http://math.stackexchange.com/a/1839417/276986
Answer: The following deals with your second question.

Without adding any additional details about $e$ and $\log$ here is the proof of the identity $$\lim_{n \to \infty}\left(1 + \frac{1}{n}\right)^{n} = \lim_{n \to \infty}\left(1 + \frac{1}{1!} + \frac{1}{2!} + \cdots + \frac{1}{n!}\right)$$ I assume that you are aware of the fact that both the limits above exist (it is easy to establish this by noting that both the sequences involved here are increasing and bounded above).
Let $$a_{n} = \left(1 + \frac{1}{n}\right)^{n}, b_{n} = 1 + \frac{1}{1!} + \frac{1}{2!} + \cdots + \frac{1}{n!}$$ and also consider another related sequence $$c_{n} = \left(1 - \frac{1}{n}\right)^{-n}$$ Clearly we have
\begin{align}
\lim_{n \to \infty}c_{n} &= \lim_{n \to \infty}\left(1 - \frac{1}{n}\right)^{-n}\notag\\
&= \lim_{n \to \infty}\left(\frac{n}{n - 1}\right)^{n}\notag\\
&= \lim_{n \to \infty}\left(1 + \frac{1}{n - 1}\right)^{n - 1}\cdot\frac{n}{n - 1}\notag\\
&= \lim_{n \to \infty}\left(1 + \frac{1}{n - 1}\right)^{n - 1}\notag\\
&= \lim_{n \to \infty}a_{n} \text{ (replacing }n - 1\text{ by } n)\notag
\end{align}
Using binomial theorem we can see that
\begin{align}
a_{n} &= \left(1 + \frac{1}{n}\right)^{n}\notag\\
&= 1 + 1 + \frac{n(n - 1)}{2!}\cdot\frac{1}{n^{2}} + \cdots\notag\\
&= 1 + 1 + \dfrac{1 - \dfrac{1}{n}}{2!} + \dfrac{\left(1 - \dfrac{1}{n}\right)\left(1 - \dfrac{2}{n}\right)}{3!} + \cdots\notag\\
&\leq 1 + 1 + \frac{1}{2!} + \frac{1}{3!} + \cdots + \frac{1}{n!}\notag\\
&= b_{n}\notag
\end{align}
Similarly if $n > 1$ then we can use the binomial theorem for general index to get
\begin{align}
c_{n} &= \left(1 - \frac{1}{n}\right)^{-n}\notag\\
&= 1 + 1 + \frac{n(n + 1)}{2!}\cdot\frac{1}{n^{2}} + \cdots\notag\\
&= 1 + 1 + \dfrac{1 + \dfrac{1}{n}}{2!} + \dfrac{\left(1 + \dfrac{1}{n}\right)\left(1 + \dfrac{2}{n}\right)}{3!} + \cdots\notag\\
&\geq 1 + 1 + \frac{1}{2!} + \frac{1}{3!} + \cdots + \frac{1}{n!}\notag\\
&= b_{n}\notag
\end{align}
It thus follows that if $n > 1$ then we have $$a_{n} \leq b_{n} \leq c_{n}$$ Both sequences $a_{n}, c_{n}$ tend to same limit hence by applying Squeeze theorem theorem it follows that $b_{n}$ also tends to the same limit and our job is done. The same technique can be used to prove the more general result that $$\lim_{n \to \infty}\left(1 + \frac{x}{n}\right)^{n} = \lim_{n \to \infty}\sum_{i = 0}^{n}\frac{x^{i}}{i!}$$ for all real numbers $x$.
Comment: How accessible is this "binomial theorem for general index" to someone at the level of the OP? The binomial theorem with an integer exponent is fine.
Comment: @Ian:

The general binomial theorem which I have used here is the one where the index is a negative integer and it is at the same level as the series $(1 − x)^{−1} = 1 + x + x^{2} + \cdots$. It does not require anything more than multiplication of infinite series. Multiplication of infinite series is in fact sufficient to prove the binomial theorem for rational index also. No differential calculus is needed here
Answer: There are some assumptions you have to make in what respect $e$ is introduced. My approach is that it is known that the derivative of $y=\ln x$ is equal to $y=1/x$.
Now using the limit definition of the derivative, we have :
$$\lim\limits_{x \to 0} \frac{\ln(x+1)-\ln1}{x}=1$$
The $1$ on the right hand side is the derivative of $\ln x$ in which we substituted $1$.
Since $\ln1=0$, we can do some algebra: Bring the $x$ in the denominator upfront as $\frac{1}{x}$ which then can be put as an exponent by laws of logs:
$$\lim\limits_{x \to 0} \ln(x+1)^\frac{1}{x}=1$$
Raising both sides to power $e$ we get:
$$\lim\limits_{x \to 0} (x+1)^\frac{1}{x}=e$$
When you perform a substitution $x=1/n$, you get your limit "connected" to $e$. Hope this input addresses some of your questions. (essentially your introductory part)
Answer: You're asking multiple questions here, and you've asked them in a certain order. But I'm gonna take a liberty and answer them in a more intuitive order.
In your third question, you asked if Euler's number is inextricably linked to time. It is, in fact, not. Euler's number is inherently a mathematical constant, not a physical one. While it may be useful regarding time dependent functions, that doesn't necessarily mean that it is fundamentally tied to time dependent functions as $\pi$ is to circles.
You see, fundamentally the number $e$ is about $2$ things. Exponential growth, and rate of change. The first thing to consider is the derivative of any exponential. Let's begin by differentiating a random exponential $a^x$.
$$\frac{d(a^x)}{dx} = \lim_{h \to 0} \frac{a^{x+h} - a^x}{h}$$
As $a^{x+h} = a^x a^h$,
$$\frac{d(a^x)}{dx} = \lim_{h \to 0} \frac{a^x a^h - a^x}{h}$$
Factoring out $a^x$ from the numerator, and outside the limit gives us
$$\frac{d(a^x)}{dx} = a^x \lim_{h \to 0} \frac{a^h - 1}{h}$$
From this, we can intuitively see that the derivative of any exponential is going to be directly proportionate to the exponential itself, as the derivative of $a^x$ is equal to $a^x$ times some constant. The question then arises: does there exist a base for which this proportionality constant is equal to $1$? Is there a function such that the function is its own derivative?
The short answer to this is yes. And we have with us the means to find it. The first thing to do is to take $\lim_{h \to 0} \frac{a^h - 1}{h}$ to be our proportionality constant. But we also know that our proportionality constant must be $1$. Hence, we get
$$\lim_{h \to 0} \frac{a^h - 1}{h} = 1$$
multiplying $\lim\limits_{h \to 0} h$ on both sides, we get:
$$\lim_{h \to 0} \frac{a^h - 1}{h}  \lim_{h \to 0} h = \lim_{h \to 0} h$$
Collecting the limits on the left hand side gives us
$$\lim_{h \to 0} \frac{a^h - 1}{h} h = \lim_{h \to 0} a^h - 1 = \lim_{h \to 0} h $$
bringing the $1$ on the left hand side to the right hand side gives us
$$\lim_{h \to 0} a^h = \lim_{h \to 0} h + 1$$
Some amount of finagling of the expression will hence give us
$$a = \lim_{h \to 0} (h + 1)^{\frac{1}{h}}$$
let us now state that $\frac{1}{h} = n$. This is equivalent to stating $\frac{1}{n}=h$. When $n\to\infty$, $h\to0$. Hence, we can now rewrite out original limit as being
$$a = \lim_{n \to \infty} \left(1 + \frac{1}{n}\right)^n$$
This is where the limit definition of Euler's number comes from. From this, we can know for certain a fundamental (if not the defining property of) the number $e$. And more importantly, it helps us understand why the derivative of $e^x$ is $e^x$. It isn't a coincidence, it's the very definition of $e$! If you're determined to find a connection between $e$ and some property as $\pi$ is to circles, then here it is: the holy grail. Euler's number is fundamentally and inextricably linked to rate of change problems. Although this is an idea you seem to have grasped intuitively, even before considering the underlying calculus.
Questions $1$ and $2$ can be answered simultaneously. By proving that the limit and series definitions of $e^x$ are equivalent, we can show definitively that there is a link between the Taylor series and exponentiation. The intuition will come naturally once you can see how the two can be equated directly without using the exponential function as an explicit intermediate.
This is slightly more difficult to prove (or rather, more difficult on my stubby little fingers as I do my best to work out the LaTex)
Let us begin by only considering the expression
$$\left(1+\frac{1}{n}\right)^n$$.
We can expand the brackets by using the binomial theorem as follows:
$$\left(1+\frac{1}{n}\right)^n = \sum_{k=1}^n \frac{n!}{k!(n-k)!n^k}$$
By doing some simplifications we get
$$\left(1+\frac{1}{n}\right)^n = 1 + \sum_{k=1}^n \frac{\prod\limits_{j=1}^{k-1} (n-j)}{k!n^{k-1}}$$
Simplification is a relative term. It comes together later though, I swear. Given $x\in\mathbb N$, we can state that
$$n^x = \prod_{i=1}^x n$$
We can hence use this information to state that
$$\left(1+\frac{1}{n}\right)^n = 1 + \sum_{k=1}^n \frac{1}{k!} \prod\limits_{j=1}^{k-1} \frac{(n-j)}{n}$$
This is equal to
$$1 + \sum_{k=1}^n \frac{1}{k!} \prod_{j=1}^{k-1} \left(1 - \frac{j}{n}\right)$$
Therefore, we can state that
$$\left(1+\frac{1}{n}\right)^n = 1 + \sum_{k=1}^n \frac{1}{k!} \prod_{j=1}^{k-1} \left(1 - \frac{j}{n}\right)$$
Let us now take the limit as $n\to\infty$ on both sides
$$\lim_{n \to \infty} \left(1+\frac{1}{n}\right)^n = 1 + \lim_{n \to \infty} \sum_{k=1}^n \frac{1}{k!} \prod_{j=1}^{k-1} \left(1 - \frac{j}{n}\right)$$
Since $\frac{j}{n} \to 0$ when $n\to\infty$, the product term simply turns into the product of a whole bunch of $1$s. As a result, regardless of what $n$ or $k$ is, the whole product becomes $1$. Hence
$$\lim_{n \to \infty} \left(1+\frac{1}{n}\right)^n = 1 + \sum_{k=1}^\infty \frac{1}{k!}$$
Because $0!=1$, $\frac{1}{0!} = 1$. As a result, we can bring the $1$ that's in front of the summation back into the summation. Hence
$$\lim_{n \to \infty} \left(1+\frac{1}{n}\right)^n = \sum_{k=0}^\infty \frac{1}{k!}$$
QED.
I would recommend trying this for yourself, by attempting to prove that this holds true for all $e^x$. Here's a hint to get you started: $e^x = \lim\limits_{n \to 0} \left(1 + \frac{x}{n}\right)^n$
Finally, you ask the big boy. The mega question. The real thinker. What does $e^{i\theta} = \cos(\theta) + i\sin(\theta)$ mean?
There are two common approaches to this. Firstly, there is the method that uses the Taylor series of $\sin(x)$, $\cos(x)$, and $e^{ix}$. But if I'm being perfectly honest... I kinda really don't want to go through the trouble of doing all that LaTex again. Which is why we move on to the second way: the Picard-Lindelöf theorem.
This theorem states that given that there are $2$ functions which satisfy

The same differential equation and
The same initial conditions

The two functions will be equal
Let us look at the function $f(x) = e^{ix}$. The derivative of this function becomes $ie^{ix}$. Hence, this is a solution to the differential equation $f(x) = if'(x)$. In addition, let us take note of the fact that $f(0) = 1$. This will become important later.
Next, let us take a look at the function $g(x) = \cos(x) + i\sin(x)$. In this case, $g'(x) = -\sin(x) + i\cos(x) = i(\cos(x) + i\sin(x))$. Therefore, $g'(x) = ig(x)$. in addition, $g(0) = \cos(0) + i\sin(0) = 1 + 0i = 1$.
Therefore, we know that the two functions have the same initial values. We know that they both are solutions to the same differential equation. As a result, we can state (by Picard-Lindelöf) that $e^{ix} = \cos(x) + i\sin(x)$. (Please note that this is not my proof. This is something I retrieved from this video; see Epic Math Time's segment on the proof of Euler's Formula). If you have the time, feel free to attempt the other method as well. It is actually simple enough if you do it by hand, given that you expand everything out rather than leaving it in terms of sigma notation.
Now onto the more pressing question: what does this mean?
Let us begin by opening the complex plane (take the $y$ axis to be the imaginary axis and the $x$ axis to be the real axis)

Given that you have a complex number $z = a + ib$ (where $a$ and $b$ are both members of the real numbers) $a$ will be the real part of $z$, and $b$ will be the imaginary part of $z$. We can plot $z$ using rectangular coordinates.
Given $z = \cos(t) + i\sin(t)$, $\cos(t)$ is the real part of $z$, and $\sin(t)$ is the imaginary part of $z$. We can hence parameterize the real and imaginary parts of $z$ in terms of an arbitrary parameter $t$ (which, as is customary with calculus, is measured in radians). Drawing this on the graph gives us the following;

As we can see, this image shows a unit circle. So the graph of outputs of $\cos(x) + i\sin(x)$ forms a unit circle on the complex plane. But we proved earlier that $\cos(x) + i\sin(x) = e^{ix}$. Therefore, given that we have a real number input $x$, the output of the function $e^{ix}$ will be a unit circle on the imaginary plane. I just spent over an hour on just the LaTex. Please send help. Peace out.


Getting windows only images from the IE Dev Tools site

Question: I think this may be  website bug but when I choose VirtualBox and Mac on this page: https://dev.windows.com/en-us/microsoft-edge/tools/vms/mac/ for anything higher than IE9 I get images for virtualbox Windows only.
Answer: You can safely ignore the filename. The content is exactly the same and the filename will change in a future update (hopefully sometime in January).
Source: I'm the PM of the website.
Comment: Ok, that works for sourcing. :) There's something about the current bundle that makes the default unarchive tool on my current gen, current software mac freak out and archive the file in a different format when I attempt to extract the contents. But when I used unarchiver (3rd party) it works fine. Maybe something to look into.
Comment: Files are too big and we need to use zip64 which is not supported by the Mac GUI (I believe the cmd works). We used rar files back in the day but people preferred zip files...


How do I implement a VIDEO gallery like gallery formatter but with videos?

Question: I need to implement a gallery of videos in DRUPAL 7 like gallery formatter in Drupal 7 but with videos.
The videos are from YOUTUBE.  I created a content type named "video" and I have used the module:  http://drupal.org/project/video_embed_field for upload the code of video.  Have you any idea for create the video galleries?
Thanks for your help.
Answer: If you're able to switch to a module other than video_embed_field I'd highly recommend the Media module along with the Media Gallery module.
You'll also want Media Youtube, I've used those three together quite a bit and they're very good.
I'd also recommend installing Colorbox to take advantage of the built-in lightbox features.
Comment: The Media Gallery module is in beta... Have you experienced it's trustable for your production site?
Answer: Also, check out the MediaFront module. It is a front end media solution for Drupal. It employs an innovative and intuitive administration interface that allows the website administrator to completely customize the front end media experience for their users without writing any code. In addition to this amazing module is the built-in Open Standard Media (OSM) Player.
You can embed your youtube videos, customize the look of the player, create playlist or galleries using views and much more.
Answer: The video_embed_field module is great. Now you just need to create a view to display a table or grid of thumbnail images and then link them to the node display page to display the embedded youtube video.
Checkout the video page on my site. It combines youtube videos with uploaded videos from the video module. When I did it a few months ago you couldn't link the thumbnail to the node display. If that's still not fixed just use a simple rewrite to "node/[nid]".
Comment: it's just a view with a "taxonomy term" contextual filter, similar to: http://drupal.stackexchange.com/questions/17920/related-content-in-drupal-7
Comment: Yes, and how can I do for the view be similar to display of gallery formatter?
Comment: not sure what the "gallery formatter" looks like but you can modify and theme your views output in many ways.
Comment: hi MotoTribe. how work related videos in your video page?
Answer: Personally I wasnt finding the media module pleasant to work with so based on several other modules I created a feature called youtube_importer_feature. Together with video_filter and video_filter_field (plus the patches I added here and here that they havent committed yet) you can import directly from youtube json api and then display those videos in any way you like but most importantly using views.


Python error: could not convert string to float: 'male'

Question: I see that similar questions have been asked, but it doesn't look like those were caused by the same problem. Here is my code that gives the error:
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import KNeighborsRegressor
from io import StringIO
d = pd.read_csv("http://www.stat.wisc.edu/~jgillett/451/data/kaggle_titanic_train.csv")
data  =d[['Survived','Pclass','Sex','Age','SibSp','Parch']]
#print(data.head(n=7))
y = data.Survived
X = data[['Pclass','Sex','Age','SibSp','Parch']]
k = 3
knn = KNeighborsClassifier(n_neighbors=k, weights='distance', metric='euclidean')
knn.fit(X, y)

So I tried to convert it to float like this:
data.Sex=data[['Sex']].astype(float)

But that just gives the exact same error. Why is it not able to convert the string to float?
Comment: For starters, the string type can NOT be converted to float value. Additionally, when sharing errors on SO, it's best to pass the actual error produced by the python interpreter.
Comment: you can change that categorical data datatyped string to numerical by one hot encoding or label encoding
Answer: You can use replace or pd.factorize:
data['Sex'] = data['Sex'].replace({'male': 0, 'female': 1})

# OR

data['Sex'] = pd.factorize(data['Sex'])[0]

Output:
>>> data
     Survived  Pclass  Sex   Age  SibSp  Parch
0           0       3    0  22.0      1      0
1           1       1    1  38.0      1      0
2           1       3    1  26.0      0      0
3           1       1    1  35.0      1      0
4           0       3    0  35.0      0      0
..        ...     ...  ...   ...    ...    ...
886         0       2    0  27.0      0      0
887         1       1    1  19.0      0      0
888         0       3    1   NaN      1      2
889         1       1    0  26.0      0      0
890         0       3    0  32.0      0      0

[891 rows x 6 columns]

Important note
To prevent SettingWithCopyWarning, use:
url = 'http://www.stat.wisc.edu/~jgillett/451/data/kaggle_titanic_train.csv'
cols = ['Survived', 'Pclass', 'Sex', 'Age', 'SibSp', 'Parch']
data = pd.read_csv(url, usecols=cols)

# OR

data = d[['Survived', 'Pclass', 'Sex', 'Age', 'SibSp', 'Parch']].copy()


Cycle 2 "Loading" background image

Question: Im trying to add a loading now gif to my cycle 2 plugin. How do i force the gif to load before the images load?
Currently i have my loading.gif as a background image. Problem is the loading.gif isn't loading  first
Answer: Have a look at the Cycle2 API page, the loader option and the associated demo. In summary:

Set data-cycle-loader="wait" on the slideshow div. This pauses the slideshow until all images are loaded.
Set the background of the slideshow div to display the loading gif. Use CSS to center this image. Here is the rule used in the above mentioned demo:

.cycle-slideshow {
    background: url(http://malsup.github.com/images/spinner.gif) 50% 50% no-repeat;
}

Cycle 2 "Loading" background image


How are Linear Differential Equations formed?

Question: A linear differential equation of second or higher order have more than $1$ solutions of $y (y1, y2,$ etc.). Hence a common solution is obtained by assuming $y = c1y1 + c2y2+.....$
Now my questions are:

How are linear differential equations formed from general algebraic expressions?
Why is it that a linear differential equation of second or higher order contain more than one solution of y that satisfy them?
Answer: If you're good with your linear algebra, solutions to an $n^{th}$ order linear differential equation form a vector space of dimension $n$, and every vector space has a basis of $n$ linearly independent vectors that span the space. In this case our vectors are functions! So an $n^{th}$ order equation will form an $n$-parameter family of solutions that are closed under addition and scalar multiplication. So if $y_1$,$y_2$,...,$y_n$ are solutions to the equation then $c_1y_1+c_2y_2+$...+$c_ny_n$ is also a solution for any real numbers $c_1,c_2$,...,$c_n$. This is also sometimes called the "principle of superposition".
Answer: When we differentiate $f(x)$ and $f(x)+c$, for any constant$c$ we get the same derivative. If we are given that derivative we cannot say with definiteness for which functio9ns it is the derivative.That is the function $\cos x$ could be the derivative of either $\sin x$ or $\sin x +8$.
Now second order differential equation involves the second derivative: So the two functions $-\cos x +8x, -\cos x$ both when differentiated twice could give $\sin x$. These two  are solutions of $y''= \cos x$ and are linearly independent.
To form a a linear differential equation from an algebraic expression is easy;
The  derivative of $\sin (x-a)^2$ is  $2(x-a)\cos(x-a)^2$. Now we have to find an algebraic relationship between the function $y=\sin(x-a)^2$  and its derivative:
$2(x-a)(1-y^2)-y'= 0$


WebRTC Server side Signaling

Question: I am new to WebRTC.
I am looking to develop an Application on GAE Java infrastructure. Its a large application but I am looking to solve

Communication between Peer to Peer ie Browser to Browser

Goal :  When a user draw a line on HTML 5 canvas, it should get updated on the canvas of the other user who is watching it.  There will be one writer and multiple watchers, who only see the changes that writer is making. ( This is business logic )
Some links :  http://www.html5rocks.com/en/tutorials/webrtc/infrastructure/#how-can-i-build-a-signaling-service.  I went through through these links which gives some knowledge on WebRTC but does not demonstrate or give any clue regarding (metadata) that need to be maintain on Server side in order to develop Signaling Server. I am looking to develop Signaling server using Channel API (Java)
My confusion : How address negotiation should be done on server side to make browsers talk to each other. Little code example or Algorithm in English sentences will really help..
Please let me know if I am in wrong direction. Few guidance will make things easier for me and even help me develop it better.
Thanks for your help. I really appreciate.
Thanks,
Shashank Pratap
Comment: essentially, it is just a signalling server that will just forward messages between the parties. You may want to indicate what is being sent with each message but JSON is your friend in this regard
Answer: WebRTC is P2P communication. Media data transfer is all handled by PeerConnection library. For this p2p connections, each peer carry out ICE process. In 'ICE process', I mean sending/receiving ICE candidate information (usually a small JSON message). To do this, each peer need another direct communication channel. We just need some kind of "Chatting" rooms.
Suppose: peer1, peer2, server

peer1 connects to server, wait for the other
peer2 connects to server
server internally makes a 1:1 communication channel for peer1, 2
peer2 start ICE procedure
peer2 sends ICE candidate message to server
server blindingly forward this message to peer1
peer1 receives ICE message and then send reply
server forward this message to peer2
steps 5~8 repeats until peer1,2 establish p2p channel

And then, real data transfer begins.
I think, above is the most simplistic scenario.

WebRTC Server side Signaling


Use page.html.twig template variable in another twig template

Question: How do I call a page.html.twig template variable from the book-tree.html.twig template.
Using kint, I have found the variable, nid as in the screenshot below:
The 'nid' is highlighted, but it is the 'x-default value that is required.

This variable will be used in a set statement, comparing it to the item.original_link.nid to set an active class.
This page nid is not available within the book-tree.html.twig template.
As per Answer 1, I have created a _preprocess function in my subthemes .theme file as below:
function subtheme_bs_preprocess_book_tree(&$variables) {
 $variables['page_nid'] = 'Add code to get the node id variable';
}

The variable page_nid now shows up in the book-tree.html.twig array. The result is 'page_id' => string(36) "Add code to get the node id variable" which is the static text I added.
I would like help on how to call the nid value from the node.html.twig template. I have tried several combinations:
$variables['page_id'] = $variables['page']['content']['book_navigation']['#book_link']['nid']
But this and many other compinations I have tried all end with a:
Notice: Undefined index: page in subtheme_bs_preprocess_book_tree()
Maybe I need to call an Available method but have no clue as to how this is done.
Below is a screenshot of the {{ kint() }} output from the top of the node.html.twig file.
the value I need to target is the 115 in this line 'x-default' => value (3) 115.
Many thanks in advance.
Answer: The book-tree.twig is rendered in its own scope.  It does not "know" any of the context it is being rendered in, so it can't tap into the variables from the page twig per se.  It only gets the variables you give it.  So you could implement a THEME_preprocess_book_tree(&$variables) hook to add it in.  $variables['page_nid'] = // your code here will make it available in twig as {{ page_nid }}.
However at the risk of being "that annoying guy" who tells you not to do things instead of just answering your question

This variable will be used in a set statement, comparing it to the item.original_link.nid to set an active class.

Personally I would eschew this approach as it ends up placing logic inside the presentation layer.  I would rather use the hook to compare item nids to page nid, and add the active class to that item's attributes as appropriate.  That way the twig can be kept extremely "stupid", and simply dump out whatever attributes for all items, and those attributes will magically contain (or not contain) the appropriate classes.
Comment: **Thanks** for being "that annoying guy"
Having read many other posts about twig templates, I will now have to read a lot more to understand the `_preprocess` process.  Many thanks.


Model view and labels are not displayed correctly

Question: I created a model view and labels are not displayed correctly when I export with the module: "Views data export".
Here are the contents of my model views-view-field--sitemap--views-data-export--field-image.tpl.php :
<?php

$fields["field_image"]->content = '<image:loc>' . $field->original_value . '</image:loc>';

echo $fields["field_image"]->content;

the result is :
<image:loc>http://www.domaine.com/xxx.jpg</image:loc>
instead of :
<image:loc>http://www.domaine.com/xxx.jpg</image:loc>

Comment: What format are you trying to export your data as?  It is likely getting encoded so your content is correct in that format.
Comment: @acrosman is in .xml format
Answer: You're trying to change the content of your XML to provide structural changes to the XML document. This content is escaped so it doesn't break the XML document.
If the whole goal of theming is set your XML image field to a image:loc element, you should just change add a Label to your field with it set to "image:loc". This will render the XML document image field as an image:loc element.


DaggerMock library -how does it override module?

Question: The DaggerMock library, is used to override dagger modules with fake implementation.  Lets take a look at one robolectric topic that is confusing me:
<code> @RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class MainActivityTest {

    @Rule public final DaggerMockRule<MyComponent> mockitoRule = new DaggerMockRule<>(MyComponent.class, new MyModule())
            .set(new DaggerMockRule.ComponentSetter<MyComponent>() {
                @Override public void setComponent(MyComponent component) {
                    ((App) RuntimeEnvironment.application).setComponent(component);
                }
            });

    @Mock RestService restService;

    @Mock MyPrinter myPrinter;

    @Test
    public void testCreateActivity() {
        when(restService.doSomething()).thenReturn("abc");

        Robolectric.setupActivity(MainActivity.class);

        verify(myPrinter).print("ABC");
    }
}
</code>
So i want to know, with this Rule what exactly is happening ? I can see that RestService was being provided by MyModule but is now being replaced with a mock. But in the examples i don't see a @Inject anywhere so i'm confused how the module was even used in the first place to provide any dependencies ?
Answer: I am the author of DaggerMock, thanks for trying it!
The implementation is a bit complicated, the rule create a dynamic subclass of the module (using mockito) and override the provides methods. The rule scans the test fields so it return a field when the module has a method that returns the same type.
The final result is very similar to Mockito InjectMocks annotation. You can take a look at the implementation on github, the core class that override the module is this: https://github.com/fabioCollini/DaggerMock/blob/master/lib/src/main/java/it/cosenonjaviste/daggermock/MockOverrider.java
I release this lib just a week ago, any feedback is welcome!
Comment: So if i understand correctly, it mocks all the fields in the module i passed in,right? All provided fields from that module will be mocked?
Comment: No, it overrides just the module methods with a correspondent field in the test. So if you have no fields in the test no methods are overridden.
Comment: @FabioCollini can you please explain that a little more maybe with example "if you have no fields in the test no methods are overridden." ?


A game: When can you merge two directed graphs?

Question: I am trying to consider the conditions under which you can win the following directed graph game:

Graph merging game. Fix an acyclic directed graph $G$; its vertex set is $V$, and its edge set is $E$. In this game, you are given two copies of $G$. For each copy, the vertices have been labeled with non-negative integers.
A move in this game consists of picking an edge $a\rightarrow b$ in one of the two copies. The value at $a$ is decremented by 1; the value of $b$ is incremented by 1. You win if you can make the two copies have the same labels at corresponding vertices, where furthermore all the labels are non-negative.

I have solved the problem for the simple case when $G$ is a tree, but I am struggling to find an efficient algorithm for DAGs—although I feel like one should exist. Any suggestions?
Side note: a solution for trees:

For each copy, compute the sum of the values of each subtree.
Construct a new labeled tree whose value at each node is the larger of the two subtree sums at that node.
In the new tree: subtract from each node's value the sum of its childrens' values.
It is straightforward to see if you can make all of the values in this tree nonnegative by passing value from parent to child. If you can, the game is winnable — the resulting tree is a tree that you can make through legal moves starting from either of the initial two trees. If you can't, the game is unwinnable.

Edit: I have an idea for a reduction from this problem to maximal flow, but am not sure if it's correct. Any suggestions?

Given a graph $G$ and two labelings $n_1,n_2 : V \rightarrow \mathbb{N}$.
Create two copies $G_1$ and $G_2$ of the graph, where the edges of $G_2$ are reversed.
Join each vertex in $G_1$ to its counterpart in $G_2$.
Add a source connected to every vertex in $G_1$ and target connected from every vertex in $G_2$.
Set the channel capacity of each edge $s\rightarrow v$ to the label $n_1(v)$. Set the channel capacity of each edge $v\rightarrow t$ to the label $n_2(v)$.
For simplicity, set the channel capacity of each other edge to "maximum"---say, the total $P$ of all the values in a single labeling (for example $P \equiv \sum_{v\in V} n_1(v))$.

I feel like the game is winnable if and only if the maximal flow of this graph is of size $P$. Does that seem correct?
Answer: Let's think about the game as moving tokens around in the graph along the edges. We're given two token distributions and asked if they can be made into the same distributions of tokens.
We can play the game on a single copy of the graph, if we have red and blue tokens and a rule that says that a red token and a blue token can annihilate each other when they meet. The question is then whether we can remove all tokens from the board from a given starting position.
This is possible if and only if we can pair up all the tokens in red+blue pairs such that for every pair there is a node in the graph that is reachable from both the red and the blue starting position.
Since it is easy to compute which pairs of nodes have common descendants, this reduces the problem to determining whether a certain bipartite graph has a perfect matching.
If you can have large numbers of tokens starting out at the same node, it will be more useful to recast it as a maximum flow problem instead of a matching problem.
Comment: It's also easy to reduce bipartite matching to this problem (graph 1 has all tokens in one side, graph 2 has tokens in the other side of the bipartite graph), so the original problem can't be done faster.
Comment: @ffao: The bipartite graph to match in might have many more edges than the original one, though.
Comment: @henning When you say a certain bipartite graph, do you mean: the graph with one node for every token on every node, with an edge joining each red token and each blue token if their respective nodes have a common descendant?
Comment: @user326210: Yes, exactly.
Comment: @HenningMakholm I have recently edited the original question with a possible solution. Is this something like what you had in mind for recasting as a maximum flow problem?
Comment: @user326210: Yes, something like that. It should be easy to see that a flow of size $P$ gives you a strategy for winning the game, and conversely that if you have a winning play, then you can construct a flow of size $P$.


Singular value decomposition problem

Question: Let $A\in \mathbb{R}^{m\times n}$ have singular values $\sigma_{1}\ge\sigma_{2}\ge\cdots\ge\sigma_{k}$ (where $k=\min\{m,n\}$).Assume $\sigma_{r}>0$, $\sigma_{r+1}=0$. Prove that $\operatorname{rank}(A)=r$. I know it is from URV. But I do not know how to solve this problem directly.
Comment: Could you remind the audience what URV is...?
Comment: Yeah,but the in $URV$, there is an equation that I do not know why,$rank(U^{T}AV)=rank(A)=r$.
Comment: Can you show that $\operatorname{rk} R = r$? This is the 'difficult' part.
Comment: $r_{ij}=u^{T}_{i}Av_{j}$,$u_{i}^{T}=0$ for $i=r+1,\ldots,m$and$Av_{j}=0$for $j=r+1,\ldots,n$
Comment: I was thinking in terms of the dyadic expansion $A= \sum_i \sigma_i u_i v_i^*$. Then $Av_i = \sigma_i u_i$, hence $\{A v_i\}_{i=1}^r$ are linearly independent, hence $\operatorname{rk} A \ge r$. Furthermore, $A v_i = 0$ for $i=r+1,...,m$, hence $\dim \ker A \ge m-r$. The rank nullity theorem gives the desired result.
Comment: @copper.hat You could post that as an answer...
Comment: @40votes: Thanks for the suggestion.
Answer: Consider the dyadic expansion $A= \sum_i \sigma_i u_i v_i^*$. Then $Av_i = \sigma_i u_i$, hence $\{A v_i\}_{i=1}^r$ are linearly independent, hence $\operatorname{rk} A \ge r$. Furthermore, $Av_i=0$ for $i=r+1,...,m$, hence $\dim \ker A \ge m-r$. The rank nullity theorem gives the desired result.

Singular value decomposition problem


background color change on mouse leave bootstrap navbar

Question: I have created a navigation menu using Bootstrap 3 navbar. But It has a small issue:
When mouse moves over a menu item it perfectly change its color to dark green. But when I leave the menu, it does not directly changes its color to light-green. It quickly changes to gray(default) color and then turn to light green.
Below is a screen of my navigation bar:

.navbar-default{
    background-color: #4ec67f;
}

.navbar-nav > li > a {
    color: #FFFFFF;
    font-size: 14px;
    font-weight: 600;
    text-transform: uppercase;
}

li.active{
    background: #34b586 !important;
}

li > a:focus{
    background: #34b586 !important;
}

li:hover > a{
    background: #34b586 !important;
    color: #FFFFFF !important;
}

li > a:hover{
    color: #FFFFFF !important;
    background: #34b586 !important;
}

How to avoid this problem? Thanks in advance.
Comment: Quite hard task to debug an...image
Comment: You'll have to add some code to this post.
Comment: check in dom inspector if ondrop down any class is given to `li` with that you can add the hover styles to that class
Comment: Could you create an online demo..?
Answer: This is a basic setup, and is all you need. It looks like your issue is that you're not setting a color on your anchor tags by default. Also, no need to set a focus style, just deal with the hover event.
http://jsfiddle.net/6uhbh3su/4/
HTML:

        Tab 1

        Tab 2

CSS:
li a:hover{

    background: red;
    color: white;
}
a{
    background: black;
    color: blue;
    display: inline-block;
    padding: 3px 8px;
}
li{
    display: inline-block;
}

Comment: Thanks but this is not what i want. when i apply background color to element  then it is visible also at the default state.
Comment: @solidshadow So just add that color in, instead of `black` ?


How to get all linked nodes from all terms in a vocabulary

Question: I have a content type "News entry", which has a term reference "News category", which is of course a taxonomy vocabulary.
I'm not sure if I get this whole taxonomy thing right, but I'm able to render and theme each category correctly (/news/category-a).
Now I want to theme the overview or home page, which displays all news entries of all categories. Easiest way for me would be selecting the right rows out of the database, but I reckon that's not very much the Drupal way.
So I figured out how to get all terms of a vocabulary. In the preprocessing function theme_preprocess_node_news_overview() I tried taxonomy_get_tree(). Now I've got an object for each term with the following contents:
https://i.stack.imgur.com/cbT8c.png
(can't post images yet)
The news entries are preprocessed in theme_preprocess_node_news_post(), It'd be great if this function could be reused for the news overview.
And now I'm stuck. How do I get Drupal to behave like it's displaying a category/tax. term, but instead of the nodes of one term get (and display) the nodes of all terms?
Answer: As "all linked nodes from all terms" are in my case the same as "all nodes of a content type", I solved my problem this way:
<code><?php
function themename_preprocess_node_news_overview(&$vars) {
  $results = db_query("SELECT nid, type FROM {node} WHERE type = 'news_post';");
  $tmp = array();
  foreach ($results as $result) {
    $tmp[] = $result->nid;
  }
  $vars['content'] = node_view_multiple(node_load_multiple($tmp), 'teaser');
}
?>
</code>


How to take normal text from database table and change according to defined variable from other database table

Question: public function customer_bill_reminder()
{
    if($this->session->userdata('role') == "ADMIN" || $this->session->userdata('role') == "SUPER ADMIN")
    {

        $from = $this->input->post('from');
        $to   = $this->input->post('to');

        $result = $this->MAILModel->customer_sms_reminder($from,$to);
        $result2 = $this->MAILModel->auto_sms_reminder();

        foreach($result2 as $row)
        {
            $message = @$row->sms_template;
        }

        foreach($result as $row)
        {
            $phone_number = @$row->mobile;
            $year = @$row->bill_period;
            $control_number = @$row->control_number;
            $amount = @$row->bill_amount;
            $message = "You will pay $amount in $year";

            echo $message;

            $this->NotificationModel->send_sms($phone_number,$message);
        }
    }
}

The above hard coded text from $message will change $amount and $year. I have problem since the text is from the database - when I echo nothing happens, it will output exactly as it is.
I want to get the output as exactly the hard-coded text but it should be from the table.
Comment: I just don't see how that's possible. PHP will parse variable names inside a double-quoted string (see https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing). As far as I know, that feature can't be switched off...but perhaps someone will correct me.
Comment: Do you mean it will literally echo `You will pay $amount in $year`, without changing $amount and $year into values?
Comment: Yes It will not change $amount and $year but when I put the exactly text from table by declaring in $message it will work great
Comment: But...how much debugging have you done? My only observations here are that: first you set `$message` to be the content of `$row->sms_template;`. What does that field contain exactly? And why do you do that, since the second loop would just overwrite it? And secondly, have you tried to individually `var_dump($amount);` and `var_dump($year);` to verify that they contain what you expected?
Comment: The field from table contains "You will pay $amount in $year" . The purpose to put that to make user to be able to edit message. Every person has different $amount to pay. If the message were needed to be hard-coded. It will be no problem
Comment: Yes it would need to be hard-coded (which you have already done in the `$message = "You will pay $amount in $year";` line anyway), because if you load the string from a database field it will not be treated as an interpolated string, and also you're loading it before you've defined the other variables which go into it.
Comment: I have already found solution through using str_replace function
Comment: That's great. If you think it would help others with a similar issue, please add it as an Answer below (see [answer]). Otherwise you can delete the question
Answer:      $message1    = str_replace('$amount',$amount,$message);

     $message2=str_replace('$phone_number',$phone_number,$message1);
     $message3=str_replace('$control_number',$control_number,$message2);
     $message4=str_replace('$year',$year,$message3);
     $this->NotificationModel->send_sms($phone_number,$message4);


Prove that $\dfrac{72!}{(36!)^2}-1$ is divisible by $73$

Question: Prove that $\dfrac{72!}{(36!)^2}-1$ is divisible by $73$
My multiple attempts are as follows:-
Attempt $1$:
If we can prove $\dfrac{72!}{(36!)^2}$ as $73\lambda+1$, then we will be done
$$\dfrac{72!}{(36!)^2}={36\choose 0}^2+{36\choose 1}^2+{36\choose 2}^2+\cdots\cdots+{36\choose 36}^2$$
I didn't get anything from here, so I tried another method
Attempt $2$:
$$72!=2^{36}(36!)\prod_{k=1}^{36}(2k-1)$$
$$\dfrac{72!}{(36!)^2}=\dfrac{2^{36}\prod_{k=1}^{36}(2k-1)}{36!}$$
$$\dfrac{72!}{(36!)^2}=\dfrac{2^{36}\prod_{k=1}^{36}(2k-1)}{2^{18}(18!)\prod_{k=1}^{18}(2k-1)}$$
$$\dfrac{72!}{(36!)^2}=\dfrac{2^{36}\prod_{k=1}^{36}(2k-1)}{2^{27}(9!)\prod_{k=1}^{9}(2k-1)\prod_{k=1}^{18}(2k-1)}$$
$$\dfrac{72!}{(36!)^2}=\dfrac{2^{9}\prod_{k=1}^{36}(2k-1)}{9\cdot2^4(4!)\prod_{k=1}^{4}(2k-1)\prod_{k=1}^{9}(2k-1)\prod_{k=1}^{18}(2k-1)}$$
$$\dfrac{72!}{(36!)^2}=\dfrac{4}{27}\cdot\dfrac{\prod_{k=1}^{36}(2k-1)}{\prod_{k=1}^{4}(2k-1)\prod_{k=1}^{9}(2k-1)\prod_{k=1}^{18}(2k-1)}$$
$$\dfrac{72!}{(36!)^2}=\dfrac{4}{27}\cdot\dfrac{37\cdot39\cdot41\cdots\cdots71}{(1\cdot3\cdot5\cdot7)(1\cdot3\cdot5\cdot7\cdots\cdots17)}$$
Now it will take lot of time to cancel out all these terms, any other way of doing this problem.
Comment: Use [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem) and [this other consequence of Wilson's theorem](https://math.stackexchange.com/questions/889241/a-consequence-of-wilsons-theorem).
Answer: Let us work in the field $F=\Bbb F_{73}$, with characteristic $73$, a prime number.
Then Wilson's theorem shows $72!=-1$ in $F$, but we go an other way, and calculate in $F$:
$$
\begin{aligned}
(36!)^2
&=36!\;36!\\
&=36!\cdot(-36)(-35)\dots (-2)(-1)\\
&=36!\cdot(73-36)(73-35)\dots (73-2)(73-1)\\
&=72!\ .
\end{aligned}
$$
So we have to show $72!/72!-1=1-1$ is zero in $F$.
$\square$
Answer: $\displaystyle \binom{72}{36}=$ coefficient of $x^{36}$ in $\displaystyle (1-x)^{72} = \frac{(1-x)^{73}}{1-x}$
$$=(1-x)^{73}(1-x)^{-1}$$
$$=\bigg[\binom{73}{0}-\binom{73}{1}x+\binom{73}{2}x^2+\cdots \bigg](1+x+x^2+\cdots)$$
$$=\binom{73}{0}-\binom{73}{1}+\binom{73}{2}+\cdots +\binom{73}{36}$$
which is divisible by $73$
due to the fact that $\displaystyle \binom{p}{r}$ is divisible by $p$
$p$ is prime number and $r\in \{1,2,3,4,\cdots,p-1\}$
Comment: $$=\binom{73}{0}-\binom{73}{1}+\binom{73}{2}+\cdots +\binom{73}{36}$$

How you arrived at this step from previous step? Can you explain in detail
Answer: $$\frac{72!}{(36!)^2}-1=\frac{36!37.38...72}{(36)^2}-1$$
$$=\frac{37.38.39.....72}{36!}-1$$
$$=\frac{(73-36)(73-35)....(73-1)}{36!}-1$$
$$=\frac{73m+36!}{36!}-1$$
$$=\frac{73m}{36!}+1-1$$
$$=\frac{73m}{36!}=73n \,where\, n\in N$$
Where m will be multiple of $(36!)$ as $\frac{72!}{(36!)^2}={72 \choose 36} \in N$
Comment: How can we say $$(73-36)(73-35)....(73-1)= 73m+36!$$, can you explain it in detail.
Comment: These are of form $(x-36)(x-35)(x-34)....(x-1)$ where $x=73$ which is polynomial in where every term except constant are multiple of $x$ and constant is product of zereos.


Array de condições SQL - PHP

Question: boa tarde, estou mandando um filtro de busca para meu BD, e quero fazer essas condições dentro de um array, por exemplo:
$condicoes = array();

$nome = $_GET['nome'];
if (!empty($nome)) {
    $condicoes = ("nome" => $nome);
}
$tipoAnimal = $_GET['tipoAnimal'];
if (!empty($tipoAnimal)) {
    $condicoes = ("tipoAnimal" => $tipoAnimal);
}
$raca = $_GET['raca'];
if (!empty($raca)) {
    $condicoes = ("raca" => $raca);
}
$tamanho = $_GET['tamanho'];
if (!empty($tamanho)) {
    $condicoes = ("tamanho" => $tamanho);
}
$sexo = $_GET['sexo'];
if (!empty($sexo)) {
    $condicoes = ("sexo" => $sexo);
}
$estado = $_GET['estado'];
if (!empty($estado)) {
    $condicoes = ("estado" => $estado);
}
$cidade = $_GET['cidade'];
if (!empty($cidade)) {
    $condicoes = ("cidade" => $cidade);
}

ai no final faria um implode eu axo, para colocar o AND para que na query fique:
SELECT * FROM nome_tabela WHERE $condicoes;

Answer: Sim, você pode usar implode/join, mas seu código está muito repetido, um jeito mais simples de fazer isso é:
$keys = array('nome', 'tipoAnimal', 'raca', 'tamanho', 'sexo', 'estado', 'cidade');

$conditions = array();

foreach($keys as $key) {
    $val = $_GET[$key];
    if (!empty($val)) {
        $conditions[] = "$key = '$val'";
    }
}

$full_conditions = join(" AND ", $conditions);
$sql = "SELECT * FROM nome_tabela" . (empty($full_conditions) ? "": " WHERE $full_conditions;");

Essa resposta vale apenas para busca por igualdade no banco de dados, não daria para fazer algo do tipo select * from tabela where nome like '%foo%', sugiro que você leia sobre ORMs em PHP[0].
[0] http://pt.wikipedia.org/wiki/Mapeamento_objeto-relacional
Comment: Nesse caso teria que verificar ali, caso o `$full_conditions` estiver vazio para não adicionar o `WHERE` no SQL, senão vai dar erro na consulta.
Answer: Uma alternativa similar à do @Peoplee mas que não sofre da limitação descrita por ele é popular o array em pequenos fragmentos, seguindo uma lógica pré-especificada pela Aplicação:
/**
 * Trata os dados de $_POST, sanitizando as informações e removendo
 * vazios e inválidos, como Estado (ver a ER e a forma de aplicação no link abaixo)
 *
 * @see http://jsfiddle.net/brunoaugusto/6fV6C/
 */
$data = array( 'tipoAnimal' => 'cachorro', 'estado' => 'SP', 'cidade' => 'Nova' );

$clauses = array();

if( array_key_exists( 'tipoAnimal', $data ) ) {
    $clauses[] = sprintf( '`tipoAnimal` = "%s"', $data['tipoAnimal'] );
}

if( array_key_exists( 'estado', $data ) ) {
    $clauses[] = sprintf( '`estado` = "%s"', $data['estado'] );
}

// Aqui nós variamos o formato

if( array_key_exists( 'cidade', $data ) ) {
    $clauses[] = sprintf( '`cidade` LIKE "%%%s%%"', $data['cidade'] );
}

$query = 'SELECT * FROM `tabela`';

if( count( $clauses ) > 0 ) {

    $query .= implode( ' AND ', $clauses );
}

echo $query;

Assim, caso o dado seja informado e venha em $_POST e passe por qualquer filtro ou validação que você venha a definir, a query será dinamicamente construída.
Porém, mesmo mais flexível, essa abordagem ainda tem uma limitação que é o de implicar o uso da cláusula AND para todas as condições. Você pode trocar pela cláusula OR ou manter como está, depende da lógica da sua Aplicação.
Apenas a título de curiosidade, esse tipo de problema não ocorre em frameworks de domínio específico, como Doctrine, por exemplo pois neles você normalmente faz algo como (não se atenha á sintaxe):
$select = new Select( 'tipoAnimal', 'estado', 'cidade' );

$select ->      from( 'tabela' )
        ->     where( 'tipoAnimal = ?', $data['tipoAnimal'] )
        ->     where( 'estado = ?',     $data['estado'] )
        ->   orwhere( 'cidade LIKE ?',  $data['cidade'] ); // Esse aqui será um OR

Answer: Uma coisa bem básica e didática seria assim:
$condicoes = array();

$nome = 'bidu';

if (isset($nome)) {
    $condicoes["nome"] = $nome;
}
$tipoAnimal = 'cachorro';
if (isset($tipoAnimal)) {
    $condicoes["tipoAnimal"] = $tipoAnimal;
}

$where = "";
$i = 1;
foreach($condicoes as $key => $c){
    if($i == 1){
        $where .= "$key like '%$c%' ";
    }else{
        $where .= "and $key like '%$c%' ";
    }
    $i++;
}

echo "SELECT * FROM nome_tabela WHERE $where";

Nesse caso o exibido na tela foi o seguinte:
SELECT * FROM nome_tabela WHERE nome like '%bidu%' and tipoAnimal like '%cachorro%'

Comment: Você está passando uma informação errada quanto ao `empty`. O `empty`serve para verificar se a variável está vazia ou é zero, e se aplica a uma série de usos além do _array_. Inclusive, em algumas ocasiões que é melhor para checar parâmetros do que `isset` (não estou falando especificamente do caso do OP). Veja mais em: http://php.net/manual/pt_BR/function.empty.php
Comment: É bem isso mesmo, eu só faria uma pequena alteração que seria: `$where .= "{$key} like '%{$c}%' AND ";` e depois do loop colocava um `rtrim($where,' AND ')` pra evitar fazer __n__ comparações (o que pode prejudicar a performance quando o loop é muito grande).
Answer: Considere utilizar uma biblioteca para gestão do banco de dados. ;)
ConnectionMSi
Ai você poderia fazer algo como:
$keys = array('nome', 'sexo', 'estado', 'cidade', 'fone');
$where = Array();
foreach ($keys as $key)
   if (!empty($_REQUEST[$key]))
      $where[$key] = $_REQUEST[$key];

$resultado = $con->Select('nome_tabela', $where);

Array de condições SQL - PHP


For what range of $\beta$ is random walk heavy-tailed?

Question: I have $\beta > 0$ and $S_0 = 0$, and $S_n = \varepsilon_1 + \cdots + \varepsilon_n, n \geq 1$, a random walk with i.i.d increments $\lbrace \varepsilon_n \rbrace$ having a common distribution
$$ P(\varepsilon_1 = -1) = 1 - C_{\beta} \text{ and } P (\varepsilon_1 > t) = C_{\beta}e^{-t^{\beta}}, t \geq 0,$$
where $C_{\beta} \in (0,1)$ such that $\mathbb{E}\varepsilon_1 = -1/2$.
I want to find the range of values of $\beta$ for which this random walk is heavy-tailed.
So far I have tried using the fact that a heavy-tailed distribution has infinite moment-generating function, as follows:
\begin{align*}
\varphi(t) = \mathbb{E}e^{t \varepsilon} = e^{-t}(1-C_\beta) + \int_0^\infty x (1-C_\beta e^{-t^\beta}) \, dx
\end{align*}
but that route doesn't seem to lead anywhere, given that the integral itself is always infinite. I have the same problem when trying to determine the value of $C_\beta$ by using fact that the expectation of $\varepsilon_1$ is $-1/2$.
Can anybody see what I'm doing wrong? Or have any ideas for me to try?
Answer: I used a different definition of heavy-tailedness: If a distribution is heavy-tailed, then $\lim_{t \to \infty} e^{\lambda t} \overline{F}(t) = \infty, \quad \forall \lambda >0$.
Therefore
\begin{align*}
\lim_{t \to \infty} e^{\lambda t} C_{\beta} e^{-t^{\beta}} = \infty \implies \lambda t - t^{\beta} >0 \implies \lambda > t^{\beta-1} \implies \beta - 1 < \frac{\log \lambda}{\log t}
\end{align*}
For large $t$ and fixed $\lambda$, $\frac{\log \lambda}{\log t} \approx 0$, and we therefore have that
\begin{align*}
\lim_{t \to \infty} e^{\lambda t} C_{\beta} e^{-t^{\beta}} = \infty \implies \beta < 1
\end{align*}
Therefore the distribution is heavy-tailed if $\beta \in (0,1)$.


How to get the minimum and maximum value of algebraic expression?

Question: here is the link of the question What will be the minimum value of the expression
Comment: See here: https://www.desmos.com/calculator/jyuq1eiidf. By this, the answer is C
Answer: Instead of trying to go about the problem as a whole, break it up into smaller parts. Define $$\left(x+\frac{1}{x}\right)^2+\left(y+\frac{1}{y}\right)^2 \quad\text{as} \quad f(x)+g(y)$$
Where $$f(x) = \left(x+\frac{1}{x}\right)^2 \quad \text{and} \quad g(y) = \left(y+\frac{1}{y}\right)^2$$
You'll quickly notice that these functions are (basically) identical. Their derivatives are $$f'(x) = 2x-\frac{2}{x^3} \quad \text{and} \quad g'(y) = 2y-\frac{2}{y^3}$$
They have global minimums of $4$ at $1 \; \text{or}\;-1$. Unfortuantely for us, that does not add to $1$! So we dig a little deeper, we know that both $f(x)$ and $g(y)$ have asymptotes at $0$ and that they grow exponentially as they approach $0$. From this we can devise a strategy to find the minimum. The best way to do this is to just split $1$ right down the middle and have $x=0.5$ and have $y=0.5$ as well. This will return $12.5$ answer C.
The reasoning behind splitting one in half is that because the functions have asymptotes as they approach zero, shifting either function even slightly will cause an exponential increase. Even if we lower one value to $0.25$, the value of the other at $0.75$ outweighs it.
Answer: By the generalized means inequality:
$$
\sqrt{\frac{x^2+y^2}{2}} \ge \frac{x+y}{2} \ge \sqrt{\frac{2}{\cfrac{1}{x^2}+\cfrac{1}{y^2}}} \quad\implies\quad \begin{cases}x^2+y^2 \ge 2 \cdot \left(\dfrac{x+y}{2}\right)^2 = \dfrac{1}{2} \\[10px]
 \dfrac{1}{x^2}+\dfrac{1}{y^2} \;\ge\; \dfrac{8}{(x+y)^2}=8
\end{cases}
$$
It follows that the following inequality holds, with equality iff $\,x=y=\dfrac{1}{2}\,$:
$$\left(x+\frac{1}{x}\right)^2+\left(y+\frac{1}{y}\right)^2 = x^2+y^2 + \frac{1}{x^2}+\frac{1}{y^2}+4 \ge \frac{1}{2}+8 + 4 = \dfrac{25}{2}$$


TreeView bound to XMLDataProvider - shows data in editor, but empty when run

Question: I have bound a TreeView to an XMLDataProvider.
The TreeView displays the data as expected in the Visual Studio editor. But when I press F5, the application runs but the treeview is blank. Does anyone know why I can't see it when I run the application?
Here's the entire code:
<Window x:Class="TreeViewDataBinding.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
    <XmlDataProvider x:Key="FolderList">
        <x:XData>
            <TreeFolders>
                <Folder Name="Audit Reports" />
                <Folder Name="Joes Test" >
                    <Folder Name="Analysis01" />
                    <Folder Name="Test090803" />
                </Folder>
                <Folder Name="Carl" />
                <Folder Name="Steve" />
            </TreeFolders>

        </x:XData>
    </XmlDataProvider>
    <HierarchicalDataTemplate
                    x:Key="FolderTreeItemTemplate"
                    DataType="Folder">
        <HierarchicalDataTemplate.ItemsSource>
            <Binding XPath="child::*" />
        </HierarchicalDataTemplate.ItemsSource>
        <TextBlock Text="{Binding XPath=@Name}" />
    </HierarchicalDataTemplate>
        </Window.Resources>
    <Grid>
        <TreeView
            ItemsSource="{Binding Source={StaticResource FolderList}, XPath=//TreeFolders/*}"
            ItemTemplate="{StaticResource FolderTreeItemTemplate}" />
    </Grid>
</Window>

Answer: I didn't run the code, but my guess is that you need to specify a namespace:
xmlns=""

Attach xmlns to your fist data tag:
<XmlDataProvider x:Key="FolderList">
    <x:XData>
        <TreeFolders xmlns="">
            <Folder Name="Audit Reports"/>
            <Folder Name="Joes Test">
                <Folder Name="Analysis01"/>
                <Folder Name="Test090803"/>
            </Folder>
            <Folder Name="Carl"/>
            <Folder Name="Steve"/>
        </TreeFolders>
    </x:XData>
</XmlDataProvider>

Comment: Thanks - I would NEVER have thought of that one.
Comment: My listbox wasn't working for the same reason. Things have become complicated with wpf (and no error messages help a lot).


Printing the node title instead of the file name from a field

Question: I have a block view, which is an unformatted list which prints my content type. All content has a field_file which I access using views-view--download--field-file.html.twig.
This prints a file link with the filename, like normal.
But is it possible to replace for example document.txt with Document node title?
Answer: You can handle it directly from your View configuration using the "Rewrite results" option from field configuration.

Edit your View
Under the fields section, add your Content: title field, chexk "Exclude from display" and uncheck "Link to the content".
then, add your file field Content: my_file_field, choose the formatter "URL to file" and expand the Rewrite results section. Check Override the output of this field with custom text and use the textarea to write the replacement text. It accepts HTML and, most importantly, tokens (you can see the list of available tokens under the "Replacement patterns" section). In the end, something like {{ title }} would do the trick.
Comment: Thanks it works!


How to get Drush in my path in Windows 10?

Question: I have Drush 9 installed on Windows 10.  I installed it via Composer using Lando.
I want to put this drush in my system path so that I can use it from cmd.exe, Powershell, and so on. I want to do this because I am trying to run Drupal Behat Extension tests with the Drush driver, which requires drush to be in the path.
What I tried
Windows 10 Control Panel -> System -> Edit environment variables
Under "User variables for MYUSERNAME", I added:

Variable: LANDO_FRIENDS
Value: C:\pathtowebsiteinstalledbycomposer\vendor\bin

Then I rebooted and tried to run drush:

drush : The term 'drush' is not recognized as the name of a cmdlet,
  function, script file, or operable program. Check the spelling of the
  name, or if a path was included, verify that the path is correct and
  try again.

So then, from PowerShell, I changed to the \vendor\bin directory and ran ./drush.  This opened up a prompt How do you want to open this file?
I don't understand why this is happening.
Here's what does work:

I can run drush from Powershell using lando, i.e., lando drush status.
I can open up a bash shell with the Windows Linux Subsystem and go to /vendor/bin and enter ./drush, which causes drush to load normally.

So drush is definitely installed, but how do I use it from Powershell/cmd.exe?
Comment: Can you just add your drush path into `PATH` system variable?
Comment: @kenorb It's in the path (environment variable). Also it's not even working from Powershell when I try to execute it directly.
Comment: You're not sharing anything with PATH, can you post the example how your PATH variable looks like?
Comment: `drush` is a (Unix) shell script. On Windows you have to run launch `drush.bat`. Drush expects a couple of tools that normally isn't present on Windows, but feel free to give it a try.
Answer: The variable will be "Path". Just select that one and edit it then add new line.
You have to download the drush.phar file from here: https://github.com/drush-ops/drush-launcher/releases/tag/0.6.0
Then you have to change the file name from 'drush.phar' to just 'drush' and put that file somewhere and that location needs to be in your path. I put mine in both my system path and user path. Once that is done you shoud be able to call drush from your drupal directory if it was installed with composer.


Project platform suggestion for web application with proper User Auth and integration support

Question: So, I have an idea to build a web app. I am new to this business but am a programmer. I liked Python and thought let me start with Django. I ran into a problem with the built-in Django User Auth system as pointed by this question of mine on SO.
In short, I am using Django's built-in User auth and thought that it will easily fill my user field (the foreignkey) in my model but it does not. I have Googled and asked questions but only got a very convoluted answer or that I have to use the Admin section if I want anything like that.
My simple need is that whenever user saves anything in their profile, the user field should get populated so that I can reference it. To me, it sounds like the most basic need for any web app.
Am I wrong. I need advice. If Django is not good for this then I am ready to learn any other good framework or platform if need be.
Answer:
In short, I am using Django's built-in
User auth and thought that it will
easily fill my user field (the
foreignkey) in my model but it does
not.

This won't just magically happen. You will have make it happen. Models are separated from the request so this would happen in your view, or a model method (perhaps save) that is passed the active user.
MVC / MTV design separates the database from the view / control logic. I don't see what framework has to do with this: unless you write the functionality yourself, the database doesn't know what to do with some User table and the currently logged in user (also separated from the data). Building in this functionality would inconvenience a lot of people as well...
In general, the python/django philosophy is: Explicit is better than implicit.
Now the solutions:
If you wanted this behavior in the view, for any form, you could potentially write:
instance = MyForm.save(commit=False) # commit=False prevents DB save.
instance.user = request.user
instance.save()

You could overwrite the save method on the model that accepts an optional user argument as well.
def save(self, *args, **kwargs):
    user = kwargs.pop(user, None)
    self.user = user
    super(MyModel, self).save(*args, **kwargs)

 mymodel = MyModel()
 mymodel.save(user=request.user)

Comment: When I say `mymodel = MyModel()` it says MyModel is not defined.
Comment: Where should I put the last two lines of code? `mymodel = MyModel()
 mymodel.save(user=request.user)`
Comment: Do I need to import something in my views.py?
Comment: This is pseudo code. I can't read into your mind and know what you call your models (unfortunately). Save your modelform with commit=False, or override your Model save method (as shown above)
Comment: Sorry about that. I think the problem is that my `if form.is_valid():` check is failing. the control never goes inside that `if` statement. Weird.
Comment: Then my guess is you need to set up your modelform to remove `User` as a field. Set the modelform class Meta exclude attribute to remove your user, since you will be supplying the user yourself later. Without knowing the exact `form.errors` that's about as much i can do!


Key Signature Only On First Line

Question: This might be a dumb question (I've only been playing nearly 2 years), but if the key signature is only stated on the first line of the music, would that still apply to the rest of the music or not? I'm going through an audition piece and don't want to be playing the wrong notes. Thanks.
Answer: The strict rule is that key signatures are re-stated on every stave.   A change from x sharps or flats to zero sharps or flats will be marked with one or more cautionary accidentals at the end of the preceding line.  (We used to add 'cancelling naturals' when moving from, say 2 sharps to 3 flats, but modern practice only uses them when moving to NO sharps or flats.)

But there's the 'Real Book' style that omits key signatures (and even clefs) after the first line.  Not too annoying in a simple lead sheet, but problematic when it crept into the orchestra books for Broadway shows, with their frequent key changes!

(Some people consider this a 'professional' style.  They are mistaken.)
I don't think you'll be in any doubt which system is being used after trying the piece both ways - with and without the implied key signature!
Comment: If the music has key sig changes it is really annoying if the key sig is not printed on every line. It would be even worse if the music also have clef changes and the clef is not printed on every line. OK, the latter doesn't happen in the real book. Anyway, I agree that lack of key sig on every line has nothing to with "professional" style. So I would say to anyone who writes music: Please always include the key sig on every line.
Comment: Interesting; do you have a reference describing the "modern practice"? Lilypond still uses canceling naturals as its default.
Comment: Gould p.93.  "CONTEMPORARY PRACTICE
At a key change use only the new key signature. This gives a simpler result.
A previous key signature requires cancelling with naturals only when the
new section has no key signature:"   Plus plenty of practical observation.
Comment: @LaurencePayne: I remember reading in a book (don't remember if it was Gould or something else) that some practices are different for published music or music which would entail multiple rehearsals, versus music which is intended for a one-off performance (such as an advertising jingle).  The use of key signatures at the start of every line was considered essential for the former, but not the latter.  Does that jibe with what you read?
Comment: @supercat Music of that sort, particularly movie/TV scores, is frequently notated without key signatures _at all_, with every sharp/flat inlined, to minimize the amount that performers who are essentially sight-reading it have to keep in their heads.
Comment: @chrylis-cautiouslyoptimistic-: I would think that would depend on the intended instrument.  For some instruments, when playing in common keys, it would be much easier for someone to sight read music which uses a key signature and marks accidentals in places that would deviate from the normal hand positions or shapes associated with the key, than to try to read every sharp or flat individually.
Comment: @supercat  There's a  tradition of not using key signatures at all in music intended for sight-reading at recording sessions, particularly music for movies/tv etc..  And of never using repeats or DS/coda jumps in such music.
Comment: @LaurencePayne: When playing a e.g. harp which has seven strings per octave, having a key signature that would indicate how to set the pedals and then having accidentals on notes which don't match the key signature (which would require the operator to change the pedals before playing them and reset the pedals afterward) would seem much more convenient than trying to have the artist guess how to set pedals for whatever notes happen to be coming up.  Key signatures might not be convenient for all instruments, but on some instruments trying to sight-read each note separately as...
Comment: ...flat, natural, or sharp would be nightmare.
Comment: @supercat   Your suggestion for harp notation is ingenious, but it isn't done that way!  Harpists do use pedal diagrams sometimes.
Comment: @LaurencePayne: Harpists don't generally set their pedals based on key signature?  For complex pieces something more may be necessary, but I would think that if a piece is in D major putting a couple sharps at the start of the first staff would be a lot easier to write and read than putting oodles of sharp signs throughout a piece.
Comment: Only a very simplistic harp part would be constantly diatonic in the scale of the key signature.   But I think we're confusing two things - traditional notation plus the harp's private system of pedal diagrams and the convention in today's movie session scoring - which tends to be if not quite atonal certainly very tonally fluid - of not using key signatures at all.
Answer: The general standard is to place the key signature at the beginning of every line. However, it's very common in lead sheets to place the key signature only on the first line. In that case, the key signature does apply to the whole piece (unless explicitly changed, of course).
Answer: Quite often - usually - when something like this occurs, playing through in both options (there will only be two - with/without key sig.) will give you the answer. One will sound good, the other...
In real/fake books, it's usual to state the key sig. on the first line only, just like you'd find with the time sig., which usually, in all music, doesn't get repeated. Think about it - if the original key sig. needed changing, there'd have to be some naturals cancelling that, in order to be in the new key of C/Am.
So, only if there's a key change will there be another key sig. shown later. Assume the original one carries through the piece.
I've often wondered why the key sig. is repeated for each line, but the time sig. isn't. Another question, maybe...
Comment: @user45266 - unless - you serendipitously think 3b and play in 4#, or vice versa. Been there, done that.
Comment: Hah, good point. Let's just say if you pick the wrong key signature, it'll often be quite clear that something's not quite right...

Key Signature Only On First Line


Store the checked checkbox value and it's name in a two dimensional array

Question: I want to store the checked checkbox value and it's name in a two dimensional array,
here is html code.

Select your favorite sports:

    <input type="checkbox" value="football" name="football"> Football

    <input type="checkbox" value="baseball" name="baseball"> Baseball

And I can only display the checked checbox values, here is jQuery code
$(document).ready(function () {
    $("button").click(function () {
        var favorite = [];
        $.each($("input:checked"), function () {
            favorite.push($(this).val());
        });
        alert("My favourite sports are: " + favorite);
    });
});

My question is how to store both values and It's name in favorite array?
Answer: You can use Array of objects for this:
favorite.push({
   name: $(this).attr('name'),
   value:$(this).val()
});

See it in action
Output:
[{
    "name": "football",
    "value": "football"
}, {
    "name": "baseball",
    "value": "baseball"
}]

If you want to display values:
$.each(favorite, function(index, obj){
   console.log("Name= "+ obj.name+"  Value="+ obj.value);
})

Comment: It returns object, how can i assign name and value to variable?
Comment: It doesn't return `Object` it will return `Array` of objects. You can easily assign value in it.
Comment: Can you please more clarify , how will i assign to variable, I have no idea about it, thanks!
Comment: Tell me what value you wants to assign to `favorite`?
Comment: I want to display like this,
output: checkbox name ="here the checkbox name" and Its value is = "here It's value"
Answer: use map().Translate all items in an array or object
var favorite= $("input:checked").map(function () {
    var obj = {};
    obj[$(this).attr('name')] = this.value;
    return obj;

}).get();

console.log(favorite)

DEMO
Answer: Use array of objects
$(document).ready(function () {
    $("button").click(function () {
        var favorite = [];
        $.each($("input:checked"), function () {

            // Add object in array
            favorite.push({
                name: $(this).attr('name'),
                value: $(this).val()
            });
        });
        console.log("My favourite sports are: ");
        console.log(favorite);
    });
});

Comment: How will i assign to variable these name and value?
Comment: `window[$(this).attr('name')] = $(this).val()`


How to include multiple entities with one many-to-many in between

Question: I have 3 tier entities. T <-> TI -> E also TI <- R (where <-> is m..n and -> 1..m)
I need to select a single T with the TI, E and R
without E it works:
var t = dbContext.T
    .Include(i => i.TIs)
    .ThenInclude(i => i.I)
    .ThenInclude(i => i.R)
    .Single(i => i.Id == id);

is it possible to include E without resorting to a for loop?
EDIT thanks to both answers from Canolyb and EspressoBins, although not exactly working, but pushed me to the right track. So the working code is:
var t = dbContext.T
    .Include(i => i.TIs)
    .ThenInclude(i => i.I)
    .ThenInclude(i => i.R)

    .Include(i => i.TIs)
    .ThenInclude(i => i.I.Es)

    .Single(i => i.Id == id);

Comment: You have to show  how T and E  are related at least
Answer: I had to look at some old code of mine with a similar problem to solve, and forgive me if my relationship directions aren't exact to yours, but does this help you get any closer?
Without using the .ThenInclude()
            var result = dbContext.T
                .Include(t => t.TI)
                .Include(t => t.TI.E)
                .Include(t => t.TI.R)
                .Where(t => t.Id == id)
                .Single();

Comment: thank you. it did help. but i feel @Canolyb1 answer is a bit closer so i had to mark his answer (see my edit)
Answer: I'm not sure if this is what you're looking for, but to the best of my knowlesge includes can be cascaded like this if you need two ThenIncludes on the same relation.
var t = dbContext.T
  .Include(i => i.TIs)
  .ThenInclude(i => i.I)
  .Include(i => i.TIs)
  .ThenInclude(i => i.R)
  .Single(i => i.Id == id);

If this is not what you're looking for, it would benefit to see your Entity relations / fluent confiugation.


Why t-test of correlation coefficient can't be used for testing non-zero?

Question: t-test of a correlation coefficient is used for testing the sample correlation against population correlation of zero. To test an assumed value of the population coefficient other than zero, we should use z-test for a correlation coefficient.
Question:

What makes the tests different such that the t-test can only test for zero? Isn't the z-test a special case of the t-test (infinite degree of freedom)?
Since the t-test can't be used for tested for non-zero correlation. Why can't we always use the z-test? What's the point of the t-test?

EDITED for reference:
100 Statistical Tests by Gopal K.Janji
Comment: I have not heard this before, do you have a source? (I may just be ignorant!)
Comment: These might be helpful: https://en.wikipedia.org/wiki/Pearson_correlation_coefficient#Testing_using_Student.27s_t-distribution and https://en.wikipedia.org/wiki/Pearson_correlation_coefficient#Using_the_Fisher_transformation . I am assuming the latter has been done in _Test 13_ your text is referring to?
Comment: Possible duplicate of [When is Fisher's z-transform appropriate?](https://stats.stackexchange.com/questions/62824/when-is-fishers-z-transform-appropriate)
Comment: @GeoMatt22 I added a reference, please look at Limitations.
Answer: Short answer: You don't use a t-test of the depicted form when $\rho\neq 0$ simply because the statistic $\frac{r\sqrt{n-2}}{\sqrt{1-r^2}}$ has a $t_{n-2}$ distribution when $\rho= 0$ (and the other assumptions hold) and it doesn't have a $t_{n-2}$ distribution otherwise.
There's several different z-tests for a correlation coefficient (whether $\rho$ is $0$ or not), but they're approximate, large sample tests. Some approximations are better than others. It may be that you can also make a good t approximation, but I don't recall seeing a derivation of any that would give you a suitable $\nu$.


Intervalo de resultado

Question: Tenho uma tabela onde os registros são salvos a cada 3 segundos 24 horas por dia
Table: myTable
dado1       dado2       dado3          data
"135,05"    "134,69"    "135,10"    "2018-11-13 15:38:16"
"132,00"    "131,91"    "132,61"    "2018-11-13 15:38:24"
"130,63"    "130,57"    "131,21"    "2018-11-13 15:38:33"
"129,96"    "129,92"    "130,88"    "2018-11-13 15:38:42"
"129,69"    "129,55"    "130,77"    "2018-11-13 15:38:50"
"129,57"    "129,38"    "130,47"    "2018-11-13 15:38:59"
"129,44"    "129,27"    "130,60"    "2018-11-13 15:39:07"
"129,85"    "129,72"    "130,80"    "2018-11-13 15:39:16"
"129,91"    "129,74"    "131,24"    "2018-11-13 15:39:24"
"130,17"    "129,83"    "131,05"    "2018-11-13 15:39:33"
"130,36"    "130,00"    "131,21"    "2018-11-13 15:39:42"
"130,30"    "129,97"    "131,14"    "2018-11-13 15:39:50"
"130,47"    "130,00"    "131,25"    "2018-11-13 15:39:59"
"130,50"    "130,02"    "131,21"    "2018-11-13 15:40:07"

Gostaria de trazer entre esses resultados o tempo de 5 em 5 minutos
Por exemplo
"130,47"    "130,00"    "131,25"    "2018-11-13 15:35:59"
"130,50"    "130,02"    "131,21"    "2018-11-13 15:40:07"

A data está a cada 5 minutos
Tentei fazer assim:
SELECT    dado1
         ,dado2
         ,dado3
         ,data
     FROM myTable
    WHERE data BETWEEN DATE_SUB(DATE(NOW()), INTERVAL DAYOFMONTH(DATE(NOW()))-1 DAY) and last_day(DATE(NOW()))
    AND  medidor = '62'
GROUP BY MINUTE(data)
HAVING
    COUNT(data) <= 5
ORDER BY id

Mas não vem nada.
[EDIT]
Já consegui fazer isso aqui:
SELECT    SUBSTRING_INDEX(GROUP_CONCAT(dado1), ',', 1) dado1
                ,SUBSTRING_INDEX(GROUP_CONCAT(dado2), ',', 1) dado2
                ,SUBSTRING_INDEX(GROUP_CONCAT(dado3), ',', 1) dado3
             ,DATE_FORMAT(data,'%Y-%m-%d %H:%i') dia
         FROM myTable
    WHERE data BETWEEN DATE_SUB(DATE(NOW()), INTERVAL DAYOFMONTH(DATE(NOW()))-1 DAY) and last_day(DATE(NOW()))
     AND  medidor = '62'
    GROUP BY DATE_FORMAT(data,'%Y-%m-%d %H:%i')
    ORDER BY id

Que traz os seguintes dados
"135.05"    "134.69"    "135.10"    "2018-11-13 15:38"
"130.47"    "130.00"    "131.25"    "2018-11-13 15:39"
"130.17"    "129.83"    "131.05"    "2018-11-13 15:40"
"129.64"    "129.57"    "130.77"    "2018-11-13 15:41"
"129.17"    "129.08"    "130.19"    "2018-11-13 15:42"
"129.61"    "129.36"    "130.55"    "2018-11-13 15:43"
"129.28"    "129.22"    "130.53"    "2018-11-13 15:44"
"129.71"    "129.64"    "130.69"    "2018-11-13 15:45"
"129.83"    "129.82"    "130.77"    "2018-11-13 15:46"
"130.22"    "130.03"    "131.24"    "2018-11-13 15:47"
"128.88"    "128.83"    "129.92"    "2018-11-13 15:48"
"128.75"    "128.75"    "129.92"    "2018-11-13 15:49"
"128.41"    "128.38"    "129.63"    "2018-11-13 15:50"
"129.32"    "129.22"    "130.25"    "2018-11-13 15:51"

Ou seja, os dados das linhas agrupados por minuto.
Agora falta trazer de 5 em 5 minutos
Comment: O que exatamente você quer dizer com `Agora falta trazer de 5 em 5 minutos` ? Uma função que a cada 5 minutos faz este select ou um "agrupamento" de 5 em 5 minutos ? Tentou utilizar algo como `DATE_ADD(sua_data, INTERVAL 5 minute)` ?
Comment: No exemplo que eu coloquei o primeiro tempo é: `2018-11-13 15:35:59` e o segundo é `2018-11-13 15:40:07` percebeu? o equivalente a 5 minutos depois
Comment: Quando você diz "de 5 em 5 minutos" quer dizer que o início do intervalo deve ser o instante no qual os minutos sejam múltiplos de 5? Note que em seu exemplo a diferença entre as datas não chega a 5 minutos completos, é 00:04:08.
Comment: Você tem registro de 3 em 3 seg. Mas quer pegar de 5 em 5 min a partir de uma data definida? É isso?
Comment: Criei a estrutura de exemplo no site http://www.sqlfiddle.com/#!9/826e65/1
Comment: Não me parece uma situação para utilização do banco de dados para extração destas informações. Pois existem regras de negócio envolvidas. Então, em seu lugar, eu faria um loop utilizando a sua linguagem de programação e extrairia somente os dados necessários.
Answer: Uma forma seria usar uma variável:
SET @data := (SELECT data FROM tab1 ORDER BY data LIMIT 1);

SELECT * FROM tab1
WHERE data IN (
SELECT
 (CASE WHEN data >= (SELECT data FROM tab1 WHERE data >= ADDTIME(@data, "00:05:00") LIMIT 1)
  THEN @data := data
  ELSE @data
 END) AS data_5
FROM tab1 A
ORDER BY data)

Eu setei a variável com o primeiro registro da tabela, mas você pode fazer a partir de uma data específica também:
SET @data := (SELECT data FROM tab1 WHERE data > '2018-11-13 15:45' ORDER BY data LIMIT 1);

O que fiz na "query interna", foi tratar a variável com o CASE e sempre que  data for maior ou igual a "variável + 5min" (ADDTIME(@data, "00:05:00")), ela atualiza a variável e trás a data, caso não, ela mantém e trás a data já setada.
Depois só fiz um select trazendo essas datas a comparando.
Poderia usar um GROUP BY também.

db-fiddle
Answer: Uma forma simples de resolver esse problema seria GROUP BY CAST( DATE_FORMAT(data,'%Y%m%d%H%i') / 5 AS UNSIGNED )
Answer: Não sei se eu entendi bem o problema, mas segundo entendi quer de 5 em 5 minutos, sem interessar onde começa o intervalo de 5 minutos, então pode fazer assim:
SELECT * FROM tab1
WHERE MOD( MINUTE( data ), 5 ) = 0  -- se o minuto for múltiplo de 5
AND data > '2018-11-13 15:40:07'    -- Se quiser maior que uma data especifica.

Veja a funcionar no db-fiddle

Intervalo de resultado


How do I make a WiX 3.5 installer with a completely self-contained .NET 4.0 installer?

Question: Continuing a previous question I asked here, I now need to move to vs2010.
I've gotten the most recent weekly build of WiX 3.5, the June 5th 2010 version.
Here's the relevant lines from my installer:
      <ItemGroup>
        <BootstrapperFile Include="Microsoft.Net.Framework.4.0">
          <ProductName>.NET Framework 4.0</ProductName>
        </BootstrapperFile>
        <BootstrapperFile Include="Microsoft.Windows.Installer.4.5">
         <ProductName>Windows Installer 4.5</ProductName>
       </BootstrapperFile>
      </ItemGroup>

and
<GenerateBootstrapper ApplicationFile="MySetup.msi" ApplicationName="MyProgram" BootstrapperItems="@(BootstrapperFile)" Path="C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bootstrapper\" ComponentsLocation="Relative" OutputPath="$(OutputPath)" Culture="en" />

However, it's just not working.  In vs2010, there are exclamation points next to the .NET Framework 4.0 and Windows Installer 4.5 files, and the properties page lists them as 'Unknown BuildAction BootstrapperFile', and the build just does not appear to install .NET 4.0 at all.  The relevant warning is:
C:\source\depot\project\vs2010\WiXSetup\WiXSetup.wixproj(68,5): warning MSB3155: Item 'Microsoft.Net.Framework.4.0' could not be located in 'C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bootstrapper\'.

Answer: The short answer is to change

<ItemGroup>
    <BootstrapperFile Include="Microsoft.Net.Framework.3.5.SP1" >
       <ProductName>.NET Framework 3.5 SP1</ProductName>
    </BootstrapperFile>
    <BootstrapperFile Include="Microsoft.Windows.Installer.3.1" >
       <ProductName>Windows Installer 3.1</ProductName>
    </BootstrapperFile>
</ItemGroup>

<Target Name="setup">
    <GenerateBootstrapper
        ApplicationFile="myproduct.msi"
        ApplicationName="myproduct"
        BootstrapperItems="@(BootstrapperFile)"
        Path="C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bootstrapper\"
        ComponentsLocation="Relative"
        OutputPath="$(cddir)"
        Culture="en"/>
</Target>

to

<ItemGroup>
    <BootstrapperFile Include=".NETFramework,Version=v4.0" >
       <ProductName>.NET Framework 4.0</ProductName>
    </BootstrapperFile>
    <BootstrapperFile Include="Microsoft.Windows.Installer.3.1" >
       <ProductName>Windows Installer 3.1</ProductName>
    </BootstrapperFile>
</ItemGroup>

<Target Name="setup">
    <GenerateBootstrapper
        ApplicationFile="myproduct.msi"
        ApplicationName="myproduct"
        BootstrapperItems="@(BootstrapperFile)"
        Path="C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bootstrapper\"
        ComponentsLocation="Relative"
        OutputPath="$(cddir)"
        Culture="en"/>
</Target>

I figured this out by going into the SDK bootstrapper directory (C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bootstrapper) on my machine, for Visual Studios 2010.  Under there is a list of projects that can be read by Wix and included for bootstrapping.  In each folder there is a file called Product.xml.  After looking at the help here for creating a .NET 3.5 installer  I found that the ProductCode attribute in the Product tag appears to identify the name of the boostrap element, so when I changed the value to that referenced in C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages\DotNetFX40\Product.xml it worked.
Comment: This got it, thanks.  I'm glad they decided to change the structure of their commands, that was very helpful and necessary.
Comment: I was also having this problem in VS2010, and this solution worked perfectly (thank you!), except for the cosmetic issue that the exclamation point still persists next to the bootstrapped packages. Nevertheless, the installer builds completely with bootstrapped packages, and installs as expected. If anyone knows what causes the exclamation point, and how to get rid of it, please add that here. Thanks!


Efeitos gráficos na Validação Javascript

Question: Qual este efeito/bibliotecaJS de validação onde a validação é realizada a cada preenchimento de campo e retornado as inconsistencias imediatamente e exibe informações flutuantes como este usado pelo cadastro do google.
Exemplos
Answer: Para as validações destacadas na caixa verde eu sugiro que você use o JQuery validation (olhe os demos em http://jqueryvalidation.org/files/demo/) ou bootstrap http://getbootstrap.com/
Para o tooltip da marcação em vermelho sugiro dois componentes, escolha o que achar melhor:

Bootstrap (esse é o melhor): http://getbootstrap.com/. Dê uma olhada em todos os componentes e verá que tem muita coisa boa que você poderá utilizar na sua app. mas veja esses para fazer o efeito da caixa em vermelho http://getbootstrap.com/css/#forms-control-validation, http://getbootstrap.com/javascript/#popovers, http://getbootstrap.com/components/#input-groups-basic e http://getbootstrap.com/javascript/#tooltips
JQuery UI http://jqueryui.com/tooltip/ , não é exatamente igual mas funciona e vem com vários componentes que você poderá utilizar sem ter que ficar colocando um monte de bibliotecas separadas na sua aplicação.

Obs.: O bootstrap é muito bom mas os arquivos css dele podem mudar o visual do seu site se ele já estiver pronto. Use apenas em novas aplicações.
Comment: Olá @Marco Antonio Quintal, Obrigado era o que procurava.


How to set transaction timeout on Jetty JNDI Atomikos configuration

Question: I am in the process of converting various Spring beans to JNDI lookups.  Currently I am using Jetty to test this.  I have configured the UserTransaction according to the Jetty documentation and it works:
<New id="tx" class="org.mortbay.jetty.plus.naming.Transaction">
    <Arg>
        <New class="com.atomikos.icatch.jta.UserTransactionImp">
        </New>
    </Arg>
</New>

The problem with this configuration it that it does not set the transaction timeout like my Spring config did:
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp">

    <property name="transactionTimeout" value="30" />
</bean>

I tried the following, but it didn't work...for some reason I ended up with TWO user transactions:
<New id="tx" class="org.mortbay.jetty.plus.naming.Transaction">
    <Arg>
        <New class="com.atomikos.icatch.jta.UserTransactionImp">
            <Set name="transactionTimeout">30</Set>
        </New>
    </Arg>
</New>

Any ideas?
Answer: You'll need to configure the atomikos transaction manager through the jta.properties file within your jetty context.
For example, look at the following directory within your Jetty distribution (I'm using 6.1.24):

/jetty-6.1.24/contexts/test-jndi.d/WEB-INF/classes

jta.properties

set the property called com.atomikos.icatch.max_timeout, which is commented out in the default sample file.
Then make sure that you start your jetty container using the correctly configured context.
Comment: Thanks for the answer.  Do you have any idea if this could be done without the `jta.properties` file?
Comment: I imagine it might be possible, but you'd have to set the values in the transaction manager as part of the server startup process.
Comment: Yes it is possible without the jta.properties. You can pass parameters to com.atomikos.icatch.config.UserTransactionServiceImp.UserTransactionServiceImp class. If you use spring you can do it there or you can do it programmatically.


How to install drush properly

Question: I am trying to install drush on my new computer and it's a mess
I'm on Mac Os High Sierra, with Mamp 5.3, PHP 7.2.14
I'm mainly interested in Drupal 7
On my previous computer, it was simple i just had to be on the htdocs folder and type : drush dl to download the latest Drupal 7 release
Now i had to install composer (v1.8.4) and then installed drush  using this command : composer require drush/drush:dev-master
I ended up with this version of drush (v9.7.0-dev)
When i type drush dl i get this message :
dl has been deprecated. Please build your site using Composer. Add new projects with composer require drupal/[project-name]. Use https://www.drupal.org/project/composer_generate to build a composer.json which represents the enabled modules on your site.

I'm no advanced user (obviously), i just need drush to have persmission to execute basic commands to install a new drupal 7, install, enable, disable modules..
Here's the result of $PATH
Mac:htdocs Mac$ $PATH
-bash: /Users/Mac/.composer/vendor/bin:/Applications/MAMP/bin/php/php7.2.14/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin: No such file or directory

Thanks
Answer: If you read the Drupal compatibility table in the docs, you'll see that the correct version for Drupal 7 is Drush 8. The installation instructions for Drush 8 are simple and clear, no Composer required - just download a phar file.
PS! If you are planning on maintaining Drupal 8 sites (with Drush 9) too, I recommend getting Drush Launcher.
Comment: I was reading this documentation page : https://docs.drush.org/en/master/install/ .
Yours seem to be the appropriate one, thanks. Can i leave the drush 9.7.0-dev or should i uninstall it ? (if so, how ?)
Comment: You should uninstall it. You can just replace it with the current version by running `composer require drush/drush`. This will install the current version of Drush. But note that with drupal 8, you cannot download modules with Drush anymore, you need to use Composer to download modules now.
Comment: The poster is asking specifically about Drupal 7 ... Regarding uninstalling the Drush (that was installed using Composer) - read https://drupal.stackexchange.com/questions/135599/how-to-uninstall-drush-via-composer NB! If/when you are using Drupal 8, you should install Drush site-local, not globally. So no matter what you do, just remove the global Drush.

How to install drush properly


Sign in with Paypal API: get basic user info

Question: I am using JavaScript to login with PayPal.
My JavaScript code is as follows and seems to work fine.

However, I am struggling with the next step. Using either JavaScript or classic ASP, I am trying to obtain the following data about the signed in user:

Email address
First name
Family name
unique id (optional)
Address (optional)
Telephone number

I have done this with Facebook, Google & LinkedIn, using examples available on the respective sites. However, with Paypal, I cannot find any useful examples of how to do this...
Answer: I manage to achieve that with the next code. It never worked for me the way paypal does it. So I do everything on one code instead of jumping.
testingPaypalIdentity.php is the url callback that i put as 'return url' and is the same that you must put on your paypal app.
Basically the code checks if there's a code wich is user permission, if there's one then creates the tokens, if there's a refresh token then it search for user info and print it.
require __DIR__ . '/bootstrap.php';

use PayPal\Api\OpenIdSession;
use PayPal\Api\OpenIdTokeninfo;
use PayPal\Exception\PayPalConnectionException;
use PayPal\Api\OpenIdUserinfo;
$baseUrl = getBaseUrl() . '/testingPaypalIdentity.php?success=true';
$tmp;
//Get Authorization URL returns the redirect URL that could be used to get             user's consent
$redirectUrl = OpenIdSession::getAuthorizationUrl(
$baseUrl,
array('openid', 'profile', 'address', 'email', 'phone',
    'https://uri.paypal.com/services/paypalattributes',
    'https://uri.paypal.com/services/expresscheckout',
    'https://uri.paypal.com/services/invoicing'),
    null,
    null,
    null,
    $apiContext
);
$refreshToken='';
if (isset($_GET['code']) && $_GET['code'] != '') {

    $code = $_GET['code'];

    try {
        $accessToken = OpenIdTokeninfo::createFromAuthorizationCode(array('code' => $code), null, null, $apiContext);
    } catch (PayPalConnectionException $ex) {
        echo $_GET['code']." ".$ex;
        //ResultPrinter::printError("Obtained Access Token", "Access Token", null, $_GET['code'], $ex);
        exit(1);
    }
    $refreshToken=$accessToken->getRefreshToken();
    print_r($accessToken);
    //ResultPrinter::printResult("Obtained Access Token", "Access Token",     $accessToken->getAccessToken(), $_GET['code'], $accessToken);
}
if($refreshToken!='') {
    try {
        $tokenInfo = new OpenIdTokeninfo();
        $tokenInfo = $tokenInfo->createFromRefreshToken(array('refresh_token' => $refreshToken), $apiContext);
        $params = array('access_token' => $tokenInfo->getAccessToken());
        $userInfo = OpenIdUserinfo::getUserinfo($params, $apiContext);
    } catch (Exception $ex) {
        // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
        echo $ex;
        exit(1);
    }
    $tmp=$userInfo;
    print_r($userInfo);
}

And check OpenIdUserinfo class to obtain the info needed, for example:
$email = $userInfo.getEmail();

Sorry for bad english, and if you required further information, please ask.
Greetings