Can a nowhere continuous function have a connected graph?

Question: After noticing that function $f: \mathbb R\rightarrow \mathbb R $ $$ f(x) = \left\{\begin{array}{l} \sin\frac{1}{x} & \text{for }x\neq 0 \\ 0 &\text{for }x=0 \end{array}\right. $$
has a graph that is a connected set, despite the function not being continuous at $x=0$, I started wondering, doest there exist a function $f: X\rightarrow Y$ that is nowhere continuous, but still has a connected graph?
I would like to consider three cases

$X$ and $Y$ being general topological spaces
$X$ and $Y$ being Hausdorff spaces
ADDED: $X=Y=\mathbb R$

But if you have answer for other, more specific cases, they may be interesting too.
Comment: I wonder whether the [Conway base 13 function](https://en.wikipedia.org/wiki/Conway_base_13_function) has a connected graph.
Comment: As Henning points out via example, this is most interesting when $X = \Bbb{R}$ (and possibly where $Y = \Bbb{R}$ too).
Comment: @NateEldredge: It turns out that [the graph of the base-13 function is totally disconnected](https://math.stackexchange.com/a/3276016/14366).
Comment: By transfinite induction one can construct a function $f:\mathbb R\to\mathbb R$ whose graph meets every Borel set in the plane whose projection onto the horizontal axis is uncountable. Can such a graph be disconnected?
Comment: @TheoBendit Indeed now I see that case $X=Y=\mathbb R$ is significantly more interesitng. I'll add it as another point.
Comment: @bof: That sounds very promising. This will also make the graph dense in $\mathbb R^2$ (since each open ball is Borel). Then, if the graph is disconnected it will be covered by two disjoint open subsets of $\mathbb R^2$, and the complement of their union is nonempty and closed, hence Borel ... all we now need to argue is that its projection is fat enough.
Answer: Here is an example for $\mathbb R^2 \to \mathbb R$:
$$f(x,y) = \begin{cases} y & \text{when }x=0\text{ or }x=1 \\
x & \text{when }x\in(0,1)\text{ and }y=0 \\
1-x &\text{when }x\in(0,1)\text{ and } y=x(1-x) \\
x(1-x) & \text{when }x\notin\{0,1\}\text{ and } y/x(1-x) \notin\mathbb  Q \\
0 & \text{otherwise} \end{cases} $$
This is easily seen to be everywhere discontinuous. But its graph is path-connected.

A similar but simpler construction, also $\mathbb R^2\to\mathbb R$:
$$ \begin{align} g(1 + r\cos\theta, r\sin\theta) = r & \quad\text{for }r>0,\; \theta\in\mathbb Q\cap[0,\pi] \\
g(r\cos\theta, r\sin\theta) =r & \quad \text{for }r>0,\; \theta\in\mathbb Q\cap[\pi,2\pi] \\
g(x,y)  =0 & \quad\text{everywhere else} \end{align} $$
Comment: Very nice examples. They show how easy is to break some continuity with additional dimensions while retaining enough of it to maintain connectedness of the graph. So I've added another case to the question, $f: \mathbb R \rightarrow \mathbb R$, in which such methods won't work. Do you think a function in this case is possible, like the one that John Hughes is constructing?
Comment: I would rewrite it, the standard interpretation would be the opposite.
Comment: @AdamLatosiński: I am unsure, and getting nowhere myself. I've been trying to figure out whether the graph of the Conway base-13 function is connected, but without success either way.
Comment: Does $y/x(1 - x)$ mean $\frac{y}{x(1 - x)}$ or $\frac{y}{x}(1 - x)$?
Comment: @Bladewood: The former.
Answer: Check out this paper:
F. B. Jones, Totally discontinuous linear functions whose graphs are connected, November 23, (1940).
Abstract:

Cauchy discovered before 1821 that a function satisfying the equation
  $$
f(x)+f(y)=f(x+y)
$$
  is either continuous or totally discontinuous. After Hamel showed the existence of a discontinuous function, many mathematicians have concerned themselves with problems arising from the study of such functions. However, the following question seems to have gone unanswered: Since the plane image of such a function (the graph of $y =f(x)$) must either be connected or be
  totally disconnected, must the function be continuous if its image is connected? The answer is no.

In particular, Theorem 5 presents a nowhere continuous function $f:\Bbb R \rightarrow \Bbb R$ whose graph is connected.

 Whether Conway base 13 function is such an example remains unknown. (at least on MSE; see Is the graph of the Conway base 13 function connected?)  It turns out the graph of Conway base 13 function is totally disconnected. See this brilliant answer.
Answer: There is a simple general strategy for many questions of this type, which is to just try to build a counterexample by transfinite induction.  Let's first think about what it means for the graph $G$ of a function $f:\mathbb{R}\to\mathbb{R}$ to be disconnected.  It means there are open sets $U,V\subset\mathbb{R}^2$ such that $U\cap G$ and $V\cap G$ are both nonempty and together they form a partition of $G$ (we will say $(U,V)$ separates $G$ in that case).  So, to make $G$ connected, we just have to one-by-one rule out every such pair $(U,V)$ from separating it.
So, then, here is the construction.  Fix an enumeration $(U_\alpha,V_\alpha)_{\alpha<\mathfrak{c}}$ of all pairs of open subsets of $\mathbb{R}^2$.  By a transfinite recursion of length $\mathfrak{c}$ we define values of a function $f:\mathbb{R}\to\mathbb{R}$.  At the $\alpha$th step, we add a new value of $f$ to prevent $(U_\alpha,V_\alpha)$ from separating the graph of $f$, if necessary.  How do we do that?  Well, if possible, we define a new value of $f$ such that the corresponding point in the graph $G$ will either be in $U_\alpha\cap V_\alpha$ or not be in $U_\alpha\cup V_\alpha$, so $U_\alpha\cap G$ and $V_\alpha\cap G$ will not partition $G$.
If this is not possible, then $U_\alpha$ and $V_\alpha$ must partition $A\times\mathbb{R}$ where $A\subseteq\mathbb{R}$ is the set of points where we have not yet defined $f$.  Since $\mathbb{R}$ is connected, this means we can partition $A$ into sets $B$ and $C$ (both open in $A$) such that $U_\alpha\cap (A\times\mathbb{R})=B\times\mathbb{R}$ and $V_\alpha\cap (A\times\mathbb{R})=C\times\mathbb{R}$.  Now since we have defined fewer than $\mathfrak{c}$ values of $f$ so far in this construction, $|\mathbb{R}\setminus A|<\mathfrak{c}$ and in particular $A$ is dense in $\mathbb{R}$.  If $B$ were empty, then $U_\alpha$ would have empty interior and thus would be empty, and so $(U_\alpha,V_\alpha)$ can never separate the graph of $f$.  A similar conclusion holds if $C$ is empty, so let us assume both $B$ and $C$ are nonempty.  It follows that $\overline{B}$ and $\overline{C}$ cannot be disjoint (otherwise they would be a nontrivial partition of $\mathbb{R}$ into closed subsets), so there is a point $x\in\mathbb{R}\setminus A$ that is an accumulation point of both $B$ and $C$.  Since $x\not\in A$, we have already defined $f(x)$.  Note now that $(x,f(x))\not\in U_\alpha$, since $U_\alpha$ would then contain an open ball around $(x,f(x))$ and thus would intersect $C\times\mathbb{R}$.  Similarly, $(x,f(x))\not\in V_\alpha$.  Thus $U_\alpha$ and $V_\alpha$ already do not contain the entire graph of $f$, and so we do not need to do anything to prevent them from separating it.
At the end of this construction we will have a partial function $\mathbb{R}\to\mathbb{R}$ such that by construction, its graph is not separated by any pair of open subsets of $\mathbb{R}^2$, and the same is guaranteed to hold for any extension of our function.  Extending to a total function, we get a total function $f:\mathbb{R}\to\mathbb{R}$ whose graph is connected.  But we can of course arrange in this construction for $f$ to be nowhere continuous; for instance, we could start out by defining $f$ on all the rationals so that the image of every open interval is dense in $\mathbb{R}$.  In fact, the construction shows that any partial function $\mathbb{R}\to\mathbb{R}$ defined on a set of cardinality less than $\mathfrak{c}$ can be extended to a total function whose graph is connected.  (Or even stronger, you could start with any partial function whose domain omits $\mathfrak{c}$ points from every interval, since that is all you need to guarantee that the set $A$ is dense at each step.)
Comment: @HagenvonEitzen: There's not actually a need to do anything additional to make the function nowhere continuous. The construction directly implies that that _every Jordan curve_ in the plane will intersect the graph, which includes even very small circles anywhere in the plane. So the graph naturally becomes dense in $\mathbb R^2$.
Comment: @EricWofsey: But whenever you have a Jordan curve, then the set of points inside and outside the curve form a possible pair of open $U_\alpha$ and $V_\alpha$ for your construction. There's no point in $U_\alpha\cap V_\alpha$ one can add to the graph, so your construction will add a point _outside_ $U_\alpha\cup V_\alpha$ to the graph instead instead. But $\mathbb R^2\setminus(U_\alpha\cup V_\alpha)$ are exactly the points on the Jordan curve.
Comment: Even simpler, for every nonempty open $S\subseteq \mathbb R^2$ and $s\in S$, there will be an $\alpha$ such that $(U_\alpha,V_\alpha)=(\mathbb R^2\setminus\{s\},S)$. Then the construction must add a point from $U_\alpha\cap V_\alpha \subseteq S$ to $G$. Since $S$ was arbitrary open, this means that $G$ becomes dense.
Comment: Stronger yet, the construction ensures that $f$ is "strongly Darboux" -- i.e., $f([a,b])=\mathbb R$ for every $a<b$. For every $y$ we can show that $G$ intersects $[a,b]\times\{y\}$: WLOG $f(a)\ne y$ and $f(b)\ne y$; now extend $[a,b]\times\{y\}$ with a ray that goes straight upwards or downwards from $(a,y)$ such as to avoid $(a,f(x))$, and a ray that goes straight up or down from $(b,y)$ and avoids $(b,f(b))$. The resulting curve divides $\mathbb R^2$ into two nontrivial open regions, so just like the Jordan curve it intersects $G$. But the vertical parts _don't_, by construction.
Comment: Without the last sentence, you might have ended up with $f(x)=0$ ;)
Answer: Not an answer
Great question, and I don't have an answer for you, but I've got some small thoughts:
By summing up weighted and displaced copies of $f$, you can get discontinuities at many places. For instance, you could write
$$
F(x) = \sum_{n \in \Bbb Z} \frac{f(x-n)}{1+n^2}
$$
That'll have an $f$-like discontinuity at every integer.
Digression
A comment asks whether the graph is still connected. Let me show that it is at $x = 1$ as an example, which should be reasonably compelling for other integer points. (For non-integer points, $F$ is continuous, so we're fine).
Write
\begin{align}
F(x) &= \frac{1}{2} f(x-1) + \sum_{n\ne 1 \in \Bbb Z} \frac{f(x-n)}{1+n^2}\\
 &= \frac{1}{2} f(x-1) + G_1(x)
\end{align}
where $G_1$ is a function that's continuous at $x = 1$.
Let's look at the graph of $F$ near $1$, say on the interval $(3/4, 5/4)$. It's exactly
$$
K = \{ (x, \frac{1}{2} f(x-1) + G_1(x)) \mid 3/4 < x < 5/4 \}
$$
Contrast this with the graph of $f$ near $0$, which is
$$
H = \{ (x, f(x)) \mid -1/4 < x < 1/4 \}
$$
and which we know (from standard calculus books like Spivak) to be connected.
Now look at the function
$$
S : K \to H : (x, y) \mapsto (x-1, y - G_1(x))
$$
This is clearly continuous and a bijection (and even extends to a bijection from a (vertical) neighborhood of $K$ to a neighborhood of $H$), so $K$ is also connected.
End of digression
And then for numbers with finite base-2-expansions, you can do the same sort of thing: let
$$
G(x) = \sum_{k \in \Bbb Z, k > 0} \frac{1}{2^k} F(2^k x)
$$
and that'll have $f$-like discontinuities at all the points with finite base-2 representations, which is a dense set in $\Bbb R$.
But I have a feeling that sliding over to the uncountable-set territory is going to be a lot harder.
Comment: @AdamChalumeau: See "Digression" in which I prove that the graph of $F$ is nice. For $G$, it's presumably tougher..
Comment: This is a good way to get functions which are discontinuous at many points, but are the graph of $F$ and and the graph of $G$ still connected?
Comment: Well...they could only be disconnected at their points of discontinuity. And (for $F$ at least) at those points the graph is (roughly) the sum of something linear (the derivative approximation) and the graph of $f$; applying a shearing operation gets rid of the linear part, and you've got something a lot like the graph of $f$. I'll add details.


Como deixar um CRUD persistente?

Question: Fiz um CRUD simples, e queria deixar os dados dele salvo, para quando abrir o Netbeans está todas as informações salvas.
Comment: Você pode explicar melhor? Está difícil entender só com o que você já disse.
Answer: Você precisará de um banco de dados para salvar as informações. Se for uma aplicação robusta, eu recomendo o postgresql com a administração do pgAdmin junto com o pgModeler para fazer os relacionamentos visualmente. Agora se você preferir pode utilizar uma base de dados muito veloz, recomendo o MySQL utilizando o Workbench.
Aconselho a utilizar como API a JPA, que é uma convenção de como você deve implementar seus providers. Neste caso eu recomendo o Hibernate.
Não tenha pressa para aprender, aprenda os conceitos de forma sólida. Eu atualmente estou estudando tudo isso também.
Comment: Não é estritamente necessário usar um banco de dados. As informações podem ser persistidas em um arquivo no filesystem, por exemplo.

Como deixar um CRUD persistente?


Show that every maximal solution to $x'=G(x)$ is defined in an interval $(a,\infty)$

Question: There is a function $G:\mathbb{R}^d\to\mathbb{R}^d$ locally lipschitz, suppose there exists $R>0$ such that $x\cdot G(x)\leq 0 , \forall x\in \mathbb{R}^d$ with $||x||\geq R$. Show that every maximal solution to $x'=G(x)$ is defined in an interval $(a,\infty)$.
By the Picar's theorem I know there exists a solution to $x'=G(x)$ on the shape of $\gamma:(a,b)\to \mathbb{R}^d$. And $a,b$ can be infinite. I don't know how to get to the proof.
Any help is appreciated.
Comment: What book did you get this exercise from? I would like to see some more related exercises.
Answer: Hint: For the existence of the solution define $x'=f(t,x)=G(x)$, since $G$ is Lipschitz on $x$ it follows that $f$ is Lipschitz on the second variable, so the Theorem of Picard applies. This solution is maximal, on the interval $(a,\infty)$ because the norm of $x$ is decreasing for $\|x\|\geq R$. To see this, notice that $$\frac{d}{dt}\langle\, x,x\rangle = 2\langle\,x,x'\rangle = 2\langle\,x,G(x)\rangle=2x\cdot G(x)\leq 0 $$


Responsive embed bootstrap não funciona

Question: estou tentando implementar o responsive embeded do bootstrap, pois preciso colocar um vídeo (.mov) no site, porém não está funcionando.
fonte: http://getbootstrap.com/components/#responsive-embed
código:

alguém sabe o que posso estar fazendo de errado? ou caso tenha alguma dica de outro responsive embed para executar um arquivo de extensão .mov é de grande ajuda.
Answer: Acho que apenas faltou colocar "https:" antes da url.

Comment: realmente funcionou, só preciso saber como tocar o video da extensão .mov, coloquei no src mas quando entra na página faz download, caso possa me ajudar, fico no aguardo, desde já obrigado

Responsive embed bootstrap não funciona


Display Loader untill the browser loading icon is rotating

Question: I have a page which contains heavy traffic . It  is fetching data from multiple servers and showing in the page . It takes usually 3-4 minutes for the page to complete the loading . Please take a look at some of the partial page data

All i need is a spinning gif or a loader to get over the page so that user can't click any link unless the page gets loaded completely .
I have tried the following code

HTML:

Loading...

The problem is when user reloads the page the browser loader spins but the content in the page doesn't get my loader to get over the content .
It only happens until the DOM gets loaded .
All I want is to get the loader to work as soon as user clicks the reload icon or hits enter or F5 or ctrl+f5 for page reload . Hope i made myself clear.
Answer: Place your jquery code in document.ready function and make some delay on that function like following :-
Add this jquery code at bottom of page.
$(document).ready(function(){
    hideLoading = function() {
        $('.loading').fadeOut(20000, function() {
            $(".content").fadeIn(10000);
        });
    };

    setTimeout(function(){
        hideLoading();
    }, 1000);
});

May be it will help you.
Comment: `setTimeout` ? Why ?
Comment: `$(document).ready(function()` works when DOM gets loaded , i want when the use clicks reload .
Comment: you can set loader on beforeunload
Comment: you have to set display block for loader from the CSS or using inline CSS, then using jQuery you should hide that loader after page load.
Comment: please add your code at jsfiddle or anywhere else, So I can update and make changes in that...


Move cursor to the last input

Question: I have a textarea in which the user can type text. The user can also push a button to add stuff like images and links. This button namely prompts them for their link, and then inputs the correct html in the textarea where the cursor was located. A working code example is this:
jQuery('input#btn').click(function(e) {
    var link = prompt("Please paste the link", "http://");
    jQuery('textarea#id1').insertAtCaret('link text');
});

The .insertAtCaret() function is the one kindly created by Daniel Beck for another question of mine. It finds the position of the cursor in the textarea, so that the html-chunk can be added here.
But after jQuery has added this html-chunk, the cursor is no longer in the textarea, but focus is now on the button that was pushed. I would like the cursor to remain where is was before pushing this button (after the added html-chunk).
Is it possible to find the last inputted text in a textarea and is it then possible to move the curser there?
Note, this input could be anywhere in the already written text in the textarea.
Comment: What about you set an attribute to the element that already given blur method. Then you can search the element by the attribute
Comment: I can, off the top of my head, think of at least two different approaches here. First one would be to focus the same element, but move the focus point X number of characters, based on the length of whatever is inserted. This would need to be done in the actual function currently inserting the content in the textarea.
You could also try to search for whatever text you input and set the focus after the last character of that content - basically read in the content of the textarea, search for a match for what you just input, and go from there.
Answer: At first you have to put back the focus to your text area.
var te = document.getElementById('id1');
te.focus();

And second set the cursor to specific position.
var mySavedPosition = 3 // or whatever it was before
te.selectionStart = mySavedPosition;
te.selectionEnd = mySavedPosition;

Thats it.
So at your example it could look like here:
jQuery('input#btn').click(function(e) {
    var link = prompt("Please paste the link", "http://");
    var te = document.getElementById('id1');
    var pos = te.selectionStart;
    jQuery('textarea#id1').insertAtCaret('link text');
    te.selectionStart = pos;
    te.selectionEnd = pos;
});

And sorry, but I'm not a friend of jQuery, so I use just native JS.
Update
I have overlooked that you want the cursor at the end of the inserted place. Since I do not know the length of the inserted text, I best get the position from the end.
jQuery('input#btn').click(function(e) {
    var link = prompt("Please paste the link", "http://");
    var te = document.getElementById('id1');
    var pos = te.textLength - te.selectionStart;
    jQuery('textarea#id1').insertAtCaret('link text');
    te.selectionStart = te.textLength - pos;
    te.selectionEnd = te.textLength - pos;
});

Move cursor to the last input


git push difference of branch with master

Question: Assume a new local branch named debug and the master is already pushed to the origin. 99% of the debug branch is the same as the master branch.
when I use git push -u origin debug, it begins to upload the whole about 1 gig project.
Is it possible instead of uploading the whole 1gig project as a new branch, just upload the changed files and copy(or maybe clone or reuse) the rest files from the master which is already uploaded?
Comment: As long as you're using the "smart" transport protocol—and GitHub do that—this is already the case in general. There are some specific exceptions, that should be rare. Are you using a shallow clone? (This might trigger one of the exceptions.) The most likely case is that you committed the addition of a big file perhaps followed by the deletion of that same big file—in which case Git must push the big file's contents as they're required by the intermediate commit.
Comment: no shallow clone! just used the regular `git branch ` @torek
Comment: If all you did was create a new branch name pointing to an existing commit, `git push` should be very quick: your Git will call up their Git, say "I need you to have commit H" (for some hash H), and they will say "I have H, don't send it." Your Git will then say: "OK, you now have everything; please create the name `debug` pointing to commit H." They should either say "ok, done" or "I won't because ____" (fill in the blank) and the conversation should terminate at this point.
Comment: In this case, however, `debug` is **100%** the same as `master`. You said "99%". Where do you believe this other 1% comes from?
Comment: after making the debug branch, I have did debug 6 files. @torek
Answer: AFAIK there is nothing you can do. Git will send only what's is necessary to be send. So it there is a lot of data being transferred, then it means you made many changes (at least from git's perspective).
As you are talking about 1GB of data I guess there are binary files in your repository.
If that's true you may consider to use git LFS feature. That should help you in the future but won't help you now (unless you rewrite whole git history).


Extension and bound of $\int_{0}^{\infty}\int_{0}^{\infty}e^{-it_{1}}e^{-it_{2}} (s + b t_{1}t_{2})^{-g} dt_{1} dt_{2}$

Question: I have some problem which needs to be resolved
to some extent.
The problem is to find an extension and bound of
a function of the form
\[
\int_{0}^{\infty}\int_{0}^{\infty}e^{-it_{1}}e^{-it_{2}} (s + b t_{1}t_{2})^{-g} dt_{1} dt_{2}
\]
where g > 0, as $b \to e^{\pi i}$.
All I know is that this is convergent for
s, b positive.
It seems to be better to replace paths by the negative imaginary axis.
But if I do so, then the factor $(s + b t_{1}t_{2})^{-g}$
goes across the negative real axis, which for me with
undergraduate complex analysis looks like a difficulty.
Is there any way we could handle this function?
Thanks in advance.
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\mc{I} & \equiv\int_{0}^{\infty}\int_{0}^{\infty}\expo{-\ic t_{1}}\expo{-\ic t_{2}}
\pars{s + bt_{1}t_{2}}^{-g}\,\dd t_{1}\,\dd t_{2} =
{2^{2g} \over s^{g}}
\int_{0}^{\infty}\int_{0}^{\infty}
{\expo{-\ic\pars{t_{1} + t_{2}}}
\over \pars{4 + 4bt_{2}t_{1}/s}^{g}}\,\dd t_{1}\,\dd t_{2}
\\[5mm] & =
{2^{2g} \over bs^{g - 1}}
\int_{0}^{\infty}\int_{0}^{\infty}
{\expo{-\ic\omega\pars{t_{1} + t_{2}}/2}
\over \pars{4 + 4t_{2}t_{1}}^{g}}\,\dd t_{1}\,\dd t_{2}\qquad
\mbox{where}\quad\omega \equiv 2\root{s \over b}
\end{align}

\begin{align}
\mc{I} & =
{2^{2g} \over bs^{g - 1}}\int_{0}^{\infty}\int_{0}^{\infty}
{\expo{-\ic\omega\pars{t_{1} + t_{2}}/2}
\over \bracks{4 + \pars{t_{1} + t_{2}}^{2} - \pars{t_{1} - t_{2}}^{2}}^{g}}
\,\dd t_{1}\,\dd t_{2}
\\[5mm] & =
{2^{2g} \over bs^{g - 1}}\int_{0}^{\infty}\int_{t_{2}}^{\infty}
{\expo{-\ic\omega t_{1}/2}
\over \bracks{4 + t_{1}^{2} - \pars{t_{1} - 2t_{2}}^{2}}^{g}}
\,\dd t_{1}\,\dd t_{2}
\\[5mm] & =
{2^{2g} \over bs^{g - 1}}\int_{0}^{\infty}\expo{-\ic\omega t_{1}/2}
\int_{0}^{t_{1}}{1 \over \bracks{4 + t_{1}^{2} - \pars{t_{1} - 2t_{2}}^{2}}^{g}}
\,\dd t_{2}\,\dd t_{1}
\\[5mm] & =
{2^{2g} \over bs^{g - 1}}\int_{0}^{\infty}\expo{-\ic\omega t_{1}/2}
\int_{-t_{1}/2}^{t_{1}/2}{1 \over \pars{4 + t_{1}^{2} - 4t_{2}^{2}}^{g}}
\,\dd t_{2}\,\dd t_{1}
\\[5mm] & =
{2^{2g} \over bs^{g - 1}}\int_{0}^{\infty}
{\expo{-\ic\omega t_{1}/2} \over \pars{t_{1}^{2} + 4}^{g - 1/2}}
\int_{0}^{t_{1}/2}{1 \over \bracks{1 - 4t_{2}^{2}/\pars{4 + t_{1}^{2}}}^{g}}
{2 \over \root{t_{1}^{2} + 4}}\,\dd t_{2}\,\dd t_{1}
\\[5mm] & =
{2^{2g} \over bs^{g - 1}}\int_{0}^{\infty}
{\expo{-\ic\omega t_{1}/2} \over \pars{t_{1}^{2} + 4}^{g - 1/2}}
\int_{0}^{t_{1}/\root{t_{1}^{2} + 4}}{1 \over \pars{1 - t_{2}^{2}}^{g}}
\,\dd t_{2}\,\dd t_{1}
\\[5mm] & =
{4 \over bs^{g - 1}}\int_{0}^{\infty}
{\expo{-\ic\omega t_{1}} \over \pars{t_{1}^{2} + 1}^{g - 1/2}}
\int_{0}^{t_{1}/\root{t_{1}^{2} + 1}}{1 \over \pars{1 - t_{2}^{2}}^{g}}
\,\dd t_{2}\,\dd t_{1}
\end{align}

The $\ds{t_{2}}$-integral can be evaluated, by some CAS, in terms of the
  Hypergeometric Function $\ds{{}_{2}\mrm{F}_{1}}$. Namely,

\begin{align}
\mc{I} & =
{4 \over bs^{g - 1}}\int_{0}^{\infty}
{t_{1} \over \pars{t_{1}^{2} + 1}^{g}}\,\,\,
{}_{2}\mrm{F}_{1}\pars{%
{1 \over 2},g;{3 \over 2};{t_{1}^{2} \over t_{1}^{2} + 1}}
\expo{-\ic\omega t_{1}}\,\dd t_{1}
\end{align}

I guess that's all we can do for awhile !!!.
Comment: I see a few problems in the beginning of your argument. If we let $\omega = 2 (s/b)^{1/2}$, then how come $i \omega (t_{1} +  t_{2})$ in the exp divided by 2 ? Also, in the second line of equations from above, where did the part $\int_{0}^{\infty} \int_{0}^{t_{1}}$ go?


What distribution could simulate "realistic" human survival times?

Question: I want to simulate more or less realistic survival times for humans. I want to use a basic distribution$^*$ to do so. What distribution and what parameters would, to some extent, resemble the survival of humans$^{**}$?
$^*$ For instance, a Weibull with a certain combination of parameters.
$^{**}$Assuming an ideal scenario: no wars, no epidemics, etc.
Comment: Welcome to CV. By "human survival times," are you referring to mortality tables?
Comment: @DJohnson hmm, good question. I was just thinking of the distribution of the age at dead of humans (assuming all kinds of homogeneity), but I think you make a good point and I should have a look at mortality tables.
Comment: Do you mean "assuming all kinds of heterogenetity?" One source for mortality data in the US is the CDC's NVSS... http://www.cdc.gov/nchs/nvss/deaths.htm
Answer: You can extract the distribution of the age at death from mortality tables or from life tables (which are often publicly available) via simple calculation. A good source of such information across many countries is the Human Mortality Database (for accessing this you need to register and be approved, but the data are free). However, in many countries life table data is often also available from government sources or similar agencies, in some cases online.
For example, I got the data for this plot (NZ male death probabilities, 2005-2007):

from here (in the sidebar box labelled, "Downloads", second link).
[However, these life-table distributions will represent a mixture across cohorts, so they won't actually represent the distribution for any given cohort. They're also always a at least few years out of date, unless you're working with projections.  Nevertheless they're about as good as you're likely to obtain easily.]
These do not look like any simple common distribution you'd find in a textbook, and vary from country to country as well as over time. There's usually a spike at the very youngest ages and a big broad hump at the older ages. While these distributions are given for discrete ages, with there being typically around 100 ages under consideration, you may well consider using continuous distributions to approximate these.
For a first world country with good health-care, you tend to see a relatively small spike at infancy and a big mass, left skew but not too far from symmetric (much as we see above), peaking in the vicinity of 80 or so (earlier if you go back in time, later in countries with good health care of the broader population; the peak above is at 87) but with a wide spread about it. Further examples here and here.
If you want to use "standard" distributions you'll need to use a mixture of them. You might do more or less okay with a two- to four- component mixture distribution for these cases. For countries with long life expectancy and low young-age mortality the broad peak might be treated as roughly normal, but you'll probably want a third component to represent mortality at the middle ages.
[Such curves - characterized by low infant mortality - may also be found in poorer countries which nevertheless have relatively good healthcare systems, and conversely higher infant mortality may be seen in otherwise wealthy countries that have a strong division between rich and poor and don't have good health coverage of the poor.]
Countries with lower life-expectancy tend to have much higher infant mortality (with the peak at the youngest ages being far higher, and extending out several years) and much more of a left tail on the broad peak (as well as the older peak being downshifted somewhat).
Answer: For a review of models which have been used you might want to look at

@ARTICLE{thatcher99,
  author = {Thatcher, A R},
  year = 1999,
  title = {The long-term pattern of adult mortality and the highest attained
          age},
  journal = {Journal of the Royal Statistical Society, Series A},
  volume = 162,
  pages = {5--43}
}

There is also a substantial literature on the extremes of human life span. Although this is not what you asked it is a cautionary tale about the difficulties of modelling in this field. A possible first read is

@ARTICLE{olshansky90,
  author = {Olshansky, S J and Carnes, B A and Cassel, C},
  title = {In search of {M}ethuselah: estimating the upper limits to human
          longevity},
  year = 1990,
  journal = {Science},
  volume = 250,
  pages = {634--640}
}


passing echo value from php page to javascript showing junk data

Question:

First image is the log showing value i got in data variable in Ajax success, I'm not able to match it with "success" since returning junk data .
Second image is the page where i enter details in database if my password field both matches(retype password).
Third images is where i get the value from page to Ajax "data" variable.
Answer: if updateprocess.php is only called by this ajax function, then you don't need the  tag etc, you can get rid of everything before <?php and after ?>...
I would point out the code is extremely open to SQL injection attacks ... so I hope it's for learning purposes only :)
Comment: that worked. so i should not use html tag if it is called by ajax function.? it will be returned along with echo.?
Comment: Correct,,,, HOWEVER... I would recommend that you return JSON it's good practice. It may seem a bit overkill for a success/fail, and you need to parse it at the JS-side. Also... SANITISE anything being inserted into DB... Could be worth at this point suggesting you read up on building a REST API for the AJAX calls. Again don't know you're project but would be very worthwhile learning.


Implementing static and non-static method of a class performance

Question: It is correct to write the same method PublicMethod of this example as static and non-static i? Is there some effect on performance invoking the non-static method or the compiler will optimize the code?
public class MyClass
{
  private double y;
  private double PrivateFunc(double x) { return some_operation(x,y);}

  public static double PublicFunc(MyClass A, double x)
  {
      return A.PrivateFunc(x);
  }

  public double PublicFunc(double x)
  {
      return MyClass.PublicFunc(this,x);
  }

  /* instead of repeating code of the static method
  public double PublicFunc(double x)
  {
      return PrivateFunc(this,x);
  }
  */
}

Comment: Calling a method is so fast you will never see a difference. It is more about readablity. Think about why you need the static or non-static method. Is it really necessary to have both?
Comment: The code you have written is nothing but recursively calling itself. This code is of no use. When you call MyClass.PublicFunc it is going to be in infinite loop and throw StackOverflowException... Did you try this code?
Comment: You first need to learn about static method and class method. And why they should be used. If static method were the solution, OOP wouldn't have been in place.
Comment: @ChetanRanpariya Although I disagree with how it's implemented, but it's not recursively calling itself. It's calling the other static method, and it wouldn't throw a `StackOverflowException`.
Comment: @AhmedAbdelhameed agree with you. I missed the `PrivateFunc` and `some_operation` methods.
Comment: @FCin if you have to implement a mathematical model with recursive or iterative invocation of a function, then the difference is important.
Comment: @Ozzy No, it is not.
Answer: Yes, sometimes it's convenient to have a static and a non-static version of a method. string.Equals() is an example although the static and the non-static versions of this method don't share the exact same implementation.
However, why do you think you need a private version of the method in this case?
You can simply implement it without the private method, something like this:
public class MyClass
{
    private double y;

    public static double PublicFunc(MyClass A, double x)
    {
      return A.PublicFunc(x);
    }

    public double PublicFunc(double x)
    {
      // The actual implementation.
      return some_operation(x, y);
    }
}


A locally injection is an injection for the real line?

Question: Let $f:\mathbb{R} \rightarrow \mathbb{R}$ be a continuous mapping, if for any $x\in \mathbb{R}$, there exist a neighbourhood $U$ of $x$, such that $f$ is an injection on $U$, then $f$ is an injection.
If $f:(a,b) \rightarrow \mathbb{R}$, and for any $x\in (a,b)$, there exist a neighbourhood $U$ of $x$, such that $f$ is an injection on $U$, then $f$ is an injection.
If $f:[a,b] \rightarrow \mathbb{R}$, and for any $x\in [a,b]$, there exist a neighbourhood $U$ of $x$, such that $f$ is an injection on $U$, then $f$ is an injection.
If $f:(a,b) \rightarrow \mathbb{R}^n$,$n \geq 2$, and for any $x\in (a,b)$, there exist a neighbourhood $U$ of $x$, such that $f$ is an injection on $U$, then $f$ is an injection.
Are these all right?
Comment: The first three are true because the order properties of the real line prevent a function from being able to loop back on itself. As Kyle Miller has demonstrated, the same is not true of $\Bbb R^n$ for $n > 1$.
Comment: The last one isn't.  Consider $f(x)=(\cos x, \sin x)$.
Answer: You already have a counterexample for the last statement. Here is a sketch of proof for the other ones:
Let $a$ and $b$ be real numbers such that $f(a)=f(b)$. Assume by contradiction that $a \neq b$. Then, the interval $[a,b]$ is a compact set where $f$ attains a maximum ($M$) and a minimum ($m$) (Extreme Value Theorem). Either $M$ or $m$ is not equal to $f(a)$. Assume w.l.o.g. that $f(a)\neq M=f(x)$ for some $x$. What can you say about $x$?
Comment: Inyectivity is a property of a function, not a point. Consider the behavior of the function around x.


JavaScript Class and Custom event handler proper syntax

Question: I understand that there are many different views on the way JavaScript should be written, but I was wondering if the way I am writing it is fine. I don't want to go into the workforce writing code that nobody understands.
The basic premise of this code was to test custom event handlers for objects, was wondering if there is any glaring "YOU SHOULD NOT DO THIS" type thing?
    function EventClass() {
        var self = this;
        var events = {};
        var i = 0;
        self.fire = function(evt, args) {
            for (x in events[evt])
                events[evt][x].call(this, args);
        }

        self.on = function(evt, fn) {
            if (events[evt] == null) {
                events[evt] = []
            }
            events[evt].push(fn);
        }
    };

    function Human(x, y) {
        var self = this;
        self.__proto__ = new EventClass();
        var xCoord = 0;
        var yCoord = 0;

        self.events = {
            "MOVEMENT" : "movement"
        };

        self.init = function(x,y) {
            xCoord = x;
            yCoord = y;
        }

        self.draw = function(context) {
            context.beginPath();
            context.arc(xCoord,yCoord,10,0,Math.PI*2,true);
            context.closePath();
            context.fill();
        }

        self.moveLeft = function() {
            xCoord -= 5;
            self.fire(self.events.MOVEMENT, xCoord);
        }
        self.init(x,y);
    };

    function Player(x, y) {
        var self = this;
        self.__proto__ = new Human();
        self.init(x,y);
    };

    function Canvas(c) {
        var self = this;
        var canvas;
        var context;
        var objects = [];

        self.init = function(c) {
            canvas = c;
            context = canvas.getContext("2d");
        };

        this.redraw = function() {
            context.clearRect(0,0,300,300);
            for (x in objects) {
                objects[x].draw(context);
            }
        }

        this.addObject = function(obj) {
            objects.push(obj);
            obj.on(obj.events.MOVEMENT, function(coord) {
                console.log(coord);
                self.redraw();
            });
        };
        self.init(c);
    }

    var canvas = new Canvas(document.getElementById("canvas"));
    var human0 = new Human(75,75);
    canvas.addObject(human0);
    var human1 = new Human(100,100);
    canvas.addObject(human1);
    var player = new Player(200,200);
    canvas.addObject(player);

    canvas.redraw();

Answer: A couple of small things -- sort of.
The first one is tiny.
Be consistent with the this and self thing.
The example I'm thinking of here is in your Canvas constructor.
The truth of the matter is that nothing inside of your particular implementation requires self.
Unless you're planning on giving your methods to other objects, or callbacks, self isn't required, there, until you get into writing functions which exist INSIDE of the methods.
And even then, all self will help with is accessing the public properties/methods of that particular instance, and wouldn't help you access events or i or whatever.
Not to say that it's not good to do -- it's just more-useful when you're doing the object-composition thing, rather than object-construction thing (and frequently becomes downright necessary, then).
The second thing was more of a problem.
__proto__ might be reasonably-well supported, if you're talking about FireFox/Chrome, but if you need to support wide swaths of browsers, you're going to make your life much more difficult by doing things that way, rather than adding to the ConstructorFN.prototype object.
Comment: I was doing Human.prototype = new EventClass() and Player.prototype = new Human() earlier and all objects were pointing to the same instance of EventClass, is there a way to fix this?
Comment: @Ven not exactly, no.  You're creating one single EventClass object.  That one object is the prototype for all Humans.  That one human is the prototype for all Players.  I'd suggest looking at composition, rather than inheritance, if you don't intend to have inherited properties which are basically `static` references.  Might I suggest looking into ***dependency injection*** in this case.  Any other form of component-based composition will be equally valid.


Solving trigonometric equations of the form $a\sin x + b\cos x = c$

Question: Suppose that there is a trigonometric equation of the form $a\sin x + b\cos x = c$, where $a,b,c$ are real and $0 < x < 2\pi$. An example equation would go the following: $\sqrt{3}\sin x + \cos x = 2$ where $0<x<2\pi$.
How do you solve this equation without using the method that moves $b\cos x$ to the right side and squaring left and right sides of the equation?
And how does solving $\sqrt{3}\sin x + \cos x = 2$ equal to solving $\sin (x+ \frac{\pi}{6}) = 1$
Comment: I explained the general solution in my answer here: http://math.stackexchange.com/a/201405/4583
Comment: Hint: Expand $\sin(x+\frac{\pi}{6})$.
Comment: Try using the [tangent half-angle substitution](https://en.wikipedia.org/wiki/Tangent_half-angle_substitution#The_substitution).
Answer: The idea is to use the identity $\sin(\alpha+\beta)=\sin\alpha\cos\beta+\cos\alpha\sin\beta$. You have $a\sin x+b\cos x$, so you'd like to find an angle $\beta$ such that $\cos\beta=a$ and $\sin\beta=b$, for then you could write
$$a\sin x+b\cos x=\cos\beta\sin x+\sin\beta\cos x=\sin(x+\beta)\;.$$
The problem is that $\sin\beta$ and $\cos\beta$ must be between $-1$ and $1$, and $a$ and $b$ may not be in that range. Moreover, we know that $\sin^2\beta+\cos^2\beta$ must equal $1$, and there's certainly no guarantee that $a^2+b^2=1$.
The trick is to scale everything by $\sqrt{a^2+b^2}$. Let $A=\dfrac{a}{\sqrt{a^2+b^2}}$ and $B=\dfrac{b}{\sqrt{a^2+b^2}}$; clearly $A^2+B^2=1$, so there is a unique angle $\beta$ such that $\cos\beta=A$, $\sin\beta=B$, and $0\le\beta<2\pi$. Then
$$\begin{align*}
a\sin x+b\cos x&=\sqrt{a^2+b^2}(A\sin x+B\cos x)\\
&=\sqrt{a^2+b^2}(\cos\beta\sin x+\sin\beta\cos x)\\
&=\sqrt{a^2+b^2}\sin(x+\beta)\;.
\end{align*}$$
If you originally wanted to solve the equation $a\sin x+b\cos x=c$, you can now reduce it to $$\sqrt{a^2+b^2}\sin(x+\beta)=c\;,$$ or $$\sin(x+\beta)=\frac{c}{\sqrt{a^2+b^2}}\;,$$ where the new constants $\sqrt{a^2+b^2}$ and $\beta$ can be computed from the given constants $a$ and $b$.
Comment: +1 Nice, thoroughly explained answer. I wonder whether there's a trend of some askers to accept the question yet without upvoting it...?
Comment: @DonAntonio: Thanks. You need $15$ rep to upvote, so new users don't have that option.
Comment: Well, that's a new one for me, @Brian. Thanks for bringing that to my attention. BTW, this seems to me a rather odd rule: if you trust them enough to ask/accept questions trust them to upvote, too. Anyway now I understand better this.
Answer: Riffing on @Yves' "little known" solutions ...

The above trigonograph shows a scenario with $a^2 + b^2 = c^2 + d^2$, for $d \geq 0$, and we see that
$$\theta = \operatorname{atan}\frac{a}{b} + \operatorname{atan}\frac{d}{c} \tag{1}$$
(If the "$a$" triangle were taller than the "$b$" triangle, the "$+$" would become "$-$". Effectively, we can take $d$ to be negative to get the "other" solution.)
Observe that both $c$ and $d$ are expressible in terms of $a$, $b$, $\theta$:
$$\begin{align}
a \sin\theta + b \cos\theta &= c \\
b \sin\theta - a\cos\theta &= d \quad\text{(could be negative)}
\end{align}$$
Solving that system for $\sin\theta$ and $\cos\theta$ gives
$$\left.\begin{align}
\sin\theta &= \frac{ac+bd}{a^2+b^2} \\[6pt]
\cos\theta &= \frac{bc-ad}{a^2+b^2}
\end{align}\quad\right\rbrace\quad\to\quad \tan\theta = \frac{ac+bd}{bc-ad} \tag{2}$$
We can arrive at $(2)$ in a slightly-more-geometric manner by noting
$$c d = (a\sin\theta + b \cos\theta)d = c( b\sin\theta - a \cos\theta ) \;\to\; ( b c - a d)\sin\theta = \left( a c + b d \right)\cos\theta \;\to\; (2) $$
where each term in the expanded form of the first equation can be viewed as the area of a rectangular region in the trigonograph. (For instance, $b c \sin\theta$ is the area of the entire figure.)
Answer: Using complex numbers, and setting $z=e^{i\theta}$,
$$a\frac{z-z^{-1}}{2i}+b\frac{z+z^{-1}}2=c,$$
or
$$(b-ia)z^2-2cz+(b+ia)=0.$$
The discriminant is $c^2-b^2-a^2:=-d^2$, assumed negative, then the solution
$$z=\frac{c\pm id}{b-ia}.$$
Taking the logarithm, the real part $$\ln\left(\dfrac{\sqrt{c^2+d^2}}{\sqrt{a^2+b^2}}\right)=\ln\left(\dfrac{\sqrt{c^2+a^2+b^2-c^2}}{\sqrt{a^2+b^2}}\right)=\ln(1)$$ vanishes as expected, and the argument is
$$\theta=\pm\arctan\left(\frac dc\right)+\arctan\left(\frac ab\right).$$

The latter formula can be rewritten with a single $\arctan$, using
$$\theta=\arctan\left(\tan(\theta)\right)=\arctan\left(\frac{\pm\dfrac dc+\dfrac ab}{1\mp\dfrac dc\dfrac ab}\right)=\arctan\left(\frac{\pm bd+ac}{bc\mp ad}\right).$$
Answer: This is little known, but you can solve the equation without much trigonometry.
WLOG, we can assume that $a^2+b^2=1$ (the coefficients can be normalized). Write
$$a\,S+b\,C=c,\\b\,C=c-aS,\\b^2(1-S^2)=(c-a\,S)^2,\\S^2-2ac\,S+c^2-b^2=0.$$
The solution of the quadratic equation is
$$S=ac\pm bd$$ where $d=\sqrt{1-c^2}$.
By symmetry,
$$C=bc\mp ad.$$
If you have enough with the values of the sine and the cosine, you can stop here. Otherwise
$$\theta=\arctan\frac SC.$$

For unnormalized $a,b$, the solution is
$$S=\frac{ac\pm bd}{a^2+b^2},\\
C=\frac{bc\mp ad}{a^2+b^2}$$ and
$$\color{green}{\theta=\arctan\frac{ac\pm bd}{bc\mp ad}}$$
where $d=\sqrt{a^2+b^2-c^2}$. It does not exist when $a^2+b^2<c^2$.

From the above, one can observe that the solution is also given by
$$\theta=\arctan\frac ab\pm\arctan\frac dc$$ but this takes two (costly) arc tangents instead of one.
Answer: I'm assuming $ab\neq 0$, since otherwise trivial. $a\sin x+b\cos x-c=0$
$$\iff a\left(2\sin\frac{x}{2}\cos\frac{x}{2}\right)+b\left(\cos^2\frac{x}{2}-\sin^2\frac{x}{2}\right)-c\left(\sin^2\frac{x}{2} +\cos^2\frac{x}{2}\right)=0$$

Assume $\cos\frac{x}{2}\neq 0$. Then

$$\stackrel{:\cos^2 \frac{x}{2}\neq 0}\iff (b+c)\tan^2\frac{x}{2}-2a\tan\frac{x}{2}+(c-b)=0$$
If $b+c\neq 0$, then
$$\iff \tan\frac{x}{2}=\frac{a\pm\sqrt{a^2+b^2-c^2}}{b+c}$$
$$\iff x=2\left(\arctan\left(\frac{a\pm\sqrt{a^2+b^2-c^2}}{b+c}\right)+n\pi\right),\, n\in\Bbb Z$$
Real solutions exist iff $a^2+b^2\ge c^2$.
If $b+c=0$, then
$$\iff \tan\frac{x}{2}=\frac{c-b}{2a}\iff x=2\left(\arctan\frac{c-b}{2a}+n\pi\right),\, n\in\Bbb Z$$

Assume $\cos\frac{x}{2}=0$. Equality holds iff $b+c=0$.
Answer: https://en.wikibooks.org/wiki/Trigonometry/Simplifying_a_sin(x)_%2B_b_cos(x)
While the above answers perfectly answer your question, you might benefit from taking a look at the above link. It particularly is relevant for the second part of the question and explains how to simplify $f(x) =a\sin(x) + b\cos(x)$ to a single sine function, approaching it both geometrically and algebraically.
Comment: Linked answers are discouraged, just to let you know, but you did provide some insight on what is found when looking at the link, so good job $(+1)$
Answer: Older textbooks often suggested solving such equations via the tan half-angle identities to make an algebraic equation in $t = \tan (x/2)$. For a derivation see https://en.wikipedia.org/wiki/Tangent_half-angle_formula or this math SE question.
In particular,
$$\sin x = \frac{2t}{1+t^2} \\
\cos x = \frac{1-t^2}{1+t^2} \\
\tan x = \frac{2t}{1-t^2}
$$
So if $a \sin x + b \cos x = c$ we have $2at + b(1-t^2) = c(1+t^2)$. This is a quadratic in $t$, which we can easily solve, and once we know $t = \tan (x/2)$ we can find $x$. For an example of this method, see this math SE answer.


Combinatorics - too much combinations ? where is my mistake?

Question: Problem :

A person has 7 friends . How many combinations exists so that he would be able to  invite different
    groups of 3 of them for a dinner that lasts 7 days  (7
    sequential days) so that every 2 friends would be together in only
    one dinner ?

My solution : If a person has 7 friends then the number of couples that could be are 7 above 2 : $\binom{7}{2}$ , which are 21.Since every couple of friends are together in exactly one dinner (out of the 7 dinners in total) , then in every day that he invites 3 different friends , he actually invites 3 different couples , that don't appear in the rest of the days .Hence , in the first day he needs to pick 3 couples out of 21 , which are : $\binom{21}{3}$ . In the second day he needs to pick 3 couples out of 18 ... and so on .
Then in total :
$ \binom{21}{3} \cdot \binom{18}{3} \cdot \binom{15}{3} \cdot \binom{12}{3} \cdot \binom{9}{3} \cdot \binom{6}{3} \cdot \binom{3}{3} $
But this seems wrong , since the number of combinations is too big . Can anyone verify that I'm wrong ?
Much appreciated
Comment: This was a fun problem to do! Before I post a full solution, could you explain where you have the problem from and (if applicable) when it's due, so I can avoid just doing your homework for you? Thanks.
Comment: @HenningMakholm: It's a workbook that I found in the library .I'm practicing some exercises before my exam on Tuesday .
Answer: Your mistake is the statement "in every day that he invites 3 different friends , he actually invites 3 different couples , that doesn't appear in the rest of the days". You don't have the ability to choose any 3 couples, because the 3 couples together need to contain 3 people. You can't, for example, invite the disjoint couples A/B, C/D, E/F, since that would amount to inviting 6 people, but that choice is counted in ${21 \choose 3}$.
Comment: I mean, I guess the quoted statement itself is right and is a helpful way to think about the problem. The problem is your inference that *any* choice of 3 couples would be permissible.
Answer: Gregory's answer explains what is wrong with your method of counting. Here's a way to get the right result:
First, since there are 21 pairs of friends and each of the 7 dinners "uses up" 3 pairs of friends, every pair of friends needs to occur in one of the dinner. Thus every friend will be invited to exactly three dinners and meet each of the 6 other friends once.
We start by counting how many different sets of 7 dinners there are, without caring about which sequence the dinners are held in. Usually this tends to be harder than counting ordered sequences, but in this particular problem it happens to be much easier.
Let A be the youngest friend. The other six friends needs to go to three dinners with A in them in three pairs. The number of ways to partition six elements into three unordered pairs is $5\cdot3\cdot1=15$ (see e.g. Brian M. Scott's answer here), so there are 15 ways to choose what the three dinners that include A will be.
Let B be the youngest friend except for A, and let C be the third friend at the dinner that A and B are in. Let D be the youngest friend not yet named, and let E be the third quest at the AD dinner. The dinners decided on so far are now:
ABC
ADE
AFG

There must be a dinner with B and D in it, and the third person there is either F or G. There are 2 options to choose among here.
Without loss of generality let's assume it was F, so our dinner list now looks like
ABC
ADE
AFG
BDF

At this point there's one and only one way to arrange the three remaining dinners. The BE diner can only be BEG, and then the CF and CE dinners must be CDG and ORY CEF.
Thus, multiplying together, the number of ways to select an unordered set of 7 dinners is $15\cdot 2=30$.
It remains to select which order the 7 dinners will be held in. There are $7!=5040$ ways to do that, so the final number of options is
$$ ((5\cdot 3\cdot 1)\cdot 2)\cdot7! = 30\cdot 5040 = 151\,200$$

How I came up with this: I started doing it "the hard way", caring about the sequence of dinners from the beginning. It took about one page of paper to exhaustively enumerate the possible shapes of the who-has-met-whom-yet graph after each night. Then I spent a few hours trying to condense the big exhaustive diagram down to a proof. Along the way, a gap in one of my proofs turned out to be because the lemma I was trying to prove wasn't true, because I had made an error during the exhaustive search, which I then needed to fix. Finally I came upon the above argument. All in all an interesting interplay and cross-fertilization between brute-forcing through a concrete examples and the desire to find an abstract argument.


talking to the umpire after being ejected

Question: Why does the umpire and manager/player keep on argueing after the ejection? Why does the umpire let the manager/player keep on talking to him and remain on the field after being ejected?
Answer:
Why does the umpire and manager/player keep on argueing after the ejection?

Why does anyone ever argue with a umpire/referee at all? Certainly no official at the professional level is ever going to change their mind because somebody shouted at them. That leaves two possibilities:

They do it because they're human, and sometimes humans do things which aren't rational, particularly when they're frustrated.
They think that by shouting at the official, they may cause the official to (subconsciously) favour that team in later decisions, or they may improve their team morale by letting the other players see that someone "is sticking up for them against The Man".

I personally suspect the first of these points is the reason in the vast majority of cases.

Why does the umpire let the manager/player keep on talking to him and remain on the field after being ejected?

What do you suggest the umpire does in this scenario? Walking away isn't going to have any effect, because the angry person will just follow them. Getting stadium security to physically remove the other person is more likely to cause a riot than improve the situation.


List flutter substituir item pelo valor onpressed do botão clilcado

Question: Em um array de botões dinamicos, onde cada botão passa um valor diferente, preciso que o valor passado seja armazenado em um arraylist de 60 posições sendo cada um referente a um botão clicado.
O array foi criado com todas posições recebendo o valor ZERO inicialmente, porém ao receber o valor do botão clicado ele deveria substituir pelo valor '1', sendo assim a cada botão clicado substitui o item no arraylist referente a sua posição.
porém quando faço isto o arraylist e zerado e so substitui a ultima posição clicada.
enfim o que eu quero e que um sistema igual ao da mega sena, onde cada número selecionado gera um array de numeros selecionados, no total vão ser 10 numero passados, portanto o array deverá ter 60 posições com 10 posições com valor igual a 1, e 50 posições com valor inicial de 0.
segue codigo completo que estou usando:
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';

class ApostaUser extends StatefulWidget {
  const ApostaUser({Key? key}) : super(key: key);

  @override
  State<ApostaUser> createState() => _ApostaUserState();
}

class _ApostaUserState extends State<ApostaUser> {
  var id_user = '';
  var _selecionados ='';
  var _count = 0;
  var color = Colors.blue;

  void _incrementCounter(selecao) async{

    final int i = int.parse(selecao);
    final _selecionados = List<int>.filled(60, 0);

    if(_count==10){
      Fluttertoast.showToast(msg: "Você já escolheu 10 números !",toastLength: Toast.LENGTH_SHORT);
    }else{
        for (var y = 0; y < _selecionados.length; y++) {
         if(_selecionados[i] == 1){
           _selecionados[i] = 0;
         }else{
           _selecionados[i] = 1;
         }
        }
        print(_selecionados);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    id_user = PrefsService.getIdUser()??'';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        leading: IconButton(
          onPressed: () {Navigator.pop(context);},
          icon: Icon(
            Icons.arrow_back_ios,
            size: 20,
            color: Colors.white,
          ),
        ),
        title:new Center(child: new Text("Criar Apostas", textAlign: TextAlign.center)),
      ),
        body: SingleChildScrollView(
          child: Center(
            child: Column(
              children: [
                Container(
                  height: 250,
                  width: MediaQuery.of(context).size.width,
                    child: Card(
                      elevation: 3,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(10.0)),
                        side: BorderSide(width: 1, color: Colors.blue),
                      ),
                      child: _contentGridView(),
                    ),
                ),
                Container(
                  child:Text(_selecionados.toString())
                ),
              ],
            ),
          ),
        ),
    );
  }

  Widget _contentGridView(){
    final _list = List<int>.filled(60, 0);
    final _bola = List<int>.filled(60, 0);

    for (int i = 0; i < _list.length; i++) {
        _list[i] = i;
        _bola[i] = i+1;

    }
    return GridView.builder(

      itemCount: _list.length,
      padding: EdgeInsets.all(5.0),
      gridDelegate:
        SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 10,
          mainAxisSpacing: 5.0,
          crossAxisSpacing: 3.0,
        ),

         itemBuilder:(context, index) =>
            CircleAvatar(
              backgroundColor: color,
              child: TextButton(
                onPressed:() => _incrementCounter(_list[index].toString()),
                  child: Text(
                    _bola[index].toString(),
                    style: GoogleFonts.roboto(fontSize: 13.0, color: Colors.white),
                  ),
              ),
            ),
    );
  }
}

Answer: A sua pergunta está um pouquinho confusa, mas acredito que seja o que você deseja como resultado, montei um pequeno exemplo baseado na sua grid.
Da uma olhadinha e aplique os ajustes necessários para caber dentro da sua necessidade.
Exemplo
import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  final List<int> bolas =
      List.generate(60, (int index) => index, growable: false);
  final List<int> bolasSelecionadas = [];

  void addItemSelected(int value) {
    if (bolasSelecionadas.length == maxBolas) {
      print("Você só pode selecionar até 10 números!");
      return;
    }

    setState(() {
      if (bolasSelecionadas.contains(value))
        bolasSelecionadas.remove(value);
      else
        bolasSelecionadas.add(value);
    });
    print(value);
  }

  Color getBackgroundColor(int value) {
    if (bolasSelecionadas.contains(value))
      return Color(0xFF4a4a4a);
    else
      return Colors.white;
  }

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      Expanded(
        child: GridView.builder(
          itemCount: bolas.length,
          padding: EdgeInsets.all(5.0),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 10,
            mainAxisSpacing: 5.0,
            crossAxisSpacing: 3.0,
          ),
          itemBuilder: (context, index) => CircleAvatar(
            backgroundColor: getBackgroundColor(bolas[index]),
            child: TextButton(
              onPressed: () => addItemSelected(bolas[index]),
              child: Text(
                bolas[index].toString(),
              ),
            ),
          ),
        ),
      ),
      SizedBox(
        height: 30,
        child: TextButton(
          onPressed: () {
            print(bolasSelecionadas);
            setState(() {
              bolasSelecionadas.clear();
            });
          },
          child: Text("Exibir selecionados"),
        ),
      )
    ]);
  }
}

