Integration of $\int\frac{1}{x^{4}+1}\mathrm dx$

Question: I don't know how to integrate $\displaystyle \int\frac{1}{x^{4}+1}\mathrm dx$. Do I have to use trigonometric substitution?

Many duplicate posts link to this one as the target. (Those posts were merged into this one, which is the source of the many answers.)
Comment: About 9 years ago I prepared a detailed evaluation of this integral, and a .pdf file of my write-up can be found at this [14 Oct. 2009 Math Forum sci.math post](http://mathforum.org/kb/message.jspa?messageID=6868513).
Comment: Related problem (definite integral): http://math.stackexchange.com/q/43457/23353 (but ***not*** duplicate!)
Comment: Hypergeometric ... $x\;{}_2F_1(\frac14,1;\frac54;-x^4)$
Comment: Reviewers: note that many duplicate posts link to this one as the target.
Answer: I think you can do it this way.
\begin{align*}
\int \frac{1}{x^4 +1} \ dx & = \frac{1}{2} \cdot \int\frac{2}{1+x^{4}} \ dx \\\
&= \frac{1}{2} \cdot \int\frac{(1-x^{2}) + (1+x^{2})}{1+x^{4}} \ dx \\\ &=\frac{1}{2} \cdot \int \frac{1-x^2}{1+x^{4}} \ dx + \frac{1}{2} \int \frac{1+x^{2}}{1+x^{4}} \ dx \\\ &= \frac{1}{2} \cdot -\int \frac{1-\frac{1}{x^2}}{\left(x+\frac{1}{x}\right)^{2} - 2} \ dx  + \text{same trick}
\end{align*}
Answer: $$\int\frac 1{1+x^4}dx=\frac12\int\frac{1+x^2+1-x^2}{1+x^4}dx$$
$$\int\frac{1+x^2}{1+x^4}dx=\int\frac{\frac1{x^2}+1}{\left(x-\frac1x\right)^2+2}dx$$
Set $x-\frac1x=\sqrt2\tan\phi$
$$\int\frac{1-x^2}{1+x^4}dx=-\int\frac{1-\frac1{x^2}}{\left(x+\frac1x\right)^2-2}dx$$
Set $x+\frac1x=\sqrt2\sec\psi$
Reference: Trigonometric substitution
Answer: HINT :
$$x^4+1
 =(x^2+1)^2-2x^2
 =(x^2+\sqrt 2x+1)(x^2-\sqrt2x+1)$$
Answer: My hint:
\begin{align}
\int \frac{1}{1+x^4}dx
&=\frac{1}{2}
\left[\int \frac{1+x^2}{1+x^4}dx+\int\frac{1-x^2}{1+x^4}dx\right]
\\ &=
\frac{1}{2}\left[
\int \frac{1}{\left(x-\frac{1}{x}\right)^2+2}
d\left(x-\frac{1}{x}\right)
+\int\frac{1}{\left(x+\frac{1}{x}\right)^2-2}
d\left(x-\frac{1}{x}\right)
\right]
\\ &=
\frac{1}{2}\left[\frac{1}{\sqrt{2}}\arctan\frac{x^2-1}{\sqrt{2}x}+\frac{}{2\sqrt{2}}\ln\frac{x^2-\sqrt{2}x+1}{x^2+\sqrt{2}x+1}\right]+\text{Constant}
\end{align}
Answer: You can factor $x^4+1 = (x^2 + \sqrt{2} x + 1) (x^2 -\sqrt{2}x + 1)$. This allows you to write the integrand as $\frac{a_1 x + b_1}{x^2 + \sqrt{2}x + 1} + \frac{a_2 x + b_2}{x^2- \sqrt{2}x + 1}$.  You would then rewrite the denominator in the form of $(x-u)^2 + v$ and rewrite the numerator as $a_i (x-u) + w$, from which you can do a change of variable to integrate essentially $x/(x^2+1)$ and $1/(x^2+1)$.
Answer: HINT :
Use
$$x^4+1=(x^2+1)^2-(\sqrt 2x)^2=(x^2+\sqrt 2x+1)(x^2-\sqrt 2x+1)$$
to get
$$\begin{align}\int\frac{dx}{1+x^4}&=\int\frac{\frac{1}{2\sqrt 2}x+\frac 12}{x^2+\sqrt 2x+1}dx+\int\frac{-\frac{1}{2\sqrt 2}x+\frac 12}{x^2-\sqrt 2x+1}dx\\&=\frac{1}{2\sqrt 2}\int\frac{x+\sqrt 2}{x^2+\sqrt 2x+1}dx-\frac{1}{2\sqrt 2}\int\frac{x-\sqrt 2}{x^2-\sqrt 2x+1}dx\\&=\frac{1}{\sqrt 2}\int\frac{x+\sqrt 2}{(\sqrt 2x+1)^2+1}dx-\frac{1}{\sqrt 2}\int\frac{x-\sqrt 2}{(\sqrt 2x-1)^2+1}dx.\end{align}$$
Here, set $\sqrt 2x+1=\tan\alpha$ for the first and set $\sqrt 2x-1=\tan\beta$ for the second.
Comment: Why don't you delete your other answer that is exactly the same as the first two lines of this answer?
Answer: By partial fractions,
$$ \frac{1}{1+x^4} = \frac{1}{2\sqrt{2}}\left(\frac{x + \sqrt{2}}{x^2 + \sqrt{2}x + 1} - \frac{x - \sqrt{2}}{x^2 - \sqrt{2}x + 1}\right). $$
The rest is standard and not a great deal of fun. Complete the squares at the bottom and make the natural substitutions.
Answer: Expand $\frac{1}{1+x^{4}}$ into partial fractions. For this purpose you need
to factorize the polynomial in the denominator. You can proceed by writing it as a product of four linear terms
\begin{equation*}
x^{4}+1=(x-x_{1})(x-x_{2})(x-x_{3})(x-x_{4})
\end{equation*}
where $x_{1},x_{2},x_{3},x_{4}$ are its complex roots. Since
\begin{equation*}
x^{4}+1=0\Leftrightarrow x^{4}=-1=\cos \pi +i\sin \pi
\end{equation*}
the four roots are
\begin{eqnarray*}
x_{1} &=&\cos \left( \frac{\pi }{4}\right) +i\sin \left( \frac{\pi }{4}
\right) =\frac{\sqrt{2}}{2}(1+i) \\
x_{2} &=&\cos \left( \frac{3\pi }{4}\right) +i\sin \left( \frac{3\pi }{4}
\right) =\frac{\sqrt{2}}{2}(-1+i) \\
x_{3} &=&\overline{x}_{2} \\
x_{4} &=&\overline{x}_{1}.
\end{eqnarray*}
Rewrite $x^{4}+1$ as a product of quadratic terms, by grouping the factors $
(x-x_{1}),(x-x_{4})=(x-\overline{x}_{1})$ and $(x-x_{2}),(x-x_{3})=(x-
\overline{x}_{2})$
\begin{eqnarray*}
x^{4}+1 &=&\left[ (x-x_{1})(x-\overline{x}_{1})\right] \left[ (x-x_{2})(x-
\overline{x}_{2})\right]  \\
&=&\left( x^{2}-\sqrt{2}+1\right) \left( x^{2}+\sqrt{2}x+1\right)
\end{eqnarray*}
Find the constants $A,B,C,D$ such that
\begin{equation*}
\frac{1}{\left( x^{2}-x\sqrt{2}+1\right) \left( x^{2}+x\sqrt{2}+1\right) }=
\frac{A+Bx}{x^{2}-x\sqrt{2}+1}+\frac{C+Dx}{x^{2}+\sqrt{2}x+1}.
\end{equation*}
To evaluate
\begin{equation*}
\int \frac{1}{x^{2}\mp \sqrt{2}x+1}dx
\end{equation*}
complete the square in the denominator (see this answer of mine)
\begin{equation*}
x^{2}\mp \sqrt{2}x+1=\left( x\mp \frac{\sqrt{2}}{2}\right) ^{2}+\left( \frac{\sqrt{
2}}{2}\right) ^{2}
\end{equation*}
and make the substitutions
\begin{equation*}
x\mp \frac{\sqrt{2}}{2}=\frac{\sqrt{2}}{2}t.
\end{equation*}
To compute the remaining integrals rewrite them as
\begin{eqnarray*}
\int \frac{x}{x^{2}\mp \sqrt{2}x+1}dx &=&\frac{1}{2}\int \frac{2x\mp \sqrt{2}}{
x^{2}\mp \sqrt{2}x+1}dx\pm\frac{\sqrt{2}}{2}\int \frac{1}{x^{2}\mp \sqrt{2}x+1}dx.
\end{eqnarray*}
Answer: As in the question linked in Hans Lundmark's comment, you can factorise the denominator as
$$x^4+1=(x^2+x\sqrt2+1)(x^2-x\sqrt2+1)\ .$$
However you can make the resulting integral a bit less painful by getting all the surds outside the integral sign: first substitute
$$u=x\sqrt2\ .$$
Then we have
$$4(x^4+1)=u^4+4=(u^2+2u+2)(u^2-2u+2)$$
and the integral is evaluated by (relatively) simple partial fractions:
$$\eqalign{I
  &=\int\frac{dx}{x^4+1}\cr
  &=2\sqrt2\int\frac{du}{(u^2+2u+2)(u^2-2u+2)}\cr
  &=\frac{1}{4\sqrt2}
    \int\Bigl(\frac{2u+4}{u^2+2u+2}-\frac{2u-4}{u^2-2u+2}\Bigr)du\cr
  &=\frac{1}{4\sqrt2}
    \bigl(\ln(u^2+2u+2)-\ln(u^2-2u+2)\cr
  &\qquad\qquad\qquad{}+2\tan^{-1}(u+1)+2\tan^{-1}(u-1)\bigr)+C\ .\cr}$$
You can now simplify the log and inverse tan terms (optional) and substitute back for $x$.
Answer: the key is to show $(x^2-\sqrt{2}x+1)(x^2+\sqrt{2}x+1)=x^4+1$
Answer: Directly by Sophie Germain's Identity or:
$$x^4+1=x^4+2x^2+1-2x^2=(x^2+1)^2-(\sqrt2x)^2=(x^2-\sqrt2x+1)(x^2+\sqrt2x+1)$$
After splitting the initial fraction we get:
$$ \int \frac{1}{x^4 +1} \ dx = \int \frac{\frac{x}{2\sqrt2}+\frac{1}{2}}{x^2+\sqrt2x+1} \ dx+\int \frac{\frac{-x}{2\sqrt2}+\frac{1}{2}}{x^2-\sqrt2x+1} \ dx=$$
$$ \frac{\sqrt2}{8} \int \frac{2x+2\sqrt2}{x^2+\sqrt2x+1} dx-\frac{\sqrt2}{8} \int \frac{2x-2\sqrt2}{x^2-\sqrt2x+1} dx=$$
$$\frac{\sqrt2}{8}
\int \frac{2x+\sqrt2}{x^2+\sqrt2x+1} dx
+\frac{1}{4} \int \frac{1}{x^2+\sqrt2x+1} dx
$$
\qquad-\frac{\sqrt2}{8}\int \frac{2x-\sqrt2}{x^2-\sqrt2x+1} dx
+\frac{1}{4}
\int\frac{1}{x^2-\sqrt2x+1}dx
=$$
$$\frac{\sqrt2}{8}\left( \int \frac{2x+\sqrt2}{x^2+\sqrt2x+1} dx -\int \frac{2x-\sqrt2}{x^2-\sqrt2x+1} dx \right)+$$
$$\frac{\sqrt2}{4} \left( \int \frac{\sqrt2}{(\sqrt2x+1)^2+1} dx+\int \frac{\sqrt2}{(\sqrt2x-1)^2+1} dx \right)=$$
$$\frac{\sqrt2}{8} \left(\ln(x^2+\sqrt2x+1)-\ln(x^2-\sqrt2x+1) \right) +\frac{\sqrt2}{4} \left(\arctan(\sqrt2x+1)+ \arctan(\sqrt2x-1)\right)+C$$
$$=\frac{\sqrt2}{8} \ln\frac{(x^2+x\sqrt2+1)}{(x^2-x\sqrt2+1)}+\frac{\sqrt2}{4}\arctan\frac{x\sqrt2}{1-x^2}+C.$$
Q.E.D.
Answer: It is posiible to use  faktorization
$1+x^4=(1-\sqrt{2}x+x^2)(1+\sqrt{2}x+x^2)$
and partial fractions.
Answer: Hint
Use $$1+t^4 = (1 + \sqrt{2} t + t^2 ) \times (1 - \sqrt{2} t + t^2 )$$ and decompose in partial fractions. You will arrive to much simpler antiderivatives.
I am sure that you can take from here.
Answer: There are two (three) ways to go. One, assume
$$x^4+1=(x^2+ax+1)(x^2-ax+1)$$
You'll get that
$${x^4} + 1 = {x^4} + \left( {2 - {a^2}} \right){x^2} + 1$$
Then $a=\sqrt 2$ (or the other, by symmetry)
$${x^4} + 1 = {x^4} + 1 = \left( {{x^2} + \sqrt 2 x + 1} \right)\left( {{x^2} - \sqrt 2 x + 1} \right)$$
The other ${x^2} = \tan \theta $, but it might get messy, unless you know how to use the Weierstrass substitution for example.
$$\int {\frac{{dx}}{{{x^4} + 1}}}  = \int {\frac{{\left( {{{\tan }^2}\theta  + 1} \right)d\theta }}{{{{\tan }^2}\theta  + 1}}} \frac{1}{{2\sqrt {\tan \theta } }} = \int {\sqrt {\frac{{\cos\theta }}{{\sin\theta }}} \frac{{d\theta }}{2}} $$
$$\int {\sqrt {\frac{{\frac{{1 - {u^2}}}{{1 + {u^2}}}}}{{\frac{{2u}}{{1 + {u^2}}}}}} \frac{{du}}{{1 + {u^2}}}}  = \int {\sqrt {\frac{{1 - {u^2}}}{{2u}}} \frac{{du}}{{1 + {u^2}}}} $$
However, Chandrasekar's is the best way to go, if you can figure it out.
Comment: Does the last integral succesfully figures itself out or did you just not want to work it out and knew it works?
Answer: The steps are as follows:
1) Decompose $\frac{1}{1+x^{4}}$ using partial fractions (it can be factored using an identity of Sophie Germain)
2) You should have a linear function in each numerator and a quadratic in each denominator. Separate into the form $\frac{const}{quadratic}+\frac{const\cdot x}{quadratic}$
3) Complete the square on this quadratic.
4) To integrate the first form, make a simple substitution to transform the integrand into the form $\frac{1}{1+u^{2}}$, which is the derivative of $\tan^{-1}(x)$.
5) For the second, make another substitution to transform the integrand into the form $\frac{1}{1+v}$, which has antiderivative $\ln(1+v)$.
Be very careful with tiny algebraic slips, and keep track of your constants.
Answer: Hints:
$$x^4+1=(x^2+\sqrt2\,x+1)(x^2-\sqrt2\,x+1)$$
Partial Fractions, and yes: you'll need arctangents.
Comment: Or factor over the complex numbers, and your partial fractions will give you (complex) logarithms.
Answer: What Chandrasekhar wrote is a very nice trick. I'll offer you here a more "standard" one:
$$x^4+1=(x^2+\sqrt{2}x+1)(x^2-\sqrt{2}x-1)\Longrightarrow \frac{1}{x^4+1}=\frac{Ax+B}{x^2+\sqrt{2}x+1}+\frac{Cx+D}{x^2-\sqrt{2}x-1} $$and now do partial fractions and find the coefficients $\,A,B,C,D$
Added...or wait until someone else do it for you, of course.
Answer: HINT (for partial fractions) :
$$
x^4+1=(x^2+\sqrt2x+1)(x^2-\sqrt2x+1).
$$
Comment: It is interesting that $\sqrt{2}$ appears suddenly. I did not manage to separate it into factors.
Comment: $x^4+1$ has 4 complex roots (the 4th roots of $-1$) which come in pairs $w,\bar w$ and $z, \bar z$. Then one sees that $w+\bar w=\pm\sqrt{2}$ and $z+\bar z=\mp\sqrt 2$.
Comment: On a more elementary tune, consider the intermediate step $x^4+1=(x^2+1)^2-2x^2$. Here the appearence of $\sqrt2$ is immediately evident.
Answer: You can use
$$x^4+1=(x^2+1)^2-2x^2=(x^2+1+\sqrt 2x)(x^2+1-\sqrt 2x).$$
Then, find $A,B,C,D$ such that
$$\frac{1}{x^4+1}=\frac{Ax+B}{x^2+1+\sqrt 2x}+\frac{Cx+D}{x^2+1-\sqrt 2x}.$$
You'll find
$$\frac{1}{x^4+1}=\frac{1}{2\sqrt 2}\left\{ \frac{x+\sqrt 2}{x^2+\sqrt2 x+1}+\frac{-x+\sqrt 2}{x^2-\sqrt 2x+1}\right\}.$$
Answer: Let $$I=\int\frac{dx}{x^4+1}$$
Enforce the substitution $x:=\frac{1}{y}\implies dx=-\frac{dy}{y^2}$ so that $$I=-\int\frac{dy}{y^2\left(\frac{1}{y^4}+1\right)}=-\int\frac{dy}{y^2+\frac{1}{y^2}}=-\frac{1}{2}\int\frac{1-\frac{1}{y^2}+1+\frac{1}{y^2}}{y^2+\frac{1}{y^2}}dy\tag1$$
Then observe that $$y^2+\frac{1}{y^2}=\left(y-\frac{1}{y}\right)^2+2=\left(y+\frac{1}{y}\right)^2-2\tag2$$
Now splitting $I$ at the end of $(1)$ into two integrals $$I=-\frac{1}{2}\int\frac{1-\frac{1}{y^2}+1+\frac{1}{y^2}}{y^2+\frac{1}{y^2}}dy=-\frac{1}{2}\int\frac{1-\frac{1}{y^2}}{y^2+\frac{1}{y^2}}dy-\frac{1}{2}\int\frac{1+\frac{1}{y^2}}{y^2+\frac{1}{y^2}}dy\tag3$$
Observe $$\frac{d}{dy}\left(y+\frac{1}{y}\right)=1-\frac{1}{y^2}$$ and $$\frac{d}{dy}\left(y-\frac{1}{y}\right)=1+\frac{1}{y^2}$$ The latter integrals in $(3)$ now become by combining the last identities & $(2)$:$$I=-\frac{1}{2}\int\frac{1-\frac{1}{y^2}}{\left(y+\frac{1}{y}\right)^2-2} dy-\frac{1}{2}\int\frac{1+\frac{1}{y^2}}{\left(y-\frac{1}{y}\right)^2+2} dy=-\frac{1}{2}\left(\int\frac{dt}{t^2-2}+\int\frac{du}{u^2+2}\right)$$
upon the substitutions $t=y+\frac{1}{y}$ and $u=y-\frac{1}{y}$.
$$
I=
-\frac{1}{2}\left(\int\frac{dt}{-2\left(
1-\left( \frac{t}{2} %% should be \sqrt 2 denominator
\right)^2\right)}
+\int\frac{du}{2\left(
\left(\frac{u}{\sqrt{2}}\right)^2+1\right)}
\right)
=-\frac{1}{4}\left(\int\frac{du}{\left(\frac{u}{\sqrt{2}}\right)^2+1}
-\int\frac{dt}{1-\left(\frac{t}{\sqrt{2}}\right)^2}\right)
$$
$$=-\frac{\sqrt{2}}{4}\left(\int\frac{dw}{w^2+1}-\int\frac{dz}{1-z^2}\right)=-\frac{\sqrt{2}}{\sqrt{2^4}}\left(\arctan(w)-\text{arctanh}\right(z))+C
$$
Note that $$w=\frac{u}{\sqrt{2}}=\frac{y-\frac{1}{y}}{\sqrt{2}}=\frac{\frac{1}{x}-x}{\sqrt{2}}$$ and $$z=\frac{t}{\sqrt{2}}=\frac{y+\frac{1}{y}}{\sqrt{2}}=\frac{\frac{1}{x}+x}{\sqrt{2}}$$
Thus $$I=\frac{1}{2\sqrt{2}}\left(\text{arctanh}\left(\frac{\frac{1}{x}+x}{\sqrt{2}}\right)-\text{arctan}\left(\frac{\frac{1}{x}-x}{\sqrt{2}}\right)\right)+C$$