Se quiser pode testar no DartPad
Alguns problemas que verifiquei

Lembre-se sempre de usr o setState((){}) para atualizar o valor das suas variáveis, caso não esteja usando algum outro gerenciador de estado.

Você pode utilizar o método List.generate(length, builder) para gerar uma lista com o total de itens que deseja e fazer os tratamentos direto no builder da mesma, sem precisar fazer um for-loop para alimentar depois.
Answer: Fiz umas modificações na função do _incrementCounter e seguindo orientação do Matheus usei o generate para criar a lista dos 60 números, adcionando + 1 no widget TEXT, apenas para exibir os número de 1 a 60,  conseguir realizar a adição e remoção do item da list, conforme o botão clicado.
Criei uma variavel para guardar e exibir somentes o numeros clicados extraidos da list.
Para mudar a cor do selecionado usei como base a função getBackgroundColor, que define a cor conforme os valores armazenados na list 'bolasSelecionadas'.
O código ficou como assim:
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';

class ApostaUser extends StatefulWidget {
  const ApostaUser({Key? key}) : super(key: key);

  @override
  State<ApostaUser> createState() => _ApostaUserState();
}

class _ApostaUserState extends State<ApostaUser> {
  var id_user = '';
  var _count = 0;
  var marcado = '';
  var cores = Colors.blue;
  final selecionados = List<int>.filled(60, 0);
  final List<int> bolasSelecionadas = [];

  void _incrementCounter(selecao) {

    final int i = int.parse(selecao);

    marcado = '';
      for (var y = 0; y < selecionados.length; y++) {

        if(y == i){
          if(selecionados[i] == 1){
            if(_count <= 10){
              _count--;
              setState(() {
                selecionados[i] = 0;
                if (bolasSelecionadas.contains(i)) {
                  bolasSelecionadas.remove(i);
                }else {
                  bolasSelecionadas.add(i);
                }
              });
            }else{
              Fluttertoast.showToast(msg: "Você já escolheu 10 números !",toastLength: Toast.LENGTH_SHORT);
            }

          }else{
            if(_count <10){
              _count++;
              setState(() {
                selecionados[i] = 1;
                if (bolasSelecionadas.contains(i)) {
                  bolasSelecionadas.remove(i);
                }else {
                  bolasSelecionadas.add(i);
                }
              });
            }else{
              Fluttertoast.showToast(msg: "Você já escolheu 10 números !",toastLength: Toast.LENGTH_SHORT);
            }
          }
        }

        if(selecionados[y] == 1 ){
          marcado = marcado + ' ' + (y+1).toString();
        }
      }
      //checando as saídas
      print(selecionados);
      print(marcado);
  }

  Color getBackgroundColor(int value) {
    if (bolasSelecionadas.contains(value))
      return Colors.deepOrange;
    else
      return Colors.blue;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    id_user = PrefsService.getIdUser()??'';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        leading: IconButton(
          onPressed: () {Navigator.pop(context);},
          icon: Icon(
            Icons.arrow_back_ios,
            size: 20,
            color: Colors.white,
          ),
        ),
        title:new Center(child: new Text("Criar Apostas", textAlign: TextAlign.center)),
      ),
        body: SingleChildScrollView(
          child: Center(
            child: Column(
              children: [
                Container(
                  height: 250,
                  width: MediaQuery.of(context).size.width,
                    child: Card(
                      elevation: 3,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(10.0)),
                        side: BorderSide(width: 1, color: Colors.blue),
                      ),
                      child: _contentGridView(),
                    ),
                ),
                Container(
                  child:Text(marcado.toString()),
                ),
              ],
            ),
          ),
        ),
    );
  }

  Widget _contentGridView(){

    final List<int> _list = List.generate(60, (int index) => index, growable: false);

    return GridView.builder(
      itemCount: _list.length,
      padding: EdgeInsets.all(5.0),
      gridDelegate:
        SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 10,
          mainAxisSpacing: 5.0,
          crossAxisSpacing: 3.0,
        ),
         itemBuilder:(context, index) =>
            CircleAvatar(
              backgroundColor: getBackgroundColor(_list[index]),
              child: TextButton(
                onPressed:() => _incrementCounter(_list[index].toString()),
                  child: Text(
                      (_list[index]+1).toString(),
                    style: GoogleFonts.roboto(fontSize: 13.0, color: Colors.white),
                  ),
              ),
            ),
    );
  }
}

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Soccer Goal Uncertanty by Referee