Views Challenge

Question: I have a custom content type called 'Project' that contains a field called 'Category' of type 'List (text)'.
I have created a custom view block that selects all category fields in Projects and used a contextual filter to 'Display a summary', so the block contains an unordered deduped list of the categories.
The block is loaded into a region in a custom template, and output in page.tpl.php using
print render($page['other_menu']);

Unfortunately, the URLs in the menu appear in this form: href="/projects/Culture-%26-Leisure"
I need them to be all lower case and replace -%26- with an underscore like this: href="/projects/culture_leisure"
I can make this happen using preg_replace(), but suspect it's possible to have the view output the URL in the format I require. I just can't figure how to make the view do this.
Comment: Boy it's hard to figure out quite what you're trying to do here. You need to get the links sorted out in the view rather than trying to do it on output. Why do they need to change?
Comment: Wazza, on this site, if you think the answer is good you can acknowledge it by clicking the up arrow.  If you think it is correct and accept it, click the checkmark.  :)
Answer: If I can reverse engineer what you are doing, am I right to assume that you have a project with a title of "Culture & Leisure" that you want linked to /projects/culture_leisure instead of "/projects/Culture-%26-Leisure" ?
If so, on Drupal 6 at least, this looks like a quick change of pathauto punctuation settings as it's the module that changes spaces and punctuation in titles and such into more presentable urls.
Here it's at 'admin/build/path/pathauto' but I am sure you can find it or its equivalent on your Drupal 7 site pretty simply.
There, just look for what it's doing with the ampersand and tell it to delete it instead of leaving it alone (which ends up in it being encoding as %26), tell it to use a '_' as the separator instead of a '-' and, last but not least, to also change everything to lowercase.
That should do it :)

Views Challenge


Realizar chamadas através de um icone no site pela webwiew do app

Question: Como realizar chamadas telefonicas dentro da webView. no site tem o link da intent do discar do telefone.
Ex: quando abro o site pelo app de webview que criei ele não chama a função discar do telefone. Alguem que pode me ajudar?
Answer: Adicione no Manifest:
<uses-permission android:name="android.permission.CALL_PHONE" />

No código faça:
ligar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (ActivityCompat.checkSelfPermission(ligar.getContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
                    + numerodotelefone)));
        }
    });

    TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    txtLi.append(tm.getSimOperatorName() + "\n");
    switch (tm.getPhoneType()) {
        case TelephonyManager.PHONE_TYPE_GSM:
            txtLi.append("GSM \n");
            break;
        case TelephonyManager.PHONE_TYPE_CDMA:
            txtLi.append("CDMA \n");
            break;
    }

O elemento txtLi é um textview que pode ficar invisível, no exemplo eu clico em um botão e então chama a ligação passando o número de telefone.
Comment: Aqui tem uma solução com o próprio html https://pt.stackoverflow.com/questions/45425/como-chamar-a-aplica%C3%A7%C3%A3o-de-ligar-n%C3%BAmero-em-uma-webview?rq=1
Comment: Obrigado Amigo por responder minha pergunta.

Ainda não deu certo mais vou continuar tentando usar o código até conseguir colocar ele no lugar certo.

hora que conseguir venho marca sua resposta como resolvida e votar em sua reputação. obrigado.


docker-compose on ubntu 18.10 the input device is not a TTY error

Question: I installed docker and docker compose in ubuntu 18.10 server, when i execute the command docker compose from terminal it is working, but when i configure a crontab to exexute a command with docker compose, i get this error :"The USER variable is not set. Defaulting to a blank string.the input device is not a TTY"
The USER error is related to an error with docker-compose.yml, juste for using ${USER}.
How can i fix the issue ?
PS: It was working normaly in ubuntu 18.04 server.
Comment: Hi, could you please correct your title to highlight the actual issue you're facing
Comment: What is the command your cron is running? To make a docker exec command a tty, use the -t flag
Answer:
The cron daemon was designed in such a way that it does NOT execute commands within your normal shell environment. This means you cannot use bare commands in cron the way you would from the SSH shell command line. This is because the PATH environment variable is /usr/bin:/bin, and the SHELL environment variable is set to /bin/sh.

Something you can reference: here and here.
So you may have to specify shell environment variable directly in crontab, like
<code>USER=xxx
* * * * * /bin/echo ${USER}
</code>


ES6 dependency of loaded module not found (uncaught typeError) when initiating new instance

Question: I'm learning JS and due to my general lack of knowledge I don't seem to find the correct keywords to google the solution myself.
I am trying to load Leaflet as part of an app, built with ES6 modules.
File structure:
- Home directory
    - index.html
    - /scripts
         - main.js
         - /app
             - mapApp.js
         - /lib
             - leaflet.js

Inside index.html
    ...

    ...

mapApp contains an object, which will be extended to contain methods to alter the map/gui. In its most basic layout mapApp.js contains:
import * as L from "../lib/leaflet/leaflet.js"

function mapApp(container){

    // Fixed values
    var bounds = [
        [50.769562,5.448265], // Southwest coordinates
        [50.801687,5.507624] // Northeast coordinates
    ];

    // Parameters

    this.container = container

    // Map initialize
    this.map = L.map(this.container,{
        zoomControl:false,
        maxZoom:21,
        minZoom:8,
        center:[50.78898,5.4889],
        zoom:14,
        maxBounds: bounds,
        maxBoundsViscosity: 1.0 // Prevents pushback behaviour at bounds
    });
};

finally inside main.js, which might create multiple instances of the mapApp:
import {mapApp} from "./app/mapApp.js";

tester = new mapApp('app')

for the final line (tester = ...) I'm getting an Uncaught TypeError: L.map is not a function.
I can solve this by importing leaflet again in main.js. But that doesn't seem like the right way to go? It seems like a a hassle that I would have to reload 'child/nested' imports throughout the program chain?
What am I not understanding?
Answer: After a ridiculousness amount of time I finally solved it.
I must have somewhere loaded a "L" library, confusing me further.
Turns out the minified leaflet (leaflet.js) can not be used for modules. Instead use the leaflet-src.ecm.js file. See also This question on more details about the .ecm format.
For other people have this, or a similar issue, I propose to also use the solution in this SO question and try to load the module straight from the console. Once it works there, you're good to go (unless like me you're confused with a mistakenly loaded library with the same abbreviation)
TL;DR: the solution is changing import * as L from "../lib/leaflet/leaflet.js" to the correct file, supporting modules: import * as L from "../lib/leaflet/leaflet-src.esm.js"


Navigation Drawer with Custom Button

Question: I am currently trying to set up a search bar for my app that looks like the photo below. Currently I have a widget that works well as the search bar, but I am trying to implement a navigation drawer that uses that button. Is there a way to tie a navigation drawer to it?
Do I need to recreate this widget in an appBar?
I am not sure what the best way to accomplish this is, and I would love some suggestions about how to proceed!

Thanks!
Answer: Use GlobalKey and show the drawer by calling myKey.currentState.openDrawer()
In demo, I also open drawer when click button
full code
<code>import 'package:flutter/material.dart';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: ListenToDrawerEvent(),
    );
  }
}

class ListenToDrawerEvent extends StatefulWidget {
  @override
  ListenToDrawerEventState createState() {
    return new ListenToDrawerEventState();
  }
}

class ListenToDrawerEventState extends State<ListenToDrawerEvent> {
  GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  static final List<String> _listViewData = [
    "Inducesmile.com",
    "Flutter Dev",
    "Android Dev",
    "iOS Dev!",
    "React Native Dev!",
    "React Dev!",
    "express Dev!",
    "Laravel Dev!",
    "Angular Dev!",
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text("Listen to Drawer Open / Close Example"),
        leading: IconButton(
          icon: Icon(Icons.menu),
          onPressed: () {
            _scaffoldKey.currentState.openDrawer();
          },
        ),
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.all(10.0),
          children: _listViewData
              .map((data) => ListTile(
            title: Text(data),
          ))
              .toList(),
        ),
      ),
      body: Column(
        children: <Widget>[
          Center(
            child: Text('Main Body'),
          ),
          RaisedButton(
            padding: const EdgeInsets.all(8.0),
            textColor: Colors.white,
            color: Colors.blue,
            onPressed: () {_scaffoldKey.currentState.openDrawer();},
            child: new Text("open drawer"),
          )
        ],
      ),
    );
  }
}
</code>
Comment: Thank you so much! This worked like a charm!
I also appreciate how detailed your response was:)
Comment: @chunhunghan can you please tell me, I am not using drawer and appbar in my app, how can i open drawer on clicking specific button.
Answer: <code> AppBar(
   leading: Builder(
     builder: (BuildContext context) {
       return IconButton(
         icon: const Icon(Icons.menu),
         onPressed: () { Scaffold.of(context).openDrawer(); },
         tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
       );
     },
   ),
)
</code>
See also:

https://api.flutter.dev/flutter/material/AppBar/leading.html
https://www.youtube.com/watch?v=EcAwFpC9S8s
Answer: <code>   if (_scaffoldKey.currentState.isDrawerOpen)
            _scaffoldKey.currentState.openEndDrawer();
          else {
            _scaffoldKey.currentState.openDrawer();
          }
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
</code>
You can manipulate depend on which side you have your drawer!!!!

Navigation Drawer with Custom Button


Load Tinymce scripts in WordPress admin page

Question: I want to use TinyMCE in my WordPress plugin. I want to add TinyMCE editor for my custom textboxes and text areas.
I have tried including below code to load TinyMCE editor scripts.
wp_enqueue_script( 'tiny_mce');
But this does not load TinyMCE editor in my admin page. When I init TinyMCE it gives me error as TinyMCE is not defined.
Could anyone here know how to load TinyMCE scripts on my admin page?
Answer: The WordPress default wp_editor() function renders an editor in a page in the typical fashion used in Posts and Pages.
You can use it like
$content = ''; // Initial content for the editor
$editor_id = 'editor_id'; //HTML id attribute value for the textarea and TinyMCE
wp_editor( $content, $editor_id );

check here


Including error dependent on output in Gaussian Process Regression

Question: I have a set of experimental data that I am trying to fit using Gaussian process regression (GPR) using Python's sklearn package. The only problem is that my data has an experimental standard deviation equal to 20% of its output. Can this dependency be handled in GPR?
In the code, the essential aspects are:
total_noise = 0.2*((numpy.abs(y))) #standard deviation

# Instantiate a Gaussian Process model
gp = GaussianProcessRegressor(kernel=kernel, alpha = total_noise**2.,
                                  n_restarts_optimizer=100)

If my kernel is simply a radial basis function, then this results in:
$$k(x_i, x_j) = RBF(x_i, x_j) + 0.2 *y_i * \mathcal I (x_i * x_j)$$
But the problem appears to be that alpha here is dependent on y (my experimental output). Correct me if I am mistaken, but I believe this is okay when training. But I ultimately want both the computed mean and standard deviation from GPR, and I do not believe sklearn's GPR is accounting for this dependency on the output in alpha since I would expect the predicted standard deviation, $\sigma^*$, to be smaller where the predicted output, $y^*$, is smaller. But this is not the case. My covariance itself appears to depend on $y$ because, in the model, $y$ exists on both sides of the sampling statement:
$$y \sim \mathcal N(0, \Sigma(y))$$
and I do not believe this is handled consistently. Is there a way to account for this dependency (i.e. my original data has a standard deviation of 20% in the y-axis) using sklearn's GPR?
Answer: If the error bars represent observation uncertainty, then essentially, you're trying to model a latent function $\bar Y$ which is a function of $X$, which is corrupted by noise:
$$Y = \bar Y + \bar Yk\epsilon$$
... where $k\epsilon \sim \mathcal N(0, k^2 \sigma^2)$.
Notice that this is quite a complicated model, i.e. if one models $\bar Y$ using a GP, the distribution of $\bar Y k \epsilon$ is no longer multivariate normal, hence Y isn't a GP. You could easily model this using a probabilistic programming tool such as Stan or PyMC, but given that $Y$ isn't a GP, I do not think that it's possible to fit the model above in scikit-learn.
I'm not entirely sure if adding an alpha term in scikit-learn is a good way to approximate the solution (I think that it is, as the variance corresponding to observed points is higher, but perhaps this is something others can weigh on).
Note that the predicted error bars of the GP don't necessarily need to look like the error bars you drew from your data - you've got lots of data, so even though the variance of the initial data points is high, there are many of them, which gives the GP enough information as to where the function will lie, roughly. The model as it's written above does not correspond well to the data, as even though the error bars are smaller along the domain, notice that they're all over the place. Really, the variance of the data hasn't really changed all that much over the domain, so there's no reason to expect the GP to have smaller error bars further along the line.
(Look at the point near (20, 60) - I do not see any reasonable line passing through all the points while exactly maintaining the error bar 'profile' as in that graph. There's more to the errors than the model above, so a GP is a very reasonable approximation to the mean function of that graph.)


Fazer handle do jQuery-Tools acompanhar um time

Question: Utilizo o jQuery-Tools pra criar um efeito personalizado de scroll em uma div como no exemplo a seguir:

"use strict";

var id_label_ms = document.getElementById("count_label_ms");
var range = document.getElementById("area");
var cronometro = {};
var countms = 0;
var counterms;
var cronometroAtivo = false;

window.onload = function () {
  areaMusica();

  var scroll = $(".area");

  $(":range").rangeinput({
    onSlide: function(ev, step)  {
      scroll.css({left: -step});
    },
    progress: true,
    change: function(e, i) {
      scroll.animate({left: -i}, "fast");
    },
    speed: 0
  });
};

function areaMusica(){
  var k = 1; var tabela = '';
  tabela = '
';
  for (var i = 0; i < 2; i++) {
    if(i < 1){
      tabela += '
';
      for (var j = 1; j < 62; j++) {
        if(j == 1){
          tabela += 'start	';
        }else{
          tabela += '	';
          k++;
        }
      }
      tabela += '
';
    }else{
      tabela += '
	';
      for(var j = 1; j < 61; j++) {
        if(j % 5 == 0){
          tabela += ''+seconds2time((j*2)-10) +"min - "+seconds2time(j*2)+'min	';
        }
      }
      tabela += '
'
    }
  }
  tabela += '
';
  document.getElementById('area').innerHTML = tabela;
}

function seconds2time(seconds){
  var minutes = Math.floor((seconds ) / 60);
  var seconds = seconds - (minutes * 60);
  var time = "";

  if(minutes < 10){
    minutes = "0"+minutes;
  }
  if(seconds == 0){
    seconds = "0"+seconds;
  }

  time = minutes+":"+seconds;
  return time;
}

function iniciar(elemento){
  var icon = elemento.dataset.option;
  range.style.left = 0;
  if(icon === "play"){
    start();
    elemento.src = "http://cdn.flaticon.com/svg/70/70419.svg";
    elemento.title = "Pausar";
    elemento.dataset.option = "pause";
  }else{
    stop();
    elemento.src = "http://cdn.flaticon.com/svg/70/70409.svg";
    elemento.title = "Tocar";
    elemento.dataset.option = "play";
  }
}

function start() {
  if (cronometroAtivo) return;
  cronometroAtivo = true;
  counterms = setInterval(function () {
    range.style.left = range.style.left.substring(0, range.style.left.length-2) - 1;
    countms = countms + 1;
    id_label_ms.innerHTML = countms / 100 + " s";
  }, 10);
};

function stop(){
  range.style.left = 0;
  cronometroAtivo = false;
  countms = 0;
  id_label_ms.innerHTML = countms + " s";

  clearInterval(counterms);
  cronometroAtivo = false;
};
.containerArea{
  height: auto;
  width: 1030px;
  border: 1px rgb(89,89,89) solid;
  margin-top: 30px;
  background: rgb(173,234,234);
}

.slider {
  position:absolute;
  cursor:pointer;
  height:1px;
  border:2px solid rgb(179,179,179);
  width:1000px;
  -moz-border-radius:2px;
  -webkit-border-radius:2px;
}

#scrollwrap {
  margin-top:30px;
  margin-left:10px;
  overflow:hidden;
  width: 1000px;
  margin-left:5px;
  height:auto;
}