Question: If a referee isn't sure about a goal, the teams are arguing, and there is no goal-line technology, what should the referee do?
Comment: Book any players who are arguing for dissent :-)
Answer: If there are assistant referees appointed for the match, the referee will receive help from them to ease any uncertainty. Whenever a shot is taken, the assistant referee should follow the ball all the way to the goal line (as it becomes the offside line when it moves beyond the second last defender).
If there is fumble, or slowly moving ball, this will enable them to see if the ball has crossed the line most of the time. This is highlighted on p. 88 of the 2015/16 FIFA Laws of the Game:

The assistant referees must be in line with the second-last opponent or the ball if it is nearer the goal line than the second-last opponent. The assistant referees must always face the field of play.

The signals for relaying this information to the referee are provided on p. 93 of 2015/16 FIFA Laws of the Game:

"Goal – no goal" situations
When a goal has been scored and there is no doubt about the decision, the
  referee and assistant referee must make eye contact and the assistant referee
  must then run quickly 25-30 metres along the touch line towards the halfway
  line without raising his flag.
When a goal has been scored but the ball appears still to be in play, the
  assistant referee must first raise his flag to attract the referee's attention then continue with the normal goal procedure of running quickly 25-30 metres along the touch line towards the halfway line.
On occasions when the whole of the ball does not cross the goal line and play continues as normal because a goal has not been scored, the referee must
  make eye contact with the assistant referee and if necessary give a discreet
  hand signal.

In some elite matches without goal-line technology (such as UEFA competitions), additional assistant referees (who are positioned slightly behind the goal line) will also help the referee make goal/no goal decisions. The relevant information is on p. 85 of the 2015/16 FIFA Laws of the Game:

The additional assistant referees' position is behind the goal line.
...
The additional assistant referee must communicate to the referee when a goal has been scored.
...
The additional assistant referees will use a radio communication system only and not flags to communicate decisions to the referee.
In the event of a breakdown of the radio communication system, the additional assistant referees will use an electronic signal beep flagstick to indicate their decisions.

If the referee has no help from assistant referees (either by virtue of them not being appointed, or by the fact they are too far from the goal line to offer advice), and the referee cannot decide that the ball has crossed the goal line, the decision is then that the ball has not crossed the line and play continues. This decision is indisputable, as highlighted on p. 26 of the 2015/16 FIFA Laws of the Game:

The decisions of the referee regarding facts connected with play, including whether or not a goal is scored and the result of the match, are final.
The referee may only change a decision on realising that it is incorrect or, at his discretion, on the advice of an assistant referee or the fourth official, provided that he has not restarted play or terminated the match.

Players politely and calmly appealing for decisions is an accepted part of the game - however, protesting decisions once they have been made is not (in spite of what you may see at the elite levels of the game). The referee should simply say 'no' and move on. If players continue to appeal, argue, or remonstrate beyond this point, they are then protesting and have crossed the line to dissent. This is highlighted on p. 126 of the 2015/16 FIFA Laws of the Game:

A player who is guilty of dissent by protesting (verbally or non-verbally) against a referee's decision must be cautioned.

It will most certainly be the attacking team protesting here. Since the defending team will most likely be under pressure near their own goal, advantage should not be played if the referee needs to take action against dissenters. Play is stopped, any player(s) guilty of dissent is/are cautioned, and play is restarted with an indirect free kick taken by the defending team from wherever any dissent was being delivered from.
If multiple players are committing dissent, the restart is taken from the position of whichever one is closest to their own goal line (this could even be the opposing goalkeeper, which would see the ball moved ninety metres down the other end of the field).
This is demonstrated on p. 38 of the 2015/16 FIFA Laws of the Game:

An indirect free kick is also awarded to the opposing team if, in the opinion of
  the referee, a player:
...

commits any other offence, not previously mentioned in Law 12, for which
  play is stopped to caution or send off a player

The indirect free kick is taken from the place where the offence occurred
  (see Law 13 – Position of free kick).

The principle of awarding a restart from the most advantageous field position (by playing a silent advantage) is enshrined in this piece of unrelated advice on p. 120 of the 2015/16 FIFA Laws of the Game:

If a defender starts holding an attacker outside the penalty area and continues holding him inside the penalty area, the referee must award a penalty kick.
Comment: To answer your first question, very easily. If the goalkeeper was to yell at the top of his lungs from 80 metres away, "What the f*** ref? That was a goal. How did you get that wrong?", most referees would caution for this, given that the use of foul language and the volume of it has crossed the line from frustration to dissent. If the goalkeeper ran out of his goal to argue, then yes, the free kick would be from where they were standing. However, goalkeepers will probably not run to the other end of the field to argue a decision while the ball is in play.
Comment: But how can a goalkeeper commit dissent when he is in the other side of the field? If the goalkeeper runs up to the referee and argues, then he might be in the other team's goal area!
Answer: If the referee feels he did not have a clear view of the ball, he can refer to the assistant referee, who will give him his opinion in whether it is a goal or not. The referee does not have to go by the advice given to him by his assistant, but generally does so. Once he has given his decision, if the players are still arguing beyond reason, he may book them.
UEFA has introduced two additional referees into the game, in their tournaments (Champions League, Europa League, EURO, etc), to assist in these kinds of decisions. These additional referees are positioned behind the goal line, beside each goal. Again, the main referee is under no obligation to give the same decision advised to him by the additional referee.
The decision made by the main referee in this regard is final and binding upon the game.
See FIFA Laws of the Game 2015/16, page 61 onwards, Interpretation of the Laws of the Game and Guidelines for Referees.

Soccer Goal Uncertanty by Referee


What are some numbers that are can be factored by Hurwitz primes but not Gaussian primes?

Question: Since gaussian primes can factor conventional prime numbers like 5, I was wondering about the same question but for quaternions.
Comment: $3=(1+i+j)(1-i-j)$. We have $(i+j)^2=-2$ so this is quite like factoring $3$ in the ring $\Bbb{Z}[\sqrt{-2}]$.
Answer: The number $11$ will do the job. It's not a sum of two squares, so it can't be a product of Gaussian primes, but it can be written
$$
11 = ( 1 + 3i + j)(1 - 3i - j).
$$
Comment: Or more generally, any prime which is 3 mod 4.
Comment: (If you want to learn more about this question and how to approach it systematically, you will want some tools from Algebraic Number Theory.)


How do you get amcharts5 to work on nuxt?

Question: How do you setup amcharts5 to work on nuxt?
Answer: Figured out answer after posting the question!
On nuxt.config.js add:
<code>build: {
  transpile: ['@amcharts/amcharts5'],
}
</code>


When someone says residual deviance/df should ~ 1 for a Poisson model, how approximate is approximate?