.container{
  min-width: 23px;
  height: 26px;
  border: 1px rgb(140, 173, 188) double;
}

.containerFaixa{
  width: 1000px;
  height: 26px;
  border: 1px rgb(140, 173, 188) double;
  background: rgb(216,216,191);
  border-radius: 7px;
}

.faixa{
  color: rgb(0, 0, 0);
  text-align: center;
  font-size: 12px;
  font-weight: bold;
  font-family: inherit;
  font-style: inherit;
  text-decoration: inherit;
  text-align: center;
  line-height: 1.85em;
}

.tempo{
  color: rgb(0, 0, 0);
  font-size: 10px;
  font-weight: inherit;
  font-family: 'Courier New', Courier, monospace;
  font-style: inherit;
  text-decoration: inherit;
}

.progress {
  background-color:rgb(179,179,179);
  height:3px;
  position:absolute;
  width:0;
}

.handle {
  position: absolute;
  z-index:4;
  width: 28px;
  height: 115px;
  background-position: top center;
  background-size: 25px 30px;
  background-image: url(http://cdn.flaticon.com/svg/17/17736.svg);
  background-repeat: no-repeat;
}

.area {
  position:relative;
  font:bold 90px  sans-serif;
  height:auto;
}

.range {
  display:none;
}

  <input id="range" type="range" max="795" value="0" />

    Count:

A intenção é criar um player de áudio personalizado, quando clicar em play, o handle começar a se movimentar junto com o count. Cada coluna da tabela representa 2 segundos.
Problema 1: Esse meu exemplo funciona localmente, mas não consegui fazer funcionar online, tanto aqui no Stack Snippets, quanto no jsFiddle e tanto quanto no codeOpen. A contagem inicia mas o handle não começa a se mover, criei um zip pra quem quiser testar localmente.
Essa nem é a questão principal, mas gostaria de entender o que há de errado pra que nessas ferramentas online ele não funcione corretamente?
Problema 2: Sei que a velocidade constante do handle deveria ser:  ou seja 2/24 = 0,0834. Então, teoricamente na função start o calculo deveria ser:
range.style.left = range.style.left.substring(0, range.style.left.length-2) - 0,0834;

Porém não está se movimentando corretamente, está se movimentando muito devagar, tentei ajustar para mais e para menos, mas sempre parece ficar ou muito lento, ou muito rápido, isso também afeta o problema 3.
Problema 3: Desejo fazer um handle que possa ser personalizado, localmente se eu altero o estilo do handle, como no exemplo a seguir:

"use strict";

var id_label_ms = document.getElementById("count_label_ms");
var range = document.getElementById("area");
var cronometro = {};
var countms = 0;
var counterms;
var cronometroAtivo = false;

window.onload = function () {
  areaMusica();

  var scroll = $(".area");

  $(":range").rangeinput({
    onSlide: function(ev, step)  {
      scroll.css({left: -step});
    },
    progress: true,
    change: function(e, i) {
      scroll.animate({left: -i}, "fast");
    },
    speed: 0
  });
};

function areaMusica(){
  var k = 1; var tabela = '';
  tabela = '
';
  for (var i = 0; i < 2; i++) {
    if(i < 1){
      tabela += '
';
      for (var j = 1; j < 62; j++) {
        if(j == 1){
          tabela += 'start	';
        }else{
          tabela += '	';
          k++;
        }
      }
      tabela += '
';
    }else{
      tabela += '
	';
      for(var j = 1; j < 61; j++) {
        if(j % 5 == 0){
          tabela += ''+seconds2time((j*2)-10) +"min - "+seconds2time(j*2)+'min	';
        }
      }
      tabela += '
'
    }
  }
  tabela += '
';
  document.getElementById('area').innerHTML = tabela;
}

function seconds2time(seconds){
  var minutes = Math.floor((seconds ) / 60);
  var seconds = seconds - (minutes * 60);
  var time = "";

  if(minutes < 10){
    minutes = "0"+minutes;
  }
  if(seconds == 0){
    seconds = "0"+seconds;
  }

  time = minutes+":"+seconds;
  return time;
}

function iniciar(elemento){
  var icon = elemento.dataset.option;
  range.style.left = 0;
  if(icon === "play"){
    start();
    elemento.src = "http://cdn.flaticon.com/svg/70/70419.svg";
    elemento.title = "Pausar";
    elemento.dataset.option = "pause";
  }else{
    stop();
    elemento.src = "http://cdn.flaticon.com/svg/70/70409.svg";
    elemento.title = "Tocar";
    elemento.dataset.option = "play";
  }
}

function start() {
  if (cronometroAtivo) return;
  cronometroAtivo = true;
  counterms = setInterval(function () {
    range.style.left = range.style.left.substring(0, range.style.left.length-2) - 1;
    countms = countms + 1;
    id_label_ms.innerHTML = countms / 100 + " s";
  }, 10);
};

function stop(){
  range.style.left = 0;
  cronometroAtivo = false;
  countms = 0;
  id_label_ms.innerHTML = countms + " s";

  clearInterval(counterms);
  cronometroAtivo = false;
};
.containerArea{
  height: auto;
  width: 1030px;
  border: 1px rgb(89,89,89) solid;
  margin-top: 30px;
  background: rgb(173,234,234);
}

.slider {
  position:absolute;
  cursor:pointer;
  height:1px;
  border:2px solid rgb(179,179,179);
  width:1000px;
  -moz-border-radius:2px;
  -webkit-border-radius:2px;
}

#scrollwrap {
  margin-top:30px;
  margin-left:10px;
  overflow:hidden;
  width: 1000px;
  margin-left:5px;
  height:auto;
}

.container{
  min-width: 23px;
  height: 26px;
  border: 1px rgb(140, 173, 188) double;
}

.containerFaixa{
  width: 1000px;
  height: 26px;
  border: 1px rgb(140, 173, 188) double;
  background: rgb(216,216,191);
  border-radius: 7px;
}

.faixa{
  color: rgb(0, 0, 0);
  text-align: center;
  font-size: 12px;
  font-weight: bold;
  font-family: inherit;
  font-style: inherit;
  text-decoration: inherit;
  text-align: center;
  line-height: 1.85em;
}

.tempo{
  color: rgb(0, 0, 0);
  font-size: 10px;
  font-weight: inherit;
  font-family: 'Courier New', Courier, monospace;
  font-style: inherit;
  text-decoration: inherit;
}

.progress {
  background-color:rgb(179,179,179);
  height:3px;
  position:absolute;
  width:0;
}

.handle {
  position: absolute;
  z-index:4;
  width: 28px;
  height: 55px;
  border: rgb(161, 233, 240) solid;
  background-position: top center;
  background-size: 25px 30px;
  background-image: url(http://cdn.flaticon.com/svg/17/17736.svg);
  background-repeat: no-repeat;
  box-shadow:  0px 0px 0px 1px rgb(0, 0, 0),inset 0px 0px 0px 1px rgb(0, 0, 0);
}

.area {
  position:relative;
  font:bold 90px  sans-serif;
  height:auto;
}

.range {
  display:none;
}

  <input id="range" type="range" max="795" value="0" />

    Count:

O tempo do movimento do handle ao clicar no botão start fica estranho e aparentemente fica mais rápido sendo que não há alteração nenhuma na função:
function start() {
  if (cronometroAtivo) return;
  cronometroAtivo = true;
  counterms = setInterval(function () {
    range.style.left = range.style.left.substring(0, range.style.left.length-2) - 1;
    countms = countms + 1;
    id_label_ms.innerHTML = countms / 100 + " s";
  }, 10);
};

Comment: Eu posso te ajudar, por 50 pontos a resolver 1 dos 3 problemas...rsrssr pode até escolher qual deseja resolver, se a recompensa for 150 resolvo os 3 problemas, brincadeiras a parte, você poderia abrir 3 perguntas né, para que não fique tão amplo as respostas.
Comment: Então @SneepSNinja, com exceção do problema 1, que é mais uma curiosidade propriamente dita, os outros 2 problemas eu tenho uma sensação que estão intrinsecamente ligados, achei melhor colocar tudo em uma questão só, mas não sei, se for necessário eu divido eles
Comment: referente ao problema 3, poderia usar o jQuery, colocar um botão para mudar o tema e fazer uma simples troca de classes entre os elementos html é algo bem simples, acho que nem vale uma resposta, um comentário acho que já da p/ entender da uma olhada lá https://jqueryui.com/toggleClass/
Answer: Referente ao problema 1:
seu teste https://jsfiddle.net/xjyofffu/
meu teste
https://jsfiddle.net/nq72w31a/
Ambos não funcionando porém da p/ ter uma idéia que a ordem de execução dos scripts faz diferença, e o jsfiddle esta arbitrando isso.
Outro ponto importante, dentro desse plugin jquery.tools.min.js tem implementado IFRAME  coisa que o JSFiddle não aceita.
Referente ao Problema 2:
Temos os blocos com 23px + 1px de padding + 1 px de borda, da 25px, mas eles estão espaçados por causa do table então tens que tirar o cellspacing deixa ele zerado, então teremos 25px por bloco, ai podemos começar a fazer uma formula e alguns testes ficaria assim:

"use strict";

var id_label_ms = document.getElementById("count_label_ms");
var range = document.getElementById("area");
var cronometro = {};
var countms = 0;
var counterms;
var cronometroAtivo = false;

window.onload = function () {
  areaMusica();

  var scroll = $(".area");

  $(":range").rangeinput({
    onSlide: function(ev, step)  {
      scroll.css({left: -step});
    },
    progress: true,
    change: function(e, i) {
      scroll.animate({left: -i}, "fast");
    },
    speed: 0
  });
  //iniciar( document.getElementById("teste") );
};

function areaMusica(){
  var k = 1; var tabela = '';
  tabela = '
';
  for (var i = 0; i < 2; i++) {
    if(i < 1){
      tabela += '
';
      for (var j = 1; j < 62; j++) {
        if(j == 1){
          tabela += '	';
        }else{
          tabela += '	';
          k++;
        }
      }
      tabela += '
';
    }else{
      tabela += '
	';
      for(var j = 1; j < 61; j++) {
        if(j % 5 == 0){
          tabela += ''+seconds2time((j*2)-10) +"min - "+seconds2time(j*2)+'min	';
        }
      }
      tabela += '
'
    }
  }
  tabela += '
';
  document.getElementById('area').innerHTML = tabela;
}

function seconds2time(seconds){
  var minutes = Math.floor((seconds ) / 60);
  var seconds = seconds - (minutes * 60);
  var time = "";

  if(minutes < 10){
    minutes = "0"+minutes;
  }
  if(seconds == 0){
    seconds = "0"+seconds;
  }

  time = minutes+":"+seconds;
  return time;
}

function iniciar(elemento){
  var icon = elemento.dataset.option;
  range.style.left = 0;
  if(icon === "play"){
    start();
    elemento.src = "http://cdn.flaticon.com/svg/70/70419.svg";
    elemento.title = "Pausar";
    elemento.dataset.option = "pause";
  }else{
    stop();
    elemento.src = "http://cdn.flaticon.com/svg/70/70409.svg";
    elemento.title = "Tocar";
    elemento.dataset.option = "play";
  }
}

function start() {
  if (cronometroAtivo) return;
  cronometroAtivo = true;
  counterms = setInterval(function () {
    range.style.left = range.style.left.substring(0, range.style.left.length-2) - 0.129;
    countms = countms + 1;
    id_label_ms.innerHTML = countms / 100 + " s";
  }, 10);
};

function stop(){
  range.style.left = 0;
  cronometroAtivo = false;
  countms = 0;
  id_label_ms.innerHTML = countms + " s";

  clearInterval(counterms);
  cronometroAtivo = false;
};
.containerArea{
  height: auto;
  width: 1030px;
  border: 1px rgb(89,89,89) solid;
  margin-top: 30px;
  background: rgb(173,234,234);
}

.slider {
  position:absolute;
  cursor:pointer;
  height:1px;
  border:2px solid rgb(179,179,179);
  width:1000px;
  -moz-border-radius:2px;
  -webkit-border-radius:2px;
}

#scrollwrap {
  margin-top:30px;
  overflow:hidden;
  width: 1000px;
  height:auto;
}

.container{
  min-width: 23px;
  height: 26px;
  border: 1px rgb(140, 173, 188) double;
}

.containerFaixa{
  width: 1000px;
  height: 26px;
  border: 1px rgb(140, 173, 188) double;
  background: rgb(216,216,191);
  border-radius: 7px;
}

.faixa{
  color: rgb(0, 0, 0);
  text-align: center;
  font-size: 12px;
  font-weight: bold;
  font-family: inherit;
  font-style: inherit;
  text-decoration: inherit;
  text-align: center;
  line-height: 1.85em;
}

.tempo{
  color: rgb(0, 0, 0);
  font-size: 10px;
  font-weight: inherit;
  font-family: 'Courier New', Courier, monospace;
  font-style: inherit;
  text-decoration: inherit;
}

.progress {
  background-color:rgb(179,179,179);
  height:3px;
  position:absolute;
  width:0;
}

.handle {
  position: absolute;
  z-index:4;
  width: 28px;
  height: 115px;
  background-position: top center;
  background-size: 25px 30px;
  background-image: url(http://cdn.flaticon.com/svg/17/17736.svg);
  background-repeat: no-repeat;
  left: 13px;
}

.area {
  position:relative;
  font:bold 90px  sans-serif;
  height:auto;
}

.range {
  display:none;
}

<link type="text/css" rel="stylesheet" href="style-teste.css" />

  <input id="range" type="range" max="795" value="0" />

    Count:

eu testei e ficou quase lá com um tempo em torno de 0.12 a 0.13 lá na parte range.style.left.substring(0, range.style.left.length-2) - 0.13; // por exemplo agora sou ruim de matemática ao meu ver teria que ser uma formula tipo 2/25 = 0.08, talvez seja esse setInterval=10 que esteja bugando sua formula a cada 10 mms tanto para mais quanto para menos, minha contribuição sobre o problema seria isso, os tamanhos dos blocos e o espaçamentos estava equivocado sobre eles.
Obs: Seu marcador esta mal posicionado no Start, ele tem que ficar encostado no primeiro bloco, fiz uma gambi ai removendo a palavra Start e mexi para posicionar ele ali rente ao primeiro bloco, vai de você ou deixar a palavra Start e posicionar ele, ou remover como eu fiz...
Comment: É que ambos usam Iframe, o JSfiddle bloqueia a tag o codeOpen não bloqueia, mas deve dar algum pau na hora de rodar o seu codigo que usa iframe dentro do iframe de exibição do codeOpen
Comment: E no codeOpen? é o mesmo problema?
Comment: Apesar de não me sentir 100% satisfeito, foi a melhor resposta rs
Answer: Existe um bloqueio para a execução do seu script jquery.tools devido a sua saída retornar em um iframe, ele passa a ser um elemento em HTML e não um js, eu acredito que seja um problema fácil de resolver, tratando isso com outro plugin, porém outro problema é o uso de variáveis globais, que interagem nesse script. Eu redeclarei os elementos que não estão sendo reconhecidos globalmente, mas mesmo assim, como há uma saída em iframe, do movimento do script, ele bloqueia, eu não sei se há uma maneira de habilitar a visualização disso, mas aqui não ocorreu erros de script:
https://jsfiddle.net/ivanferrer/037j5ua6/


orderBy in hasOne relation doesn't work

Question: I have a table (weathers) with several thousands rows, 90000 +- at the moment, each one belonging to one location.
This table can have multiple rows belonging to one location, but I still want just one, the last one for a given location.
My model Location have this relation defined as:
...
public function last_weather() {
    return $this->hasOne(\App\Weather::class, 'id_location')->orderBy('weathers.id', 'DESC');
}
...

And on my controller I'm retrieving the last_weather like:
...
Location::with(['last_weather'])->findOrfail(1);
...

The strange thing is that this worked until I have 45000+- rows in the weather table, I have 3200 locations, and the last records for each location that are returned are on 40000+- rows (between id 40000 and 43000 +-, of the weathers table)
I have checked my DB and I have each location updated on the 80000's, but the relation are returning the data from the 40000's. This is not even the first or the last weather for each location.
Comment: Can you add `\DB::enableQueryLog();` before your query, and then `dd(\DB::getQueryLog())` after your query, and post the results?
Answer: You can do this in your Location model
public function weathers()
{
   return $this->hasMany(\App\Weather::class, 'id_location');
}

public function lastWeather()
{
   return $this->weathers()->latest()->first();
}

Then in your controller
$location = Location::findOrfail(1);

then you can access the last weather like this
$location->lastWeather();

UPDATE
Or you can adjust how you eager load weathers
$location = Location::with([
        'weathers' => function($query) {
            $query->orderBy('id', 'DESC')->first();
        },
    ])
    ->findOrfail(1);

Comment: I have added another way
Comment: I would prefer to leave it like a relation, it's more flexible. I can just eager load, or select the collumns as want
Answer: Order by will return all rows, to only return a single row for each matching condition you need to use Group by
I never used Laravel, but looking at your code I'm guessing your query should look like this:
return $this->hasOne(\App\Weather::class, 'id_location')->groupBy('weathers.id', 'DESC');
Comment: Can you post that, adapt my code on the Model to that please?
Comment: Ok, but how do I retrieve the last one? This is returning the first one
Comment: Either delete `DESC` from the end, or replace it with `ASC`
Comment: It gives an error if I leave the `DESC`, ` Column not found: 1054 Unknown column 'DESC' in 'group statement' (`

orderBy in hasOne relation doesn't work


D6/views - Multiple nodes in one slide grouped by taxonomy

Question: I have the following taxonomy:

food

fruits

apples
pears
bananas

vegtables

tomatoes
carrot
cucumber

meat

chicken
beef
duck

...and a view that brings all those items, currently as an html list grouped by taxonomy term. I use fields for each item.
I need to change my view in order to split them in slides (or pages with prev/next) so that each slide/page will hold all the items of a food subcategory (the whole group). Ideally with a slider but pagination will also suffice.
To be precise I'd like a similar result as in this question. But in my case I have the above taxonomy tree to help distinct nodes I need in each slide
Thanks in advance!
Answer: You might add an argument to your view.
The url of your view should looks like: "my_site/my_views_url/11"
(#11 is the tid of "fruits")
This url will list all terms depth to "fruits" (so apples, pears, bananas)
To add a depth in your argument term in the view follow the views UI :
Comment: Thanks for your prompt reply. Ok so I added the argument and changed the menu's link url to point to the category I want to display first, "fruits". I get a page with the content of fruits (apples, pears, bananas). What I'm missing now is a way to navigate between those categories (fruits, vegetables, meat). Adding menu items is not an option as I want this to be look and feel gallery-like
Comment: i suggest you to post an other question without slideshow (because your question's title is confusing) focus on your need : a view for a taxonomy tree with links with childrens terms
Comment: I edited this one along with its text. Hopefully it's more clear now...
Answer: I think you are looking for Taxonomy VTN module , but it subgroup with alphabets

Taxonomy VTN module provides an index for vocabularies, terms and
  nodes just like those you find at the end of reference or technical
  books. It supports synonyms, terms, related terms, and parent/child
  relations.

or may be this module you are looking for, it have the alphabetical sort order for the vocabulary.


Finding the height of a regular tetrahedron

Question:
The length of an edge of a regular tetrahedron is $8cm$. Find the total area of surfaces and the volume

I've been able to find the area of all surfaces, which is $(4\times27.713) cm^2$ but I'm not able to find the volume.

There's no height given. How can I derive the height?
Answer: Hint
the heights in the base are crossing each other in the ratio $1:2$ exactly under the top.
Answer: The volume of a regular tetrahedron with side $a$ is given by
$V = \frac {a^3} {6 \sqrt{2}}$
Comment: @Brahadeesh it answers the Y part of an XY question. The problem is "Find the total area of surfaces and the volume".
Comment: fair enough... but a little more explanation would help improve the answer. The OP wants to know about the height of a tetrahedron given the side length.
Comment: @Brahadeesh it's a possible duplicate question anyway, please see my comment below the question.
Comment: thank you for searching it out, I've added my vote to close as duplicate based on the link.


Error 404 when attempting to publish page via github

Question: I am not having success when trying to publish my basic html page.
Here is my repository:
https://github.com/mathiasgc/mathiasgc.github.io
I have an index.html file in my master repository, as well as the CNAME with the domain name.
Thanks,
Mathias
Answer: The problem appears to be that you forgot to give your index file an extension. You have an index file successfully in your repository, but it is simply called index. You need to give it a valid index extension - in your case I believe you're looking for index.html.
When uploading your index file, make sure to actually call it index.html specifically, and not just index.
Hope this helps! :)
Comment: Thanks! that makes sense(i was scrolling the scroll down bar and selecting .html). However, I'm trying to add the new .html file and not having any success. I'm typing : "git add ." and  getting no response. I already have an existing repository, and had no problems earlier Any idea's?
Comment: There are two reasons; you have either already added that file, or you haven't made any changes. Have you checked with `git status`? Did you rename the old file, or did you remove it? Don't forget that you'll also need to commit and push before you see any changes.
Comment: Your right! Thanks for being so nice! :D So for future edits, I do "git commit" and "git push"? Is there anything faster? preferably one line?
Comment: All good :) Once you've confirmed this solution solves your problem, please don't forget to mark the solution as correct by clicking on the grey check below the vote buttons -- this removes it from the 'Unanswered Questions' queue, and awards reputation to both the question asker and question answerer. Of course, in saying that, you are under no obligation to mark my answer (or any other answer) as correct, though it does help to keep things flowing smoothly :)
Comment: Will do! Much appreciated!


How to get alternative text on image hover