Question: I've often seen the advice for checking whether or not a Poisson model fit is over-dispersed involving dividing the residual deviance by the degrees of freedom. The resulting ratio should be "approximately 1".
The question is what range are we talking about for "approximate" - what is a ratio that should set off alarms to go consider alternative model forms?
Comment: Not an answer to this interesting question, but what I will often do is run several models (e.g. Poissson, NB, maybe zero-inflated versions) and compare them - both on AIC-type measures and on predicted values.
Comment: [This link](http://www.ats.ucla.edu/stat/sas/output/sas_poisson_output.htm) might be of interest. Specially the section "Criteria For Assessing Goodness Of Fit".
Comment: @Procrastinator The link is a perfect example of what I'm talking about: "Then, if our model fits the data well, the ratio of the Deviance to DF, Value/DF, should be about one. Large ratio values may indicate model misspecification or an over-dispersed response variable; ratios less than one may also indicate model misspecification or an under-dispersed response variable." What's the range of "about 1"? 0.99 to 1.01? 0.75 to 2?
Comment: https://www.r-bloggers.com/count-data-and-glms-choosing-among-poisson-negative-binomial-and-zero-inflated-models/ also has some information about how to answer this question, though @StasK's response covers it well enough.
Answer: 10 is large... 1.01 is not. Since the variance of a $\chi^2_k$ is $2k$ (see Wikipedia), the standard deviation of a $\chi^2_k$ is $\sqrt{2k}$, and that of $\chi^2_k/k$ is $\sqrt{2/k}$. That's your measuring stick: for $\chi^2_{100}$, 1.01 is not large, but 2 is large (7 s.d.s away). For $\chi^2_{10,000}$, 1.01 is OK, but 1.1 is not (7 s.d.s away).
Comment: For future reference you can, instead of the prefix / apology about being an asshole thing, just state the information and a reference. It would probably save you typing, and make you appear *less* of an asshole, which might be a novel experience.
Comment: "so $\chi^2_k/k$ has a standard deviation of $\sqrt{2/k}$" can you direct me to somewhere that demonstrates this please?
Comment: https://www.amazon.com/Encyclopedia-Statistical-Sciences-Applications-Statistics/dp/0471150444. Sorry to be an asshole, but that's a reference distribution in statistical inference; if you don't understand it, you should not be working with generalized linear models such as Poisson.
Comment: See edit and the wikipedia reference. I have volunteered a few hundred answers over a few years, so I admit it is a bit difficult for me to have a really novel experience.
Answer: Asymptotically the deviance should be chi-square distributed with mean equal to the degrees of freedom.  So divide it by its degrees of freedom & you should get about 1 if the data is not over-dispersed. To get a proper test just look up the deviance in chi-square tables - but note (a) that the chi square distribution is an approximation & (b) that a high value can indicate other kinds of lack of fit (which is perhaps why 'around 1' is considered good enough for government work).


Uniformly bounded partial sums of $\sum f'_n$ imply uniform convergence $\sum f_n$?

Question: Suppose $f_n: [a,b] \to \mathbb{R}$ is a sequence of differentiable functions where the series $\sum_n f_n(x_0)$ converges at one point. By Theorem 7.17 in Rudin (Principles of Mathematical Analysis) I conclude the series $\sum_n f_n(x)$ converges  uniformly to some function when the series $\sum_n f'_n(x)$ converges uniformly on $[a,b]$.
What if I know that $\sum_{n} f_n(x)$ converges for each $x \in [a,b]$ but just that partial sums $\sum_{n=0}^N f'_n(x)$ are bounded uniformly (but maybe not converging).  Is it still true that $\sum_n f_n(x)$ converges uniformly?
If not can someone please show me a counterexample.
Answer: Uniform convergence of $\sum f_n'$ is much stronger than what is needed to guarantee uniform convergence of $\sum f_n$.  Uniform boundedness of the partial sums is sufficient.
Suppose $\sum_{n=0}^ \infty f_n(x)$ converges pointwise and
$$\tag{*} \left|\sum_{n=0}^m f'_n(x)\right| \leqslant B$$
for all $x \in (a,b)$ and all $m \in \mathbb{N}.$
Take a partition $a = x_0 < x_1 < \ldots x_r = b$ where $x_k - x_{k-1}  < \epsilon/(2B)$.  We have convergence of $\sum f_n(x)$  at the $r+1$ endpoints, and, hence,   there exists a positive integer $N$ such that for all $p > m > N$ we have
$$|g(x_k)| := \left|\sum_{n = m+1}^{p} f_n(x_k) \right| < \frac{\epsilon}{2} \quad (k = 0,1,\ldots,r)$$
For any $x \in (a,b)$ there is a closest point $x_k$ such that $|x-x_k| < \epsilon/(4B)$. By the reverse triangle inequality and MVT, we have for some $\xi$ between $x$ and $x_k$,
$$|g(x)| \leqslant |g(x_k)| + |g(x) - g(x_k)| = |g(x_k)| + |g'(\xi)||x- x_k| \leqslant \frac{\epsilon}{2} + \frac{\epsilon}{4b} |g'(\xi)|$$
The inequality (*) leads to $|g'(\xi)| = \left|\sum_{n = m+1}^{p} f'_n(\xi) \right| \leqslant 2B$ and it follows that for all $x \in (a,b)$,
$$|g(x)| = \left|\sum_{n=m+1}^{p}f_n(x)\right| < \epsilon$$


how to send push notification via location through one signal plugin in wordpress(wordpress-admin)

Question: I have no idea how to implement this plugin.
My idea is, how to implement one signal plugin(in wordpress) could send push notification via location to my android studio app users.
I want to group my app users via location so that only in that area can receive notification.
Is there any best idea to configure onesignal plugin?
Comment: Please edit your question and add what you have tried so far.
Comment: Please review [How do I ask a good question](https://stackoverflow.com/help/how-to-ask). Before posting, ***you are expected to have researched your issue and made a good attempt to write the code yourself***. If you get stuck on something *specific*, come back and include a summary of what you have tried and the relevant code in a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Please read [How much research effort is expected of Stack Overflow users](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users)
Answer: Please Read The api documentation for one signal post push notification.
first you need to create segment fro your backend of the one signal then use below code for send push notification.
<code><?PHP
function sendMessage(){
    $content = array(
        "en" => 'Your Push notification message'
        );

    $fields = array(
        'app_id' => "------------- Your App Id ----------",
        'included_segments' => array('Your Segment Name'),
  'data' => array("foo" => "bar"),
        'contents' => $content
    );

    $fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
                                               'Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
</code>


Need help understanding the logical structure behind solving an equation?

Question: Suppose I have an equation $f(x) = 0$, and I know the solution exists. The solution is $x = a$ (I don't know the actual solution to begin with, I just know it exists). I perform a series of $irreversible$ operations and arrive at the answer:
$f(x) = 0 \implies \cdots = \cdots \implies \cdots = \cdots \implies x = a$
which is just a big $f(x) = 0 \implies x = a$.
Since the operations are irreversible, we cannot go in the other direction and claim $ x = a  \implies f(x) = 0$
Nevertheless, we know that the solution is $a$, so if we plug in $a$ into $f$ we get zero. But hold on a minute, the statement "if we plug in $a$ into $f$ we get zero" really means $x = a \implies f(x) = 0$; we just went in the other direction, which is something we said we couldn't do!
What is wrong here? Does the fact that $f(x) = a$ has a solution imply that there must be a reversible series of steps between $f(x) = a$ and $x = a$?
Edit: A condensed version
1) We know $f(x) = 0$ has a solution.
2) We can prove $f(x) = 0 \implies x = a$ using irreversible steps.
3) Now that we computed what $a$ actually is, by 1) we know that $x = a \implies f(x) = 0$ is true. Does it follow now that there exists another method to solve the equation using purely reversible steps?
Comment: `I know the solution exists and it is x=a` What is that supposed to mean exactly? Taken at face value, you know a priori that $x=a$ is *the* root, so the rest of the question becomes immaterial.
Comment: @dxiv Sorry, I mean that all I know is a root exists; its value is $a$, but I don't know that to begin with.
Comment: @vagoberto I can't think of such an example for equations, but this can happen for inequalities. For example, suppose you know that $x > |a| + |b|$. Using the triangle inequality, you can conclude that $x > |a+b|$. But if you start from  $x > |a+b|$, you cannot go backwards and conclude $x > |a| + |b|$.
Comment: `all I know is a root exists` Do you know it is unique? The question says "***the*** solution", which would tend to imply that.
Comment: @dxiv Yes for simplicity's sake, we can assume we know there is one unique root.
Answer: $f(x) = 0 \Longrightarrow x = a$ tells you that if $x$ happens to be a root of $f$ then $x$ must be equal to $a$. In other words, the only possibility for a root of $f$ is $a$. However, this implication does not guarantee that $a$ is in fact a root. That's why you need to plug $a$ into $f$ and see whether or not you get zero.
Comment: But I am already given that $f$ has a root; so if we proved $f(x) = 0 \implies x = a$ then $a$ $must$ be a root, no?
Comment: Well then yes. Let $\mathcal{S}$ be the logical implication "$f(x) = 0 \Longrightarrow x = a$ for any $x$ in the domain of $f$". Next suppose that $f$ has a root - say it is the element $x_0$ in the domain of $f$. By definition of what it means to be a root, it must be that $f(x_0) = 0$. Then by the logical implication $\mathcal{S}$, it follows that $x_0 = a$. Thus $a$ is a root
Answer: You have derived a necessary condition for $f(x)=0$, namely that $x=a$. It is, however, still possible that $a$ is not actually a root of $f$, i.e. it need not be the case that $x=a \Rightarrow f(x)=0$ .
For example, $a$ might be outside of the original domain of $f$ and $f(a)$ might not even be properly defined. Imagine $f(x)=x$ where $f: [1,2] \rightarrow \mathbb{R}$ and look for $f(x)=0$.
Comment: You didn't say in the original question that you assumed the existence of a root. By making all these additional assumptions, you seem to be assuming
reversibility. If there is a root (this is a separate statement from your derivation and thus not part of it) and if additionally $f(x=a)=0$, then $a$ is a root, no matter how you derived $a$. Do you have an example where a root exists (i.e. you can proof existence of a root) and you can create an irreversible solution to $f(x)=0$?
Comment: But I am already given that $f$ has a root; so if we proved $f(x) = 0 \implies x = a$ then $a$ $must$ be a root, no?
Comment: Also see my comment on dxiv's answer.
Comment: I have edited the question a few times, but I did mention in the original version that I know a root exists. To address your question, I could not find such an example; hence the last question in the original post: "Does the fact that $f(x)=a$ has a solution imply that there must be a reversible series of steps between $f(x)=a$ and $x=a$?"
Answer: [ EDIT ] Original answers remains in the edit history, but after clarifications given in the comments, the question appears to be (paraphrased):

Assuming that $f(x)=0$ has a unique solution, and provided we prove that $f(x)=0 \implies x=a\,$, is that sufficient to prove that $a$ is the unique solution, or is it still necessary to verify that $a$ does in fact satisfy $f(a)=0\,$?

The answer to this question is "the former" i.e. $f(x)=0 \implies x=a\,$ is sufficient to prove that $a$ is the unique root.
That's because any series of irreversible (but otherwise correct) operations can introduce additional roots, but can never discard a legitimate root. Therefore if $f(x)=0 \implies x \in A=\{a,b,c,\cdots\}$ then those $a,b,c,\cdots$ values are not all guaranteed to be roots of the original equation, but all the actual roots are guaranteed to be in $A$.
In the given case, however, the potential solution set $A=\{a\}$ contains a single value and, since it's been assumed that the equation has in fact one unique root, then that root must be $a$.
Comment: OP commented in response to our answers that he wants to assume the existence of such a root prior to the derivation, in which case this example doesn't work. I think the assumption of the root + the derivation of a necessary condition, does in fact imply that you know $f(a)=0$ but this is because the additional premise is circumventing the one-sided derivation via a modus ponens argument. I.e. We know that "If $f$ has a root, it is $a$" and we know "$f$ has a root" (premise), thus we do in fact know $a$ is a root of $f$.
Comment: @TimonG. I am as confused as anybody about the finer points of the question. I just posted a request for clarification under the OP.
Comment: When you plug $a$ into $f(\cdot)$ and get $f(a)=0$ you get merely $f(a)=0$---not a general $f(x)=0$ for arbitrary $x$.
Comment: dxiv, the tagging system may be broken I believe. Just letting you know that I responded to your comment above. Please let me know if there is anything else which needs clarification. I will try to condense it here a little bit: 1) We know $f(x) = 0$ has a solution. 2) We can prove $f(x) = 0 \implies x = a$ using irreversible steps. 3) Now that we computed what $a$ actually is, by 1) we know that $x = a \implies f(x) = 0$ is true. Does it follow now that there exists another method to solve the equation using purely reversible steps?
Answer: This is impossible to answer in any rigorous way without having a precise definition of the sort of "steps" you want to consider.  But basically, the answer is no.
It happens all the time in math that we can separately prove $P\Rightarrow Q$ and $Q\Rightarrow P$, but there is no direct way to prove $P\Leftrightarrow Q$ in both directions at once.  So there is no reason to expect that just because you can prove both $f(x)=0\Rightarrow x=a$ and $x=a\Rightarrow f(x)=0$, you can prove $f(x)=0\Leftrightarrow x=a$ by a series of reversible steps.  After all, any mathematical statement at all can be encoded in equations like this by defining your function $f$ appropriately.
Comment: Thank you very much for your answer. I think it pretty much answers the question, but tomorrow I will need to exaime the answer in the context of the problem I was solving (I am very tired now)


Calculating Confidence intervals of marginal means for a linear mixed model using emmeans package

Question: I have built this model in R:
library(emmeans)
library(lmerTest)
mixed_age_interaction = lmer(basdai ~ 1 + gender + time + age +
                               gender*time + time*age + gender*age +
                               gender*time*age + (1|ID) + (1|country), data = dat, REML = F, control=lmerControl(optimizer="bobyqa"))

In this model, I am predicting the treatment response basdai (scale 0 to 100), using gender (male/female), time (0, 0.5, 1 and 2 years, time as a categorical variable), age (18-90 years), and the two-way and three-way interactions of these variables. The linear mixed model takes into account correlations within subjects and subjects within countries.
I used the following code to plot the relationship between sex, time and age:
emmip(basdai_age,~ gender ~ time | age, at = list(age = c(20, 40, 60, 80)), plotit= TRUE)

This gives me the following plot (blue = female, red = male):

The plot looks good, although it may be confusing for viewers to see that time is not plotted at the 1.5 year mark since it is not a measured category. Moreover, it would be helpful to add labels at the top of each subplot indicating the age group being displayed (e.g. "20 years", "40 years", etc.) to make it more clear.
Therefore I have tried to substract the data from the emmip() function by using plotit = FALSE, and subsequently trying to create the plot to my liking. However, I am struggling to calculate the confidence intervals of the estimated marginal means. I asked chatGPT for help which has provided me with the formula, but the CI's seem to small.
Here is what I have tried so far:
library(ggplot2)
df_basdai_age <- emmip(basdai_age,~ gender ~ time | age, at = list(age = c(20, 40, 60, 80)), facetlab = "label_both", plotit= FALSE)
df_basdai_age <- emmip(basdai_age,~ gender ~ time | age, at = list(age = c(20, 40, 60, 80)), facetlab = "label_both", plotit= FALSE)
df_basdai_age$age = as.factor(df_basdai_age$age)
levels(df_basdai_age$age) <- c("20 years", "40 years", "60 years", "80 years")
df_basdai_age$time = as.numeric(as.character(df_basdai_age$time))
df_basdai_age <- mutate(df_basdai_age, ymin = yvar - qt(0.975, df)*(SE/sqrt(df)))
df_basdai_age <- mutate(df_basdai_age, ymax = yvar + qt(0.975, df)*(SE/sqrt(df)))

#Plot the graph
p <-
  ggplot(df_basdai_age, aes(x = time, y = yvar, color = tvar)) +
  geom_line(size = 1) +
  geom_point() +
  geom_errorbar(aes(ymin=ymin, ymax=ymax), width=.05) +
  labs(x = "Time (years)", y = "") +
  theme_cowplot() +
  facet_wrap(~ age, nrow = 2) +  theme(legend.position="none")

# show plot
p

This is the resulting plot:

Here is the complete dataset:
structure(list(gender = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), levels = c("Male", "Female"
), class = "factor"), time = c(0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.5,
0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2,
2, 2, 2, 2, 2), age = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L,
4L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 1L, 1L, 2L, 2L, 3L, 3L, 4L,
4L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L), levels = c("20 years", "40 years",
"60 years", "80 years"), class = "factor"), yvar = c(53.2222132545591,
55.644671238144, 53.979760945038, 58.0003674613788, 54.737308635517,
60.3560636846136, 55.4948563259959, 62.7117599078483, 18.8785653284777,
27.3140001897482, 25.9035670388476, 33.6311637386693, 32.9285687492176,
39.9483272875904, 39.9535704595875, 46.2654908365116, 17.1280381612022,
25.6617577361121, 23.8414745169542, 31.7675512043731, 30.5549108727061,
37.8733446726342, 37.268347228458, 43.9791381408953, 15.8476044974251,
25.0206920526655, 23.029545900933, 30.9838114430519, 30.2114873044409,
36.9469308334382, 37.3934287079488, 42.9100502238246), SE = c(1.48085388286971,
1.54315837900391, 1.41163641601991, 1.42678010979953, 1.4630053643472,
1.49892114510165, 1.62355480278176, 1.73623936576435, 1.47800196744245,
1.54052855366631, 1.41101870318731, 1.42580231659991, 1.46095633844491,
1.4978877623696, 1.61701847301061, 1.73363627458762, 1.48984952535246,
1.58248569215204, 1.41398647326204, 1.43575219607306, 1.47296775812952,
1.52128548685686, 1.65241653887761, 1.80638768204503, 1.51339032203046,
1.65536350490358, 1.41906539783371, 1.45202624858626, 1.4940999289118,
1.56932417176622, 1.71642484529658, 1.95023658100379), df = c(19.1992529938252,
22.636661796014, 15.8557024206515, 16.5459552649169, 18.2937320570655,
20.157114181664, 27.7433329713143, 36.2839788594381, 19.051888835057,
22.483155277679, 15.828184146664, 16.5012376120077, 18.1918644929504,
20.10278950016, 27.3001430927299, 36.0701453085591, 19.669221418473,
25.0336574427524, 15.9616355502659, 16.9666087914172, 18.7980095965655,
21.3885230873732, 29.7715565509346, 42.514368203954, 20.9429853491516,
29.973619949575, 16.1930278685159, 17.7496566912749, 19.9012388133609,
24.2214091721269, 34.6602465546453, 57.7544903350949), tvar = structure(c(1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), levels = c("Male",
"Female"), class = "factor"), xvar = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), levels = c("0",
"0.5", "1", "2"), class = "factor"), ymin = c(52.5153436652014,
54.9731205471491, 53.2276742716765, 57.258776742029, 54.0195058924355,
59.6599914019999, 54.8631940181502, 62.1273437446853, 18.1699669372756,
26.6410506766869, 25.1510488995009, 32.8889200571732, 32.2094835380351,
39.2516759650496, 39.3188965541991, 45.6801042113467, 16.4265441774652,
25.0104024242387, 23.0910485329519, 31.0320361368517, 29.8433247363632,
37.1900266089296, 36.649658499789, 43.4202483189333, 15.1597661980371,
24.4031685566235, 22.2826943822545, 30.2589939247067, 29.5126365026472,
36.2891347676435, 36.8013488320248, 42.3963183501654), ymax = c(53.9290828439169,
56.316221929139, 54.7318476183996, 58.7419581807286, 55.4551113785984,
61.0521359672273, 56.1265186338416, 63.2961760710114, 19.5871637196797,
27.9869497028096, 26.6560851781943, 34.3734074201655, 33.6476539604,
40.6449786101312, 40.5882443649759, 46.8508774616764, 17.8295321449393,
26.3131130479854, 24.5919005009564, 32.5030662718946, 31.2664970090489,
38.5566627363388, 37.8870359571269, 44.5380279628573, 16.5354427968132,
25.6382155487075, 23.7763974196115, 31.7086289613971, 30.9103381062346,
37.6047268992329, 37.9855085838727, 43.4237820974838)), estName = "yvar", pri.vars = c("gender",
"time", "age"), adjust = "none", side = 0, delta = 0, type = "link", mesg = "Degrees-of-freedom method: satterthwaite", row.names = c(1L,
2L, 9L, 10L, 17L, 18L, 25L, 26L, 3L, 4L, 11L, 12L, 19L, 20L,
27L, 28L, 5L, 6L, 13L, 14L, 21L, 22L, 29L, 30L, 7L, 8L, 15L,
16L, 23L, 24L, 31L, 32L), labs = list(xlab = "Levels of time",
    ylab = "Linear prediction", tlab = "gender"), vars = list(
    byvars = "age", tvars = "gender"), class = "data.frame")

Question: If I have the standard error, marginal mean, degrees of freedom, how do I calculate the ymin and ymax for a marginal mean of a linear mixed model? Is the formula used here correct?
Comment: Just use `emmeans` instead of `emmip`: `emmeans(mixed_age_interaction, ~gender*time*age)`. This will give you all combinations together with the confidence intervals. Use this to make the plot to your liking. If you insist calculating it manually, the formula would be: `yvar + qt(0.975, df)*SE` (for the upper limit), I think.
Comment: @COOLSerdash thanks, I prefer to do it manually because then I don't need to transform the data from this format `emmean(mixed_age_interaction, ~gender*time*age)` to a format I can use for data visualization. Your formula seems to correspond with the CI's calculated with `emmean(mixed_age_interaction, ~gender*time*age)`. If you want, you can reply this as an answer and I can give you the bounty.
Answer: You can see the correct standard errors and confidence intervals by doing
emmeans(basdai_age, ~ gender * time | age,
    at = list(age = c(20, 40, 60, 80)))

Your attempts to re-engineer the standard errors is incorrect. They are correct as they stand. You are trying to interpret standard error as if it is a standard deviation in a simple univariate situation, where standard errors are computed as $s/\sqrt{n}$. But this is not a simple univariate model and that is the wrong formula. emmeans() already knows the right one, so leave it alone.


How to get the rendered view as a string in express.js?

Question: I want to store the rendered view res.render as string to a variable and use node-html-pdf package to print pdf:
var pdf = require('html-pdf');
var html = res.render('my_view', res.view_data); // not work

pdf.create(html).toStream(function(err, stream){
    stream.pipe(fs.createWriteStream('./foo.pdf'));
});

Answer: You'll need the app instance of express application.
var appInstance = express();
appInstance.set('views', path.join(__dirname, 'views')); // Set this relative to your file
appInstance.set('view engine', 'pug'); // Or whatever your view engine is

appInstance.render("my_view", view_data, (err, html) => {

  pdf.create(html).toStream(function(err, stream){
    stream.pipe(fs.createWriteStream('./foo.pdf'));
  });

});

Comment: Thank! Btw, I just found that `appInstance` can also obtain via `res.app`.