Question: How to display image's alternative text when an user hovers on that image.
I have come across few posts that displays popups and views, but not the alternative text of the corresponding images. Some of the modules like qTip and Beautytips looks relevant but I suppose those modules doesn't deliver my requirements. If I'm wrong, please let me know how to use those modules to get the alternative text displayed on hover.
Are there any suggestions regarding how to get alternative text on image hover (possibly without views)
Here, I've created a basic page and in the body I've added an image using advanced text editor.
Answer: In the field settings for the image, make sure to 'Enable Title field' - this will present a text input for each content under the upload button.  You can include the title here, and it will show on mouse over.
Comment: I've edited my post. I'm not using content type to upload the image. I'm adding an image using advanced text editor options.
Comment: Well, @GIRI, then you have to find a way to implement the title attribute there. I'm not sure, but I'ld guess that [CKEditor](https://www.drupal.org/project/ckeditor) or [Media](https://www.drupal.org/project/media) has that possibilty implemented.
Comment: Last but not least you could write a little bit jQuery to automatically have the alt attribute set as title attribute @GIRI: http://stackoverflow.com/questions/1734806/is-there-a-way-to-show-alt-text-as-a-mouseover-tooltip-in-firefox-like-ie-does
Comment: yup, sounds great.. I did that
Comment: @GIRI - Would be nice to have your solution as a proper answer to your question. How you wrote and implemented what JS code exactly?
Comment: Yup, good idea. I've updated my answer
Answer: I think what you are trying to do is in conflict with accessibility best practices. My understanding is that the alt attribute is only meant to be used for contexts where the image does not appear, and is not meant to be used as a compliment to the display of the image itself (as a tooltip or a description). In other words, I think the display of the alt text and the image are intended to be mutually exclusive.
Of course that does not mean that it's technically not possible to use the alt text as a tooltip (some ideas around that are discussed in this post), it's just discouraged.
Perhaps it would be best to refactor your content so that your hover text (that's intended to be used as a tooltip) is moved to the title attribute. This way you will be in-step with accessibility best practices and will automatically get native tooltip support from browsers.
I suppose that does not directly address your question, but it seems like the right note to start with.
Answer: There might be different ways to address this issue, but based on my problem statement and requirements I found this solution is quite easy.
I'm injecting jQuery code and modifying the CSS to get the hover effect. My idea is firstly to insert hover text as a span through jQuery injection. Secondly, modify the CSS in such a way that the text span appears only on hover.
Refer JS FIDDLE for the example code.
I've used JSInjector module for injecting jQuery code and modified reset.css file


How to Create a Front-end Lost Password Page for WordPress?

Question: I am trying to build a page for user to change their own password.
Is there any hook for it? I just google it but I did not succeed.
Of course without plugins.
Comment: Why not using plugins?
Answer: The function you're looking for is wp_set_password( $password, $user_id ). See Codex page for more info.


Touch events not working EaselJS

Question: I'm developing a HTML5 Canvas game using EaselJS and I've found a problem after changing my code. The touch events were working before this change, but it's not working anymore and I don't remember what I've changed, but it wasn't related to the stagemousedown/stagemouseup events. I've tested the game on iOS 7 only.
Can someone help me?
As I said, I don't know where the problem is then I'll put the entire code here instead of the relevant part only (>400 lines). I highly recommend seeing the [fiddle][1] instead.
Here's my code:
function init() {

    var objectsCollideAt = {
        it: [], // If it is collideable, it'll be in this array.
        top: [],
        left: [],
        right: [],
        bottom: []
    },
    key = {
        up: false, // W, arrow up or spacebar
        left: false, // A or arrow left
        right: false, // D or arrow right
        down: false, // S or arrow down
        holdingUp: false
    },
    mouse = {
        x: 0,
        y: 0
    },
    touch = {
        tollerance: 50 // Object "margins" when using touch or mouse
    },
    collisionSystem = {
        /* This variable is responsible for deactivating the
         * edge-to-edge collision detection forEach when a
         * side-to-side collision happened, to get better
         * performance. Can cause extremely rare bugs.
         */
        //sideCollided: false // Commented because it was causing a critical bug.
    };

    var stage = new createjs.Stage("canvas");

    createjs.Touch.enable(stage);

    var Graphic = function (src, blockWidth, blockHeight) {
        src = src.split(",");
        return {
            createBlockAt: function (x, y, blockGroupWidth, blockGroupHeight, clsdir, alpha) {
                for (var blockY = 0; blockY < blockGroupHeight / blockHeight; blockY++) {
                    for (var blockX = 0; blockX < blockGroupWidth / blockWidth; blockX++) {

                        var obj = new createjs.Bitmap(src[Math.floor(Math.random() * src.length)]);

                        obj.width = blockWidth;
                        obj.height = blockHeight;
                        if (typeof alpha !== 'undefined') {
                            obj.alpha = alpha; // While debugging this can be used to check if a block was made over another block.
                        }

                        obj.x = Math.round(x + (blockWidth * blockX));
                        obj.y = Math.round(y + (blockHeight * blockY));

                        if (clsdir != "none") {
                            objectsCollideAt.it.push(obj);
                        }
                        if (typeof clsdir !== "undefined") {
                            clsdir.split(" ");
                            if (clsdir.indexOf("top") >= 0 && blockY == 0) {
                                objectsCollideAt.top.push(obj);
                            }
                            if (clsdir.indexOf("left") >= 0 && blockX == 0) {
                                objectsCollideAt.left.push(obj);
                            }
                            if (clsdir.indexOf("right") >= 0 && blockX == (blockGroupWidth / blockWidth - 1)) { // blockGroupWidth/width results in the horizontal number of blocks
                                objectsCollideAt.right.push(obj);
                            }
                            if (clsdir.indexOf("bottom") >= 0 && blockY == (blockGroupHeight / blockHeight - 1)) { // blockGroupHeight/height results in the vertical number of blocks.
                                objectsCollideAt.bottom.push(obj);
                            }
                        } else {
                            if (blockY == 0) {
                                objectsCollideAt.top.push(obj);
                            }
                        }

                        obj2container.addChild(obj);
                    }
                }
            }
        }
    }
    var dirt = Graphic("http://i.imgur.com/zF6Lhfl.png", 40, 40);
    var rock = Graphic("http://i.imgur.com/QgxGfJs.png", 40, 40);
    var grass = Graphic("http://i.imgur.com/5SkIyyM.png, http://i.imgur.com/CT6yf5q.png, http://i.imgur.com/gTwOePB.png", 40, 40);
    var shadow = Graphic("http://i.imgur.com/50I5K1F.png", 40, 40);
    var shadow2 = Graphic("http://i.imgur.com/dR9195w.png", 40, 40);

    var obj2container = new createjs.Container();
    // Note that the hero will respawn in the middle of each object if he die.
    //  dirt.createBlockAt(X, Y, W, H);
    dirt.createBlockAt(0, 40, 40 * 3, 40 * 9);
    rock.createBlockAt(40 * 4, 40 * 3, 40 * 3, 40);
    dirt.createBlockAt(40 * 3, 40 * 5, 40 * 4, 40 * 5);
    rock.createBlockAt(40 * 12, 40 * 6, 40, 40);
    shadow.createBlockAt(40 * 5 - 20, 40 * 8 - 2, 40, 40, "none", 0.5);
    shadow.createBlockAt(40 * 4, 40 * 9 - 2, 40, 40, "none", 0.5);
    rock.createBlockAt(40 * 5 - 20, 40 * 7, 40, 40);
    rock.createBlockAt(40 * 4, 40 * 8, 40, 40);
    shadow2.createBlockAt(0, 40 * 9, 40 * 7, 40, "none", 0.5);
    dirt.createBlockAt(0, 40 * 10, 40 * 14, $(window).height() - (40 * 10)); // Use $(window).height() instead of stage.canvas.height here. stage.canvas.height wasn't set yet. // This will be unnecessary after implementing camera movement.
    grass.createBlockAt(0, 40 * 1 - 20, 40 * 3, 20, "none");
    grass.createBlockAt(40 * 3, 40 * 5 - 20, 40 * 4, 20, "none");
    grass.createBlockAt(0, 40 * 10 - 20, 40 * 14, 20, "none");

    obj2container.cache(0, 0, $(window).width(), $(window).height());
    stage.addChild(obj2container);

    var data = {
        images: ["http://i.imgur.com/RjVQ6e1.png"],
        frames: {
            width: 30,
            height: 40
        },
        animations: {
            stand: 0,
            run: [1, 2, "runloop", 0.15],
            runloop: [3, 7, true, 0.15],
            jump: 11,
            fall: 12,
            stopfalling: [13, 15, "stand", 0.25]
        }
    };
    var spriteSheet = new createjs.SpriteSheet(data);
    var hero = new createjs.Sprite(spriteSheet, "stand");
    hero.offset = 4 + 1; // "+1" is important, change the first number only.
    hero.regX = hero.offset + 2;
    hero.regY = hero.offset;
    hero.width = 30 - (hero.offset * 2) - 10;
    hero.height = 40 - (hero.offset * 2);
    hero.xvel = hero.yvel = 0; // Number of pixels the hero will move / 8.

    if (localStorage.x && localStorage.y && localStorage.xpast && localStorage.ypast) { // Was localStorage declared?
        hero.x = Number(localStorage.x);
        hero.y = Number(localStorage.y);
        hero.xpast = Number(localStorage.xpast);
        hero.ypast = Number(localStorage.ypast);
    } else {
        hero.x = hero.xpast = 40; // Very first X.
        hero.y = hero.ypast = 0; // Very first Y.
    }

    hero.jumping = true;
    hero.airtime = 0;
    hero.animation = "stand";
    stage.addChild(hero);

    if (typeof Storage === undefined) {
        alert("Your browser doesn't support saving the game. All changes will be discarted when you leave the page.");
    }

    document.addEventListener("keydown", function (evt) {
        if (evt.keyCode == 87 || evt.keyCode == 38 || evt.keyCode == 32) { // up
            if (!key.holdingUp && !hero.jumping) { // Check if hero isn't jumping and if user isn't holding the key.
                key.up = true;
            }
        }
        if (evt.keyCode == 65 || evt.keyCode == 37) { // left
            key.left = true;
        }
        if (evt.keyCode == 68 || evt.keyCode == 39) { // right
            key.right = true;
        }
        if (evt.keyCode == 83 || evt.keyCode == 40) { // down
            key.down = true;
        }
    });

    document.addEventListener("keyup", function (evt) {
        if (evt.keyCode == 87 || evt.keyCode == 38 || evt.keyCode == 32) { // up
            key.up = false;
            key.holdingUp = false;
        }
        if (evt.keyCode == 65 || evt.keyCode == 37) { // left
            key.left = false;
        }
        if (evt.keyCode == 68 || evt.keyCode == 39) { // right
            key.right = false;
        }
        if (evt.keyCode == 83 || evt.keyCode == 40) { // down
            key.down = false;
        }
    });

    stage.on("stagemousedown", function (e) {
        if (event.which === 1) {
            mouse.x = e.stageX,
            mouse.y = e.stageY;

            if (mouse.x > hero.x + hero.width + touch.tollerance) {
                key.right = true;
            }
            if (mouse.x < hero.x - touch.tollerance) {
                key.left = true;
            }
            if (mouse.x > hero.x - touch.tollerance && mouse.x < hero.x + hero.width + touch.tollerance && mouse.y > hero.y - touch.tollerance && mouse.y < hero.y + hero.height + touch.tollerance) {
                key.up = true;
            }
        }
    });

    stage.on("stagemouseup", function () {
        setTimeout(function () {
            key.up = false;
            key.right = false;
            key.left = false;
            key.holdingUp = false;
        }, 1000 / 60); // Wait for one tick loop.
    });

    // Collision handler:

    function collisionHandler(obj1, obj2array) { // MASTERPIECE!

        // Side-to-side collision handler:
        objectsCollideAt.top.forEach(function (obj2) {
            // Top side:
            if (obj1.ypast + obj1.height < obj2.y && obj1.y + obj1.height >= obj2.y &&
            // Checks if past position X was correct:
            obj1.xpast + obj1.width >= obj2.x && obj1.xpast <= obj2.x + obj2.width) {
                hero.yvel = 0;
                hero.jumping = false;
                if (hero.airtime > 30) {
                    // hero.xpast and hero.ypast must be set to the same position so it will not cause a collision.
                    hero.x = hero.xpast = Number(localStorage.x);
                    hero.y = hero.ypast = Number(localStorage.y);
                } else {
                    obj1.y = obj2.y - obj1.height - 1;
                    if (typeof Storage !== undefined && !hero.jumping && hero.y == hero.ypast) { // Checks for localStorage support.
                        localStorage.x = obj2.x + ((obj2.width / 2) - (obj1.width / 2));
                        localStorage.y = hero.y;
                        localStorage.xpast = hero.xpast;
                        localStorage.ypast = hero.ypast;
                        //Debugging:
                        //console.log("Stored "+Number(hero.x)+" as "+Number(localStorage.x)+".");
                    }
                }
                hero.airtime = 0;
            }
        });

        objectsCollideAt.left.forEach(function (obj2) {
            // Left side:
            if (obj1.xpast + obj1.width < obj2.x && obj1.x + obj1.width >= obj2.x &&
            // Checks if past position Y was correct:
            obj1.ypast + obj1.height >= obj2.y && obj1.ypast <= obj2.y + obj2.height) {
                hero.xvel = 0;
                obj1.x = obj2.x - obj1.width - 1;
            }
        });

        objectsCollideAt.right.forEach(function (obj2) {
            // Right side:
            if (obj1.xpast > obj2.x + obj2.width && obj1.x <= obj2.x + obj2.width &&
            // Checks if past position Y was correct:
            obj1.ypast + obj1.height >= obj2.y && obj1.ypast <= obj2.y + obj2.height) {
                hero.xvel = 0;
                obj1.x = obj2.x + obj2.width + 1;
            }
        });

        objectsCollideAt.bottom.forEach(function (obj2) {
            // Bottom side:
            if (obj1.ypast > obj2.y + obj2.height && obj1.y <= obj2.y + obj2.height &&
            // Checks if past position X was correct:
            obj1.xpast + obj1.width >= obj2.x && obj1.xpast <= obj2.x + obj2.width) {
                hero.yvel = 0;
                obj1.y = obj2.y + obj2.height + 1;
            }
        });

        /*
                Now that every side-to-side collision change was made,
                the edge-to-edge collision handler will not detect
                blocked collisions.
                */
        // Edge-to-edge collision handler:

        objectsCollideAt.left.forEach(function (obj2) {
            // Top left edge:
            if (obj1.ypast + obj1.height < obj2.y && obj1.xpast + obj1.width < obj2.x && obj1.y + obj1.height >= obj2.y && obj1.x + obj1.width >= obj2.x) {
                hero.xvel = 0;
                obj1.y = obj2.y - obj1.height - 1;
                obj1.x = obj2.x - obj1.width - 1;
            }
            // Bottom left edge:
            if (obj1.ypast > obj2.y + obj2.height && obj1.xpast + obj1.width < obj2.x && obj1.y <= obj2.y + obj2.height && obj1.x + obj1.width >= obj2.x) {
                hero.yvel = hero.xvel = 0;
                obj1.y = obj2.y + obj2.height + 1;
                obj1.x = obj2.x - obj1.width - 1;
            }
        });

        objectsCollideAt.right.forEach(function (obj2) {
            // Top right edge:
            if (obj1.ypast + obj1.height < obj2.y && obj1.xpast > obj2.x + obj2.width && obj1.y + obj1.height >= obj2.y && obj1.x <= obj2.x + obj2.width) {
                hero.xvel = 0;
                obj1.y = obj2.y - obj1.height - 1;
                obj1.x = obj2.x + obj2.width + 1;
            }

            // Bottom right edge:
            if (obj1.ypast > obj2.y + obj2.height && obj1.xpast > obj2.x + obj2.width && obj1.y <= obj2.y + obj2.height && obj1.x <= obj2.x + obj2.width) {
                hero.yvel = hero.xvel = 0;
                obj1.y = obj2.y + obj2.height + 1;
                obj1.x = obj2.x + obj2.width + 1;
            }
        });
    }

    function changeAnimation(obj1, frameOrAnimation) {
        if (obj1.animation != frameOrAnimation) {
            obj1.animation = frameOrAnimation;
            obj1.gotoAndPlay(frameOrAnimation);
        }
    }

    // Tick:

    createjs.Ticker.on("tick", tick);
    createjs.Ticker.setFPS(60);

    function tick(event) {

        if (key.up && !hero.jumping && !key.holdingUp && Math.abs(hero.ypast - hero.y) < 6) { // Distance between last frame and actual frame y must be less than 6px.

            // KNOWN BUG: SOMETIMES THE JUMP HEIGHT DOUBLE! [IMPORTANT]
            // Diagnostic: None.
            // Reproduction: This bug normally occur during lags and was amplified after implementing time-based logic.
            // Solution: Unknown.

            hero.yvel -= 145; // How much speed the jump will produce. Please avoid changing this number — Speeds over 200 can kill the hero.
            hero.jumping = true;
            key.holdingUp = true; // Prevent jumping multiple times while holding the key.
        } else {
            if (hero.yvel < 0) {
                hero.yvel += 3;
            }
        }
        if (key.left && !key.right) {
            hero.xvel -= (!hero.jumping) ? 3 : 2;
            hero.regX = hero.offset + 12; // Need review.
            hero.scaleX = -1;
        }
        if (key.right && !key.left) {
            hero.xvel += (!hero.jumping) ? 3 : 2;
            hero.regX = hero.offset + 2; // "+2" is due to the head's opposite side.
            hero.scaleX = 1;
        }
        if (key.down) {
            //hero.yvel+=3; // Commented because there's no need for pushing the hero down. If uncommented: // Need review.
        }

        hero.xvel = (hero.xvel > 0) ? Math.min(hero.xvel, 50) : Math.max(hero.xvel, -50);
        //hero.yvel = (hero.yvel > 0)?Math.min(hero.yvel, 125):Math.max(hero.yvel, -125); // No need for this, there's gravity already.

        if (hero.jumping == true) {
            if (hero.yvel < 50) {
                changeAnimation(hero, "jump");
            } else {
                changeAnimation(hero, "fall");
            }
        }

        if (hero.ypast != hero.y && hero.yvel > 0) {
            hero.airtime++;
            changeAnimation(hero, "fall");
        }
        if (hero.airtime > 100) {
            // hero.xpast and hero.ypast must be set to the same position so it will not cause a collision.
            hero.x = hero.xpast = 0;
            hero.y = hero.ypast = 0;
        }
        if (!key.left && !key.right) {
            if (!hero.jumping) {

                if (hero.animation == "fall" || hero.animation == "stopfalling") {
                    changeAnimation(hero, "stopfalling");
                } else {
                    changeAnimation(hero, "stand");
                }

                if (hero.xvel != 0) {
                    hero.xvel += (hero.xvel < 0) ? 5 : -5;
                }
            } else {
                if (hero.xvel != 0) {
                    hero.xvel += (hero.xvel < 0) ? 2 : -2;
                }
            }
            if (Math.abs(hero.xvel) < 3) {
                hero.xvel = 0;
            }
        } else {
            if (!hero.jumping && hero.xvel != 0) { // Not jumping, pressing left or right
                changeAnimation(hero, "run");
            }
        }

        setTimeout(function () {
            hero.yvel += 7;
        }, 250);

        hero.xpast = hero.x;
        hero.ypast = hero.y;
        hero.x += Math.round(event.delta / 1000 * (hero.xvel * 6));
        hero.y += Math.round(event.delta / 1000 * (hero.yvel * 6));

        collisionHandler(hero, objectsCollideAt.it);

        stage.update();
    }

    // Canvas resizing:
    var resizeCanvas = function () {
        stage.canvas.width = window.innerWidth;
        stage.canvas.height = window.innerHeight;
    }
    resizeCanvas();
    $(window).on('resize', resizeCanvas);
}

// Image preloading (Primitive!):

function loadImgs(src, callback) {
    var sprite = new Image();
    sprite.onload = callback;
    sprite.src = src;
}
loadImgs("http://i.imgur.com/RjVQ6e1.png", function () { // Hero Sprite
    loadImgs("http://i.imgur.com/zF6Lhfl.png", function () { // Dirt
        loadImgs("http://i.imgur.com/gTwOePB.png", function () { // Grass 3
            loadImgs("http://i.imgur.com/CT6yf5q.png", function () { // Grass 2
                loadImgs("http://i.imgur.com/5SkIyyM.png", function () { // Grass
                    loadImgs("http://i.imgur.com/QgxGfJs.png", function () { // Rock
                        loadImgs("http://i.imgur.com/50I5K1F.png", function () { // Shadow
                            loadImgs("http://i.imgur.com/dR9195w.png", function () { // Shadow2
                                init();
                            });
                        });
                    });
                });
            });
        });
    });
});

JSFiddle
Answer: I've found the problem in my code. It wasn't working due to the event.which == 1 condition inside the "stagemousedown" event handler. This occurs because, at least on iOS, the event.which is equal to 0.
Here's my final stagemousedown event handler:
stage.on("stagemousedown", function (e) {
    if (event.which < 2) {
        mouse.x = e.stageX,
        mouse.y = e.stageY;

        if (mouse.x > hero.x + hero.width + touch.tollerance) {
            key.right = true;
        }
        if (mouse.x < hero.x - touch.tollerance) {
            key.left = true;
        }
        if (mouse.x > hero.x - touch.tollerance && mouse.x < hero.x + hero.width + touch.tollerance && mouse.y > hero.y - touch.tollerance && mouse.y < hero.y + hero.height + touch.tollerance) {
            key.up = true;
        }
    }
});

Touch events not working EaselJS


Compare two comma-separated columns in two different oracle tables

Question: I want to compare a comma-separated column in oracle table with another comma-separated column in a different table. If the all the values (within comma-separated column and irrespective of their order) on column one are contained within column two  it should not return that row.
For example  -

Column 1 has  a,b,c,def
Column 2 has  a,c,b
This should not be returned as a,c and b in column 2 are contained
within column 1 irrespective of their order.
Column 1 has a,cl,owd
Column 2 has a,owd,pp
This row should be returned because column 2 has 'pp' which is not
contained within Column 1.
Column 1 has vvv,ccc,rr
Column 2 has ccc,rr
This row should not be returned.

Can I accomplish this in SQL ? Not expecting a procedure or function.
Thanks for all the help !!
Comment: You shouldn't be storing comma separated values in a single column in the first place. It would be better if you re-designed your datamodel (i.e. solving the root cause) instead of fighting the symptons of the wrong design.
Comment: Those rules are quite confusing, the description in text vs the examples isn't matching.
Answer: First: I think your example doesn't match your question.
But concentrating on your question: If the all the values (within comma-separated column and irrespective of their order) on column one are contained within column two it should not return that row.
You need to parse the csv into a set (the regexp_substr part) and then check if the set from column two fully contains the set from column one (the minus part):
SELECT *
  FROM csv
 WHERE EXISTS
         (SELECT REGEXP_SUBSTR (col1, '[^,]+', 1, ROWNUM)
            FROM DUAL
           CONNECT BY ROWNUM <= LENGTH (col1) - LENGTH (REPLACE (col1, ',')) + 1
          MINUS
          SELECT REGEXP_SUBSTR (col2, '[^,]+', 1, ROWNUM)
            FROM DUAL
          CONNECT BY ROWNUM <= LENGTH (col2) - LENGTH (REPLACE (col2, ',')) + 1
         )
;

See http://www.sqlfiddle.com/#!4/3cdb3/1 for working example.


Undestanding Memorylessness and Geometirc Random Variables

Question: I know there is a lot on internet about it but I'm still not clear about the concept.Suppose a person starts tossing coins right now.After 4 tosses(all tail) another person enters the room.By independence,the person who enters know given that first 4 tosses were tail see the experiment no differently from the one who was tossing before.Now say the next toss is a head.According to first gut Pr(success on fifth trial) = (1/2)**5 whereas according to second guy = 1/2.Who is corect?
Answer: The idea of memoryless is that if $X$ is geometrically distributed, then
$$
P(X = n | X \ge m) = P(X = n - m),
$$
where $n \ge m$. As you state, the chance of flipping $t,t,t,t,h$ equals $(\frac{1}{2})^5$, so the first guy is right. However, the chance of throwing heads at the fifth flip given that you have thrown four tails equals $\frac{1}{2}$. Note that those are different events.
Answer: Both, only they are not computing the same thing: first guy is considering Pr(first success on fifth trial)=(1/2)**5 while second guy is considering Pr(first sucess on fifth trial|no success in first four trials)=Pr(first success on first trial)=(1/2).


How do I display user signatures in comments?

Question: Drupal 7 has a "personalization" section on ...admin/config/people/accounts
If this exists in Drupal 9, I'd love to know where it is.
The goal: enable signatures for user accounts.
If it's truly gone in D9, the question then becomes what's the best workaround?

A custom field in user account: then how to display that in the comment?
Is there a module I haven't found that does this? I see a signatures module but it appears underdeveloped and lacks the security OK.
Answer: git log -Spersonalization led me to https://www.drupal.org/node/1548204, which leads to https://www.drupal.org/project/signature and https://www.drupal.org/node/2457545. So, this feature was moved to contrib before Drupal 8 launched in 2015 and this functionality is now in the Signature module.
Comment: Not the answer I was hoping for, but it is the answer. Thanks.
Answer: Custom field + twig solution:
It is also possible to use a combination of custom field in 'user' and then print in comments.html.twig
[edit to add version that does not use '|raw']
{{- content|without('links') -}}  {# suppress links #}
    {# add sig #}

     {% set usersig = comment.getOwner.YOUR_FIELDNAME.value %}
            {%  if usersig|length == 0 %}
              {% set usersig = ' ' %}
            {%  endif %}
              {% set sigbody = {
                  '#type':   'processed_text',
                  '#text':    usersig,
                  '#format':  comment.getOwner.YOUR_FIELDNAME.format,
                } %}
              {{sigbody}}

    {# add previously suppressed links #}
   {{content.links}}

[end edit]
Original method (probably not a good idea)...
{{ comment.getOwner.INSERT_CUSTOM_FIELDNAME.value|raw }}

The "|raw" is for formatted text field (renders the html as html). If your field is plain text omit that.
The advantage of this approach is that it is lighter and does not depend on a module that is not ready for production use. Disadvantage: the module appears to offer some more features.
On the safety of the |raw switch - One method is to use the Twig Tweak module's check_markup feature. That and other options discussed here: How to print text (formatted, long) in twig without raw filter?
Comment: `|raw` is usually unsafe.
Comment: Thanks. Will have to fix that. Would it be unsafe if the field is limited to a trusted role and has limited html for its filter? If so, what's best practice for rendering the field safely? I should note that I got that option from here: https://www.drupal.org/docs/8/modules/inline-formatter-field/common-twig-patterns#s-images If it's unsafe, perhaps the documentation needs updating?
Comment: Yes, that is probably a bad example. Official docs on the subject are: https://www.drupal.org/docs/security-in-drupal/writing-secure-code-for-drupal
Comment: Found some info on that.  Editing the answer.
Comment: Added method that does not use '|raw' filter.
Comment: Another edit: In my theme, the signature field was printing below the comment links. The fix was to print the content object with links suppressed, then print the links below the signature. This is now included in the code snippet to make the solution more complete.


Is it OK if I have some high leverage points in my experimental plots and they weren't outliers?

Question: I've analyzed effects of temperature and sample thickness on drying process via response surface methodology. I've faced to four high leverage points (my four axial runs) that stick together on normal probability plot. these points aren't the outlier (on residual versus run plot).
Comment: Why would you care if the points have high leverage if they don't have high Cook's distance?
Comment: Labelling the axes might help.
Comment: so, that's not a problem in my data if I have some high leverage points that aren't outliers and don't have high Cook's Distance?
Answer: Just because a high leverage point isn't an outlier doesn't mean all is well.
A single sufficiently influential point can pull the line essentially right through it (so its residual is 0).
A pair of influential points can easily make each other's externally studentized residuals zero / nearly zero.
So you can have a few points that behave as if they're from a completely different relationship from that you see in (say) 99% of the data, but  they're sufficiently influential, they will have small residuals and even their studentized deleted residuals (/externally studentized residuals) can be small.
This can happen with Cooks Distance (and a variety of other measures of influence) -- the effect of another outlier can make Cook's distance look fine for both.
If you remove all the influential points - as Michael suggests in comments - and the line is little changed, then there should be little to worry about.
Comment: This is true but let's say the slope of the regression line is not changed much when the influential point(s) are left out it doesn't have much effect to include them and it doesn't
Comment: @Michael Yes, that's a good point; if all the influential points (I believe OP mentioned there were four) are together deleted with little effect, there's  no harm in including them (and likely a considerable benefit in estimated variance of coefficients)


transcribing a pause smaller then a measure

Question: I'm transcribing Cappella music. When sometimes there is a small pause less then a measure before starting again the next theme or further melody. My question is how do I notate such a pause.
Answer: That's what either a fermata (on the last note of the ending phrase) or a caesura (after the last note of the ending phrase) are for.
Comment: I think in choral music (which I what I assume you mean), it's more common to use either a breath mark (a 'V-shaped' symbol), or a pause ('comma' symbol).
Comment: Does these two, fermat, caesura good for any length?
Comment: In show music, we always call ceasura "rail-road tracks" because they're indicated with "//"  They are of any length.. and usually rely on cues from the actors on stage.
Comment: Fermata and caesura are of indefinite length.  If you want to be more militant, you can always throw in an out-of-meter measure, such as a 3/8 measure of rest in a 4/4 song.


FTPS server in DMZ. Force different IP addresses for passive mode

Question: I'm setting up an FTP server with TLS/SSL encryption (FTPS, not SFTP). The server would be placed in DMZ. This means that it has tho interfaces: one for connections from the company's network and the other (statically NATed to Internet-valid ip address on a border router) for connections from the Internet.
A small ASCII-art to illustrate the setup:
<code>                  |<----------------------------- DMZ --------------------->|

Inet  <---------> |    border router       |  <-------> FTPS server <------->  Internal network
        184.108.40.206   | 220.127.116.11 <NAT> 10.0.1.1 |     10.0.1.1         10.0.2.2
</code>
Active mode works well. But for the passive mode, FTP server has to send its IP address to the client. First problem is that the server doesn't know its external address (126.96.36.199), only DMZ-external (10.0.1.1). FTP server software allows to set this address (ForceIpAddress in pure-ftpd), but in this case users from internal network will be unable to work with this FTP (because it will send them 220.127.116.11 instead of 10.0.2.2)
So, the question is if there is a method to choose the IP to send according to client IP address or the interface, the request came to? Note that if a client connects from the Internet, he should get Internet-valid IP address (22.214.171.124) insted of server's internal (10.0.1.1). I'm using pure-ftpd but can change to anything else.
I used two FTP servers on different ports and redirected the request using iptables, but this is not the best way, I think.
Some FTP clients (ex. WinSCP) also allow to force the server's address, but not all of them.
Any options to solve the situation?
Comment: I'm not aware of any ftp server that allows setting the IP to use for PASV connections based on the IP of the client, though since you brought it up, it does seem like it would be a reasonable idea to implement an "except for network xx.xx.xx.xx/xx" option for the "force passive mode address" option.  Perhaps you could submit it as a wishlist item?
Answer: The FTP protocol was created when all machines on the internet were globally addressable with a unique IP address. The only reason FTP behind a NAT appliances works now is because the NAT appliance filters FTP traffic and corrects the clear text of the FTP command connection (port 21) to allow for the non-routable addresses involved.
Since you're wrapping your FTP traffic in SSL the NAT appliance cannot read this traffic and so cannot correct for your non-compliant IP addressing. Your solution is going to come from your FTP server.
pure-ftpd has an -N flag that forces "active" mode meaning the FTP server initiates the data transfer (port 20) and will refuse "passive" mode. Passive mode is what FTP clients behind NAT have to use to download from a public FTP site, which you will no longer be compatible with.
proftpd (the best of all posible FTP servers that I've bothered to play with) has a config hack to solve this problem. You can add the "MasqueradeAddress xxx.xxx.xxx.xxx" directive to the config file which will make proftpd tell all clients that the MasqueradeAddress is the ip address of the FTP server. Ensure you have port 20 on this address forwarded with NAT to your FTP server.
As per your note: The "MasqueradeAddress" directive can be used in side the scope of the "VirtualHost" directive, allowing you to provide both the inside access as well as the outside NAT access.
Comment: Thank you for giving me the right direction. Could you, please, edit your answer and note that different "MasqueradeAddress" directives can be used in different "VirtualHost"s? Then the answer will be full. And, of course, I'll accept it. :)
Comment: Not so easy. The problem was that I needed to pass *different* ip addresses in different cases. But while reading about MasqueradeAddress directive, I've noted that it can be used in  context. If I could configure different VirtualHosts for internal and external interface and set different MasqueradeAddress for them, it would solve the problem. I'll try.


Pegar item específico de um fetchAll em PHP

Question: estou usando o código:
<code>$lista = $db->query('select * from tabela') or trigger_error($db->error);
$lista->execute();
$item = $lista->fetchAll(PDO::FETCH_ASSOC);
$mes = 1;
    while ($mes < 13){
    echo $obito[$mes]['total']; //quero listar o total aqui
    $mes++;
}
</code>
Comment: Olá Italo esse $db é uma instância do PDO??
Comment: o que é `$db`? o que é `queryMes`? falta código antes dessas linhas.
Comment: @ItaloRodrigo não simplifique, coloque, realmente o que você esteja fazendo, tudo que for relevante e nos detalhes.
Comment: Pode ser `echo $item[3]['nome'];`
Comment: irei editar a pergunta
Comment: use o `print_r` ou  `var_dump` pra saber se vem como array ou objeto. Se é uma instância PDO, deve vir como objeto.
Comment: Aquele `$lista->execute()` não faz mto sentido. Da um `print_r($obito)` e colque na pergunta, assim todo mundo sabe a estrutura dele.
Comment: é uma instancia pdo sim
Comment: @VirgilioNovic a query funciona bem, é que eu simplifiquei o código acima. a variável $item deve listar todos os meus itens
Comment: editei e postei o código que estou usando agora
Comment: obrigado a todos, consegui resolver
Answer: Você pode tentar o código abaixo;
<code>$host = 'localhost'; // endereço do servidor de banco de dados.
$dbname = 'seu_banco_de_dados'; //nome de sua base de dados
$user   = 'root'; // seu usuário do banco
$pass   = ''; // sua senha do banco

$db = new PDO('mysql:host='.$host.';dbname='.$dbname,$user,$pass);
$lista = $db->prepare(queryMes($ano,$ibge));
$lista->execute();
$item = $lista->fetchAll(PDO::FETCH_ASSOC);

echo $item[3]['nome'];
</code>

Ou pode usar o for para listar...

<code>$host = 'localhost'; // endereço do servidor de banco de dados.
$dbname = 'seu_banco_de_dados'; //nome de sua base de dados
$user   = 'root'; // seu usuário do banco
$pass   = ''; // sua senha do banco
$lista = $db->prepare(queryMes($ano,$ibge));
$lista->execute();
$item = $lista->fetchAll(PDO::FETCH_ASSOC);

foreach($item as $info) {
    echo $info['nome']."<br/>";
}
</code>
Comment: Ah ítalo você não esta usando o PDO?
Comment: sim coloque if(isset($item[$i]) { echo 'Existe';   }
Comment: Corrigi a resposta, altere os valores para os dados do seu banco de dados.
Comment: são objetos diferentes. só conferir no manual. [PDO Manual](http://php.net/manual/pt_BR/book.pdo.php) e [MySQLi Manual](http://php.net/manual/pt_BR/class.mysqli.php)
Comment: na linha $obitos->execute(); dá erro Fatal error: Call to undefined method mysqli_result::execute()
Comment: editei e botei o código que estou usando agora, por favor dá uma olhada
Comment: funcionou sim, obrigado. voce pode me explicar a diferença entre: $db = new mysqli(); e $db = new PDO();
Comment: sem querer abusar da sua boa vontade, só falta mais um detalhe pra eu concluir o trabalho. como saber se $item[$i] existe?