Sum of Indicators: $\sum_{n=1}^{\infty} \mathbb{1}\{X_1^2/\alpha^2 \geq n\} = \left(1 + \left\lfloor\frac{X_1^2}{\alpha^2}\right\rfloor\right)$

Question: I was working on proving the following proposition:

Suppose $(X_n)$ is some iid sequence of random variables such that $\mathbb{E}(X_1)^2 < \infty$. Then for every $\alpha > 0$ we have
$$\mathbb{P}\left(\limsup_{n \to \infty}|X_n| \geq \alpha\sqrt{n}\right) = 0.$$

Proof. We wan't to invoke the Borel-Cantelli Lemma (B.C.), so since $X_n$ are iid we have
$$\sum_{n=1}^{\infty}\mathbb{P}(|X_n| \geq \alpha\sqrt{n}) = \sum_{n=1}^{\infty}\mathbb{P}(X_n^2 \geq \alpha^2 n) = \sum_{n=1}^{\infty}\mathbb{P}\left(\frac{X_1^2}{\alpha^2} \geq n\right).$$
Using the Monotone Convergence Theorem, we can represent the right-most term as
$$ \sum_{n=1}^{\infty}\mathbb{P}\left(\frac{X_1^2}{\alpha^2} \geq n\right) =  \sum_{n=1}^{\infty}\mathbb{E}\left[\mathbb{1}\left\{\frac{X_1^2}{\alpha^2} \geq n\right\}\right] = \mathbb{E}\sum_{n=1}^{\infty} \mathbb{1}\left\{\frac{X_1^2}{\alpha^2} \geq n\right\}.$$
Therefore,
$$\mathbb{E}\sum_{n=1}^{\infty} \mathbb{1}\left\{\frac{X_1^2}{\alpha^2} \geq n\right\} = \mathbb{E}\left(1 + \left\lfloor\frac{X_1^2}{\alpha^2}\right\rfloor\right) \leq 1 + \frac{\mathbb{E}X_1^2}{\alpha^2} < \infty.  \tag{1}$$
So, we can invoke B.C. and are done. The bit about the indicator equality involving the floor function is given as a hint without going into detail.
Question.  How do we get the equality involving the floor in (1)? Specifically, I don't see how
$$\sum_{n=1}^{\infty} \mathbb{1}\left\{\frac{X_1^2}{\alpha^2} \geq n\right\} = 1 + \left\lfloor\frac{X_1^2}{\alpha^2}\right\rfloor.$$
Could someone expand on this derivation please?
Answer: I think there is a slight mistake. (I am interpreting $\left\lfloor x \right\rfloor$ as the greatest integer less than or equal to $x$).  If the sums are  from $0$ to $\infty$ then you get the value as stated, but otherwise you will get $\left\lfloor\frac{X_1^2}{\alpha^2}\right\rfloor$ instead of $\left\lfloor\frac{X_1^2}{\alpha^2}\right\rfloor +1$
Suppose $\left\lfloor\frac{X_1^2}{\alpha^2}\right\rfloor=k$. Then $k \leq \left\lfloor\frac{X_1^2}{\alpha^2}\right\rfloor <k+1$. So  the only integers $n$ such that $\frac{X_1^2}{\alpha^2}\geq n$ are $n=1,2,...,k$. So when you add the indicators on LHS you see that $k$ terms are $1$ and the rest are zeros. Hence the sum is exactly $k$.
Comment: On closer inspection, I did mean to have sums from $0$ to $\infty$. Nonetheless, your explanation of $\lfloor \cdot \rfloor$ clears it up for both the $n=0$ and $n=1$ case.
Answer: I guess there's a small mistake in the end. Fix any $\omega \in \Omega$ . Then, $\frac{X_1(\omega)^2}{\alpha^2}$ is a finite quantity, so $\exists~ N_\omega \in \mathbb{N}$ such that $$\frac{X_1(\omega)^2}{\alpha^2} \geqslant  N_\omega\quad~\text{ and }~\quad \frac{X_1(\omega)^2}{\alpha^2} < N_\omega +1$$ and hence, $\left\lfloor\frac{X_1(\omega)^2}{\alpha^2}\right\rfloor = N_\omega$
Thus, for $n = 1 , 2 , \cdots , N_\omega$ , we have : $\mathbb{1}\left\{\frac{X_1(\omega)^2}{\alpha^2} \geq n\right\} = 1$ and otherwise, $0$ .
Therefore, $$\sum_{n=1}^{\infty}\mathbb{1}\left\{\frac{X_1(\omega)^2}{\alpha^2} \geq n\right\} = \sum_{n=1}^{N_\omega}\mathbb{1}\left\{\frac{X_1(\omega)^2}{\alpha^2} \geq n\right\} = N_\omega = \left\lfloor\frac{X_1(\omega)^2}{\alpha^2}\right\rfloor$$
Since this result is true for any $\omega \in\Omega$ , therefore : $$\sum_{n=1}^{\infty} \mathbb{1}\left\{\frac{X_1^2}{\alpha^2} \geq n\right\} = \left\lfloor\frac{X_1^2}{\alpha^2}\right\rfloor$$

It is to be noted that even after this correction, Borel - Cantelli lemma works fine, so you'll obtain what you wanted. Hope it helps.
Comment: I did actually mean sums $0$ to $\infty$ in the end, but your answer is a nice addition.
Comment: Ohh. Then you can just take sum from $0$ and you'll yield the same thing, with an additional $1$ added to the final sum (Precisely your result).


Does $\operatorname{rank}(T) = \dim(W)$ imply linear transformation is onto.

Question: If you have a linear transformation going from $V,W$, where $V,W$ are finite-dimensional vector spaces. Does the $\dim(\operatorname{range}(T))$ being equal to the dimension of the target space imply that the linear transformation is onto. If it does do you mind explaining why.
Answer: rank $T$ is the dimension of the range of $T$. So the range of $T$ is a subspace of $W$ that has the same dimension as $W$, hence the image is $W$, or in other words, $T$ is onto.
This argument relies on the fact that a subspace $U$ of $W$ that has the same dimension as $W$ is $W$ (call this dimension $n$). We can prove this easily.
Take a basis for $U$, it has $n$ elements, since the basis is a linearly independent subset of $W$ it can be extended to a basis of $W$, of course all the basis for $W$ have $n$ elements, so the extension consists on adding nothing, therefore the basis for $U$ is a basis for $W$ and hence $U=W$ as desired.


How to return no result in search filter in react native

Question: I am fetching my data from an API. I want that when I search something and if no data found then it should simply appear no result found in text format on the screen. But idk i am not being able to do that. Pls look at my code. thanks
filtering here:
  latestFeatured = value => {
    const latestFeatured = this.state.inMemoryLatest.filter(item => {
      let latestLowercase = item.speaker.toLowerCase();
      let latestTermLowercase = value.toLowerCase();
      return latestLowercase.indexOf(latestTermLowercase) > -1;
    });
    this.setState({
      latestuploads: latestFeatured,
    });
  };

return statement:
<TextInput
    onChangeText={value => {
      this.latestFeatured(value);
    }}

    style={styles.textInput}
/>

Answer: You can try a conditional render, with:
{ this.state.latestuploads && (
    <TextInput
        onChangeText={value => {
          this.latestFeatured(value);
        }}

        style={styles.textInput}
    />
)}

Here, the TextInput will only appear if this.state.Latestuploads it's not empty.
I don't really undertand your code entirely, but make sure you put the right state on the place of this.state.Latestuploads .


Running R Scripts on a server?

Question: I would like to install R on a server (linux) where I could create shell scripts to execute R scripts on the server. Does R support this?
Answer: Why wouldn't it? For example you can find R as a webapp or R Studio over ssh as more complex examples or just login via ssh and use R.
Comment: I'm a little unsure as to which Linux install to use on my server and how to execute R Scripts from within the command line.
Comment: Linux distros for servers are a matter of taste. I usually go with debian but you can use whatever you are used too (if you are new to linux I think debian and ubuntu have the most guides on server setup). R over commandline can be found in this question for example http://stackoverflow.com/questions/18306362/run-r-script-from-command-line
Comment: So I have to install a Linux distro on my server and then install R along with it?
Comment: Yep if u rent a server (virtual or full) it usually comes with a distro of your choice pre installed. If you build it yourself you would have to install it yourself. Installing R should be easy. For debian it's just  `apt-get install r-base` and an additional `apt-get install` for the additional packages see http://cran.r-project.org/bin/linux/debian/
Comment: Thank you so Trudbert! I appreciate your patience :)

Running R Scripts on a server?


How to create HOC to wrap useContext provider in React?

Question: I want to reuse a context provider in different parts of my app using HOC ("higher order components"), but my state does not get updated.
This is the wrapper of the provider.
import React, { FC, useState } from "react";
import AdminContext from "./adminContext";

const AdminContextWrapper: FC = ({ children }) => {
  const [authAdmin, setAuthAdmin] = useState<boolean | null>(null);

  const value = { authAdmin, setAuthAdmin };
  return (
    <AdminContext.Provider value={value}>{children}</AdminContext.Provider>
  );
};

export default AdminContextWrapper;

This is how I am implementing it :
import { useContext } from "react";
import AdminContext from "@comp/contexts/adminContext";
import AdminLogin from "@comp/admin/adminLogin";
import Limit from "@comp/admin/limits";
import AdminContextWrapper from "@comp/contexts/adminWrapper";

const Admin = () => {
  const { authAdmin } = useContext(AdminContext);

  const AdminPage = () => {
    return (

        <Limit />

    );
  };

  return (
    <AdminContextWrapper>
      {authAdmin ? <AdminPage /> : <AdminLogin />}
    </AdminContextWrapper>
  );

Finally, this is my context:
import { createContext } from "react";
import { AdminContextType } from "@comp/utils/types";

const InitialUserContext: AdminContextType = {

  authAdmin: false,
  setAuthAdmin: (authAdmin: boolean | null) => {},

};

const AdminContext = createContext<AdminContextType>(InitialUserContext);

export default AdminContext;

I can see the state change in the login page but the admin page is not getting the update.
adminLogin.tsx
//...
 const { setAuthAdmin, authAdmin } = useContext(AdminContext);

 useEffect(() => {
    console.log(authAdmin); // returns true after validating but the admin does not update.
  }, [authAdmin]);
//...

I highly appreciate any help. Thank you.
Answer: Unless I'm misreading things, in
const Admin = () => {
  const { authAdmin } = useContext(AdminContext);
  // ...
  return (
    <AdminContextWrapper>
      {authAdmin ? <AdminPage /> : <AdminLogin />}
    </AdminContextWrapper>
  );
}

you're trying to use the context outside its provider AdminContextWrapper - useContext would return undefined there unless you're already nested within another provider for the admin context, in which case the inner AdminContextWrapper there would give the inner components a  different admin context.
You may want to make sure there's only ever exactly one admin context.
(As an aside, the // ... above used to be a nested component in your original code. Never do that – nested components' identity changes on each update, causing spurious re-renders.)
Comment: You are right, I am having two contexts. Thank you!!
Comment: https://stackoverflow.com/questions/67770959/react-how-to-change-state-value-from-child-to-parent-using-usestate-and-useconte


Como encerrar uma sessão por inatividade usando Angular7

Question: Gostaria de encerrar a atividade do usuário se não houver clique em qualquer página da minha aplicação, estou usando Angular e o Nebular.
Comment: Jefferson dá par ser feito com Angular, poderia postar algum código que tenha tentado e colocar mais informações como o período que o usuário fica sem interagir com a tela para disparar a inatividade.
Answer: No javascript existe uma função para você fazer isso.
<code>setTimeout(function(){
  alert("Teste");
}, 3000);
</code>
Comment: Mas eu gostaria que ele identificasse que não houve clique com o mouse, nesse caso funcionaria?
Comment: Acho que essa resposta pode te ajudar:

[IdleTime](https://stackoverflow.com/questions/667555/how-to-detect-idle-time-in-javascript-elegantly)


How to Connect Pt 1000

Question: I am trying to connect a 2-wired PT 1000 to a micro-controller board .... Does anyone has any idea how this should be done? I did not try anything since I am afraid to blow the ADC of the board
Comment: Better asked on the http://electronics.stackexchange.com/
Answer: Assuming your PT1000 is a RTD (Resistive Tempurature Device) max resistance of 1000 ohms. You can simply use a voltage divider, as shown in the picture. Since it is a passive circuit, now way to exceed 5V, it is safe.

Ideally you will want to bias the divider to mid range (or 2.5v). So you will want to replace the 3.9K with something better. But the below will get you initially going.
Comment: by any chance do you have a guide software for the PT1000 or PT100 because I did not find any

How to Connect Pt 1000


Forçar formato numérico/língua para o documento

Question: Onde trabalho é muito comum termos problemas com as macros de excel, que geram tabelas e gráficos, dependendo da língua e da versão do Excel que o cliente está usando.
Como forçar uma língua (por exemplo inglês) e consequentes formatos numéricos?
Dessa forma uma trinta porcento apareceria, por exemplo, sempre como 30.00% e um milhar sempre como 1,000.00 independente da língua do usuário?
PS.: Sei que é possível usar .NumberFormat em cada célula, mas estou procurando por uma configuração global que resolva todos os números dentro do documento.
Comment: Pergunta totalmente válida. Até hoje não encontrei como normalizar a localização de arquivos gerados via código.
Comment: @gmsantos creio que com a resposta abaixo fica ok! Creio que quando o mathiasfk testar irá colocar marcar como respondida.
Answer: Se quiser utilizar a o ponto ao invés da vírgula em todo os campos da planilha poderá acessar o menu EXCEL > OPÇÕES > AVANÇADO > 'Usar separador de sistema' e definir o que deseja.
Para fazer isso via código no VBA utilize a seguinte função:
Function setSeparadorDecimal()
  With Application
    .DecimalSeparator = "."
    .ThousandsSeparator = ","
    .UseSystemSeparators = False
  End With
End Function

Conforme advertido pelo nosso amigo @mathiasfk, a função acima altera a Aplicação e não somente o arquivo ativo, portanto, caso seja interessante retornar o separador decimal do Excel para o padrão, utilize a função abaixo:
Application.UseSystemSeparators = True

Espero ter ajudado!
Comment: Um aviso à quem for usar isso: Essa configuração fica salva no Excel mesmo após o arquivo ser fechado, então é uma boa prática voltar à configuração original no final da sua macro. `Application.UseSystemSeparators = True`
Comment: Obrigado! No caso penso que iria resolver apenas para essa cópia do Excel, no caso, a da minha máquina. O meu grande problema é que cada cliente pode ter uma configuração diferente.
Comment: @mathiasfk editei a resposta e creio assim conseguirá forçar o arquivo a utilizar o separador que deseja. Caso esteja correta a resposta, marque como resolvido. Abs!
Comment: Perfeito! Exatamente o que eu procurava.


Intuition for why sum of gaussian RVs is different from gaussian mixture

Question: I know that in the case of Gaussian mixture, the "intuition" is that you're drawing from a PDF which itself is just a sum of weighted Gaussian PDFs.
I don't understand the intuition behind how the sum of two iid Gaussian RVs leads to a Gaussian RV. I know the maths behind it, but I'm having a hard time visualizing how the sum of two Gaussian RVs leads to a Gaussian RV (and not a mixture).
Comment: Adding two random variables $\neq$ adding two density functions
Comment: @HongOoi I got that. The (accepted) answer below does a great job of explaining things.
Answer: Forget the Gaussian part for a moment. Compare these two simple situations:
A) take a coin whose two sides are marked with 0 and 1 and a die with 20 sides numbered 1 to 20. Toss the coin and roll the die --- and add the results to get a total.
Consider these questions (and hints):
What's the chance you get a total of 0?  (you can't!)
What's the chance you get a total of 1?  (need 0 on the coin and a 1 on the die)
What's the chance you get a total of 11? (You need (0,11) or (1,10) here)
What's the chance you get a total of 21? (need (1,20) here)
B) take the same coin and the same die and choose which one to use, by tossing a second coin labelled "coin" and "die". Now your total is the number showing on whichever object you tossed or rolled at the second step.
What's the chance you get a total of 0?  (get this by tossing ("coin",0) )
What's the chance you get a total of 1?  ( ("coin",1) or ("die",1) )
What's the chance you get a total of 11?  ( ("die",11) )
What's the chance you get a total of 21?  (you can't!)
The first case (A) is a sum of random variables (convolution of the p.m.f.s). The second case (B) is a mixture (weighted average of p.m.f.s).

They're entirely different kinds of things.
Now consider a Gaussian case. For example, if X ~ N(0,1) and Y ~ N(100,10) - where the two are independent - then X+Y has almost no chance of being between -1 and 1 (the contribution of Y makes the sum very far above values like those), but a 50-50 mixture of X and Y has quite a good chance of being between -1 and 1.
In the case of iid Gaussians (as you suggest in comments), let's simplify further and take the example of the standard normal case (because it's the same up to scale and location shifts that don't alter the distribution shape of either the inputs or the output), though I'll talk about more general cases. First we have to see what calculating distributions for sums of random variables (particularly independent ones) involves; this is necessarily somewhat mathematical but I'll try to motivate what's going on rather than just do the algebra (which is easy to find done for the Gaussian case anyway so I'll just be explaining what happens rather than repeating what's easily found)
With discrete variables (as above) to compute the probability of a sum, you have to add the probabilities of all the distinct events that have that sum. So if $Z=X+Y$, $P(Z=z)=\sum_x P(X=x)P(Y=z-x)=\sum_x p_X(x)p_Y(z-x)$ (product because of independence of $X$ and $Y$, and $x$ ranges over the values possible for $x$ in that sum).
This is discrete convolution.
Similarly for the continuous case -- we add over the cases that give the sum -- .
So $f_{Z}(z)=\int_x f_X(x)f_Y(z-x) dx$
... this is a convolution integral. In particular, see the animation in the second diagram here$^{[1]}$
For standard normals, that integral is just $\int_{-\infty}^{\infty} \frac{1}{\sqrt{2\pi}}e^{-\frac12 x^2} \frac{1}{\sqrt{2\pi}}e^{-\frac12 (z-x)^2} dx$
But note that we have a quadratic-in-x in both exponents, so when we multiply them we're just adding the quadratics -- giving another quadratic (clearly this same idea applies for any independent Gaussians whatever their means and variances, and indeed, will generalize up to the jointly-normal case).
So we end up with exp of (a quadratic in x with negative leading term). Because we can complete the square, we can split the quadratic into two terms -- the quadratic becomes  $k.(x-\text{something})^2$ + a term not in $x$ (which drops out the front of the integral, since as far as the integral in $x$ is concerned, it's a "constant").
In our simplified example that should look something like $2(x^2-z/2)^2+z^2/4$.
The first thing is (up to a scaling factor) a density in $x$, so if you pull out the required scaling factor from the scaling constant on the bivariate you started with you're left with an integral of a normal density. The remainder of the original scaling factor goes out the front, and the integral is $1$ (it's a density!). What's left out the front is $\exp$ of a quadratic in $z$ with a negative leading term (i.e. a Gaussian), times just the required scaling constant to make it a density.
In short, the reason why convolutions of Gaussians are Gaussian is because products of $\exp$s are $\exp$s of sums and sums of quadratics are also quadratics. If your quadratics have negative leading terms (as they will for Gaussians), the sum is also going to have a negative leading term. So convolutions of Gaussians must be in the form of Gaussians.
Another simple/intuitive argument is as follows: Again consider the iid-bivariate Gaussian case $(X,Y)$, where the contours are circular. Without loss of generality, make it centered at the origin. Now if we rotate 45 degrees
\begin{equation}
        \begin{pmatrix}
        U \\
        V \\
        \end{pmatrix} =
        \begin{pmatrix}
        \sqrt{\frac12} & \sqrt{\frac12} \\
        \sqrt{\frac12} &-\sqrt{\frac12} \\
        \end{pmatrix}
        \begin{pmatrix}
        X \\
        Y \\
        \end{pmatrix} =
        \begin{pmatrix}
        \sqrt{\frac12}(X+Y) \\
        \sqrt{\frac12}(X-Y) \\
        \end{pmatrix}
\end{equation}
we still have the same circular-bivariate Gaussian density centered at the origin. So $U$ and $V$ are also iid Gaussian with the same mean and variance as (X,Y). But $U$ is just a scaled $Z$, so $Z$ is also Gaussian. (We can generalize to the non-zero-mean case by simple shifts)
There are a number of proofs for the Gaussian case here; generally using characteristic functions (/Fourier transforms) or by using the convolution integral. I don't know that they're necessarily going to be intuitive for you. However, if you're used to characteristic functions/Fourier transforms that pretty much gives it to you immediately and might convey some of the intuition; in particular the Fourier transform of a Gaussian is Gaussian in form, and the product of two scaled Gaussian functions in the same variable is another scaled Gaussian, and convolution in the time domain equals multiplication in the frequency domain, so we see that the convolution of two Gaussians is Gaussian.
In any case it's useful to have the proofs so you see in more detail where my prior handwaving about quadratics is coming from.
$[1]$  Weisstein, Eric W. "Convolution." From MathWorld--A Wolfram Web Resource. https://mathworld.wolfram.com/Convolution.html
Comment: @mdewey The OP's comment "any physical examples which would help me think of the sum being Gaussian" suggests that learner is pretty happy with everything except some kind of intuition about why sums of independent Gaussians are Gaussian, which they hope to gain via a "physical example". At least that's how I read it. That's a tricky task; the closest I have been able to get to it is the geometric argument with the rotation of the bivariate iid normal
Comment: That's good intuition! But I don't immediately see if this also gives intuition about the sum of two gaussian RVs _also_ being Gaussian. Did I miss that?
Comment: Actually, it's not true in general (as discussed elsewhere on site). Which subset of the cases for which it is true do you want? Just the independence case?
Comment: In $Z \ = \ X + \ Y$, $X$ and $Y$ are iid Gaussian.
Comment: Okay, try it now.
Comment: This is a good mathematical explanation. I was just wondering if you had any physical examples which would help me think of the sum being Gaussian, as well. I do think that would be a difficult thing to do, though. I'll try to think of that now.
Comment: I really don't see what example could justify an essentially mathematical result (closure of Gaussians under convolution). That convolutions tend to be more hump-shaped than their arguments might be possible to justify intuitively / by examples, but I really don't quite see what you could really seek there in relation to the closure of Gaussians under convolutions. Actually, I have one idea, but it's still essentially mathematical, though geometrical, maybe that will suit you better. (now added above)
Comment: (+1) the coin die example is very neat and, it strikes me, is almost the physical example the OP seeks.
Comment: @Glen_b This is brilliant. Thanks for all the help!


Send Email with Different Accounts

Question: I've been searching but didn't find much.
Is there any module or way to send emails with Drupal, but using different email accounts?
For example, I have a site which will have 3 different email accounts to send email.
User A creates a node, the user will receive an email from the email account 1.
User B takes an action, he or she will receive an email from the email account 2.
Etc.
To sum up:
Is there any module to hold different email accounts in one drupal site and send email with them?
I've seen some modules to hold different email accounts for the users, but not for the site.
Thanks in advance.
Answer: Nice question  you are right  no module for that . but  you can configure it by rules
like
after saving node
add action - sand e-mail userA
on this add conditions according to your need
like  account type userA
I think this is the possible way for that
Comment: Thanks for your answer. That could be a possible solution, but the problem is the account which sends the email, it must be different depending on the case. Changing the From field of the email without changing the email which truly sends the email will trigger the spam filters.
Comment: well for this we have use token
Comment: But token is different if  userA is like seller type  userB is buyer type so we can create  token for email and then  add action on it
Comment: I'm afraid that creating a token to change the From field will not solve the problem, still we can't change the email account from where the messages are sent.
Answer: You can use hook_mail_alter() for altering the from email address. You can check the message id accordingly and change the from address.
<code>function MODULE_NAME_mail_alter(&$message) {
  if (isset($message['id']) && !empty($message['id'])) {
    if ($message['id'] == 'your condition') {
      $message['from'] = $message['headers']['From'] = 'your email address';
    }
  }
}
</code>
Comment: Thanks for your answer! Tried this and tried with the $message['headers']['Sender'] = $message['headers']['Return-Path'] fields too.
The problem is that the email is rejected because of spoofing, we are sending always with the same account, and changing "on-the-fly" some of the fields.
We send with firstname.lastname@example.com, but we need to send with email@example.com too.
Unfortunately changing the headers does not solve the problem.

Send Email with Different Accounts


PHP $_SERVER['REMOTE_ADDR'] sometimes resolves to empty string

Question: When accessing my site from a number of machines $_SERVER['REMOTE_ADDR'] always resolves to an empty string. What can be the cause of this?
Additional info:
One of the machines is running the site on localhost. Shouldn't a machine on localhost always resolve to 127.0.0.1?
My set up is LAMP. One dev. machine that runs the site localhost and that has the problem is a Mac and runs XAMPP. I think our live staging environment is CentOS (shared host).
Comment: What web server software, and what version of PHP?
Comment: Are you doing a `gethostbyaddr()` lookup on `REMOTE_ADDR`?
Answer: I guess this results from a missing reverse delegation for the address. You should avoid reverse resolution unless absolutely necessary.
Not only is it expensive in terms of latency, but can also yield unexpected results as there is no requirement on what to resolve to - or to resolve at aall.
Comment: I think you're thinking of REMOTE_HOST. REMOTE_ADDR is the IP address.
Answer: I just ran into this problem, and it turns out that the PHP code was setting it to <code>''</code> explicitly before running my code. This was because the IPv6 remote addr didn't match its IPv4 only regex.
Leaving this here in case someone else has the same problem, it was a too simple reason for me to spot it.
The module in question was simplemachinesforum.
Answer: Try looking at phpinfo() from those machines and see what they present.
Comment: That will take some time. Not all machines are under my control.


Isomorphism between $(V^*)^{\otimes k}$ and $(V^{\otimes k})^*$

Question:
Is there a natural isomorphism between $(V^*)^{\otimes k}$ and $(V^{\otimes k})^*$ ?

I don't know how to proceed and will appreciate a hint. Thanks!
$(V^{\otimes k})^*$ is a vector space and so is isomorphic to $(V^{\otimes k})$. Now, I need to show isomorphism between $(V^*)^{\otimes k}$  and  $(V^{\otimes k})$. I can't proceed beyond this point.
Here dual of a vector space $W$ is $W^*$.
Comment: Yes, but that's certainly not how you go about it; there isn't a natural isomorphism between a vector space and its dual. Try to find a way to pair elements of $(V^{\ast})^{\otimes k}$ with $V^{\otimes k}$.
Comment: Not literally a duplicate, but reading this question and its answer should help you: http://math.stackexchange.com/questions/1487482/natural-isomorphism-v-otimes-w-cong-v-otimes-w.  Note that you need $V$ to be finite-dimensional.
Comment: @QiaochuYuan I am think I am getting this wrong but for $k=2$, if $\{v_i\otimes v_j\}$ is the basis of $V\otimes V$ and $\{v_i^*\otimes v_j^*\}$ is the basis of $V*\otimes V$, then can we not send $v_i\otimes v_j$ to $v_i^*\otimes v_j^*$? The map I am thinking of is $f(a)=f(\sum a_{ij} v_i\otimes v_j)=\sum a_{ij}v_i^*\otimes v_j^*$
Comment: The above map is injective and linear. Also, $\dim (V^*\otimes V^*)=n^2=\dim(V\otimes V)*$ so it is an isomorphism.
Comment: That map isn't natural; if you pick a different basis you'll get a different map. One way to say what "natural" means is that you can talk about it without choosing a basis.
Comment: @QiaochuYuan, I see. I am not really able to think of  a natural isomorphism.
Answer: By definition, there's a natural dual pairing $V \otimes V^{\ast} \to k$ ($k$ the underlying field). Apply the dual pairing $n$ times to get a natural pairing
$$V^{\otimes n} \otimes (V^{\ast})^{\otimes n} \to k.$$
This gives a natural map $(V^{\ast})^{\otimes n} \to (V^{\otimes n})^{\ast}$. Can you show it's an isomorphism (when $V$ is finite-dimensional)?


Algoritmo Desligando Tela do PC após execução

Question: Estou utilizando a windows.h em conjunto com C++, com a finalidade de criar uma rotina através dos eventos de INPUT. Tais como setar a posição do mouse na tela, clicar e coisas do gênero, porém toda vez que executo qualquer uma das duas funções, a tela apaga em seguida (Como se tivesse ficado ausente por muito tempo), pois basta movimentar o mouse que ela volta.
void setMousePos(int posX, int posY){
    INPUT Input;
    Input.type = INPUT_MOUSE;
    Input.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;

    Input.mi.dx = posX*(65535.0f/GetSystemMetrics(SM_CXSCREEN));
    Input.mi.dy = posY*(65535.0f/GetSystemMetrics(SM_CYSCREEN));
    SendInput(true,&Input, sizeof(Input));
}

void onClick(){
    INPUT Input;
    Input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
    SendInput(true, &Input, sizeof(Input));
    Input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
    SendInput(true, &Input, sizeof(Input));
}

Ele simplesmente executa as funções, e em seguida, apaga a tela. Alguma do Por Que está ocorrendo o mesmo?
O Problema está na multiplicação pelo resultado da divisão 65535.0f/GetSystemMetrics(SM_CXSCREEN);
Se eu executo a conta com um numero normal (1280 por exemplo), ocorre tudo bem, porém quando utilizo uma variável (posX por exemplo), ele é a causa do apagão.

Sistema Operacional: Windows 8.1
Linguagem: C++
Biblioteca: windows.h
Comment: Olá, fico feliz que você tenha corrigido o problema. Mas, sendo assim, por favor crie você mesmo uma resposta detalhando a sua solução (e a marque como aceita). **Não edite a pergunta para incluir a solução**, poir esse site não é um fórum. Se não fez ainda, por favor leia a [help]. :)
Comment: Quase você criou o seu primeiro vírus, já pode mandar pro seus amigos pra perturbar eles :) - Brincadeiras a parte, que bom que conseguiu resolver, recomendo que poste a função "inteira" como ficou.
Comment: Descobri que na realidade, o problema não é a divisão, e sim a multiplicação feita após obter o resultado da divisão. Porém, se eu executo a conta com números normais, não há problema algum, exemplo: Input.mi.dy = 800*(65535.0f/GetSystemMetrics(SM_CYSCREEN));. Porém se no lugar do 800 eu utilizar uma variável, isto causará o apagão.
Comment: Resolvi o problema por enquanto. Ao invés de criar um INPUT toda vez que executasse a função, coloquei-o para passar como argumento: void setMousePos(int posX, int posY, INPUT& Input). Desta forma inicializo o mesmo na função main.
Comment: Você pode zerar a estrutura toda, ao criar o INPUT. o importante é, por exemplo, como vc nao usa o x e o y no click, zere eles na função click. Os membros que vc nao usar no move, zere na função de mover, e assim por diante. Mais fácil é você zerar a estrutura toda ao criar o input, o que é relativamente simples. Isso não vale só pra esse caso. Sempre que usar uma estrutura desse tipo, tenha a certeza de ter ela limpa;
Answer: Problema Resolvido. E agradecimentos à Luiz Vieira por ter me orientado, e a Bacco por ter me ajudado.
A solução foi ao iniciar o INPUT, seta-lo como 0:
setMousePos(int posX, int posY){
    INPUT Input={0} // A resolução do problema foi simples assim
    .......... /Resto do Código
}


How to reload a table view in a view controller in iPhone?

Question: I am new to iPhone development. I have created a table view in a view controller. I want to reload the table view so that I can display the contents which are parsed previously in delegates. More over reloadData does only reload the cells. It doesn't take care of actually updating the underlying datasource.
E.g. if I read data from an array in tableView:cellForRowAtIndexPath:, I have to change the array values before calling reloadData.
How can I achieve this?
Answer: It sounds like you need a manager class (or something) to encapsulate the process of requesting, downloading, parsing the data and updating your model objects.
You can use delegation to tell the view controller to reload after you've done all of the above.
Answer: If you have a delegate method that returns you the values that that needs to be refreshed in the TableView do the following:
- (void)didFetchData:(NSArray*)dataList
{
    //Update the dataSource List that is used in the tableView
    self.dataSourceList = [NSArray arrayWithArray:dataList];

   //Now call the reload method to update the data.
   [self.tableView reloadData];
}

Note: Always make sure you update the dataSource object and then call the [tableView reloadData]


Exclude test code in npm package?

Question: The devDependencies section of npm's package.json documentation says to list your test dependencies there so that users of your package don't have to pull down extra dependencies. Would it make sense to also add my test directory to .npmignore in that case?
Comment: See related: https://stackoverflow.com/questions/25124844/should-i-npmignore-my-tests
Answer: Yes that's what most people do, here are some npmignore files for popular Node.js modules:
https://github.com/socketio/socket.io/blob/ab46351a8446516fb4eea3b8333f7c0f18afaac5/.npmignore
Other people allowlist what they want published in their package.json files setting:
https://github.com/senchalabs/connect/blob/master/package.json

https://github.com/strongloop/express/blob/master/package.json
Comment: I would suggest that if people want to run tests for my module/package, they would actually take the time to clone my repo and run `npm install` so they get all the actual development dependencies. It sucks big time when you start depending on some module that happens to have about 20 megabytes of autogenerated test code published to npm (e.g. moment-timezone <= 0.0.3), along with a bunch of test frameworks that I don't need in order to use the module.
Comment: Some might find it useful to keep tests there so people can do `npm test module` if for some reason something isn't working and they want to test the modules they're using.
Comment: first link is broken
Answer: One thing that I haven't been able to find explicitly mentioned anywhere is the fact that the "files" entry in package.json supports using a ! prefix on an entry. So, for example, I have a "files" entry that looks like this:
{
  "files": [
    "lib/**/*",
    "!lib/**/*.map"
  ],
}

I do that because my lib directory includes .map files that I don't want to include in the package, and this includes everything but the *.map files.
Comment: Yes, it says, "File patterns follow a similar syntax to .gitignore, but reversed..." Since .gitignore allows bang characters, I tried it out, and it worked for me. I don't know why it's not working for you.
Comment: `!/src/**/__tests__/*.test.ts` worked for me.
Comment: The files entry is documented to to follow a similar syntax to .gitignore, but reversed. See: https://docs.npmjs.com/cli/v9/configuring-npm/package-json#files
Comment: Is this documented somewhere? I can't get this to work (npm v8) and neither can I find any documentation about it.
Comment: It definitely worked for me in npm 6, but I'm not sure I've tested it in npm 8. However, even though the npm documentation link above is for v9, the v8 documentation says the same thing (replace v9 with v8 in the link).
Comment: Doesn't say anything about excluding files. Just says that you can include files by using patterns similar to the gitignore :/
Answer: Another approach is to use a lib folder and store everything in there. Then you can configure your package.json to consider only that folder.
In order to work you need also to move your main file inside lib and specify it in the package.json. See example below:
{
  "name": "your-package",
  "main": "./lib/index.js",
  "files": [
    "/lib"
  ]
}

More info are available on this nice article

Exclude test code in npm package?


What is the purpose of userError and isUserError functions?

Question: I'm exploring the exception mechanism in Haskell. I have figured out how catch and handler functions work.
main = toTry `catch` handler

handler :: IOError -> IO ()
handler e
    | isDoesNotExistError e = putStrLn "The file doesn't exist!"
    | otherwise = ioError e

The type of userError is String -> IOError. As I understand, that means we can pass userError as e in the aforementioned handler. Hoogle says about userError "Construct an IOError value with a string describing the error." But how to actually construct userError and what is the purpose of it? userError takes only a String, how can it possibly do anything?
For example, the aforementioned isDoesNotExistError e has its like own internal logic (as I understand), which deals with "does not exist" case. But we construct our own userError :: String -> IOError using only a String, so after all, is userError kind of a synonym for our String?
I would be grateful if you showed a simple example of using userError and isUserError.
Answer: userError is basically a smart constructor for a value of type IOError (which itself is an alias for IOException), which uses a single data constructor also named IOError. Two of the fields are ice_type :: IOErrorType and ioe_description :: String; the rest of the fields aren't relevant to UserError, so userError is really just a wrapper around the data constructor IOError:
userError       :: String  -> IOError
userError str   =  IOError Nothing UserError "" str Nothing Nothing

When you want to raise your own IOError, you use userError to create it; the resulting IOError value is what gets passed to the handler.
isUserError e simply tests if ioe_type e is UserError.


Has Many relations in between both models

Question: I have the database something like this
  == Invoices ==
  id
  customer_id

  == Customers ==
  id
  firstname
  lastname
  membersince

So I made relations in between both models like below.
Relation definition in the Invoices Model:
'customers'=>array(self::HAS_MANY,'Invoices','customer_id'),

Relation definition in the Customers Model
'invoices' => array(self::BELONGS_TO, 'Invoices', 'invoice_id'),

Now I want to know the relation in between both models are correct? Any suggestions are welcome.
Answer: No, the relation between the models is not correct.
I assume what you want here is that customers can have many invoices, but an invoice can only be owned by a single customer, as this is what your database schema implies.
Please note that in the code below I distinguish between singular and plural forms of customer and invoice to make the code logical and easy to understand.
In that case the relation definition in the Invoice model would be like this:
class Invoice extends CActiveRecord {
    public function relations() {
        return array(
            'customer' => array(self::BELONGS_TO, 'Customer', 'customer_id')
        );
    }
}

The invoice 'belongs to' a customer. 'Customer' indicates that the type of model we refer to is a Customer, and 'customer_id' is the name of the column in the invoices table that refers to the primary key of the customer.
The Customer model looks a bit trickier:
class Customer extends CActiveRecord {
    public function relations() {
        return array(
            'invoices' => array(self::HAS_MANY, 'Invoice',
                               'customer_id', 'index' => 'id')
        );
    }
}

Here the relation definition indicates that a Customer can refer to many Invoice models. Notice how the rest of the relation is defined. customer_id is again the column that refers to a Customer, and 'index' => 'id' tells Yii to use the column id in the customers table as key for the relationship.
You can find more information about the relations method in the Yii documentation.


Avoid Circular References in Symfony2's Dependency Injection?

Question: I am a big fan of dependency injection, but something bothers me and I was wondering whether someone could give me an explanation:
It is not possible to create two services that depends on each other, because we will get a "Circular Reference" exception. I think everyone using symfony2 has met this error.
While I understand very well this error, I meet it sometimes because with a lot of services, comes complexity... and, maybe also because designing/sizing services is not easy.
Therefore, I was wondering about the root cause of this error:

It is to protect us regarding a potential serious design error? If this is the case, could you give me an example of what serious can happen if two dependent services could "live together"?
It is purely technical? I.e. because it is not possible to call both constructors. If this is the root reason, why not solve it by forcing service constructors to be empty and have an init method?

I.e.:
<code>class MyService1{

   private $service2;

   public function __construct(){ //empty constructor
      ...
   }

   protected function init(MyService2 $service2, ...){
      $this->service2 = $service2;
   }

}

class MyService2{

   private $service1;

   public function __construct(){ //empty constructor
      ...
   }

   protected function init(MyService1 $service1, ...){
      $this->service1 = $service1;
   }

}
</code>
And then instantiate both services:
<code>$service1 = new MyService1();
$service2 = new MyService2();
$service1->init($service2);
$service2->init($service1);
</code>
I'm pretty sure there is something I don't have understood in depth. So could someone explain me why we are prevented to create circular references in the container?
Thank you
Comment: Because your service1->init method would receive a service that is not fully initialized.  Bad things will happen when you try to use a partially initialized service.
Comment: I'm sorry, I am not convinced by this argument. Because in the init method, you would be in the same state than in the constructor... Symfony2 developers could create an abstract Service class that forces to implement that method... I don't think this is particularly dangerous.
Comment: So what happens if a depends on b which depends on c which in turn depends on both a and b?  I suspect that after you work with di a bit more you might have a change of opinion. If not then submit a patch.  The Symfony group encourages outside help.
Comment: I don't think this is very difficult to implement the general case. But I think there is another reason this has not been done. And that's probably more a "Best practice" reason than a technical one. And that's why I am asking here... to have a better understanding...
Answer: Ideally your services would adhere to the dependency inversion principle.
That is, high-level components would depend on low-level components but not the other way round. Additionally for higher cohesion, this dependency would be via an abstraction or interface.
See this question from the Programmers SE site.
Comment: I think I have understood this. But I think that even if the Component A' constructor's prototype is __construct(ComponentBInterface $componentB), the Symfony2 service config will inject ComponentB implementation. There's no problem in your diagram because it is simple. Let me give a concrete example: I have a BasketHelper who contains methods related to orders and a CertificateHelper (which handles the certificate product). There are some methods which are a bit in between (i.e. related both to the orders and certificates)... Then, I guess I should create a Third service that depends on both?


How does interchange of counter variable in this double summations work?

Question: I'm reading a book on linear algebra. $F$ is a field and $S$ is the set of nonnegative integers. It say the the set of all functions from $S$ into $F$ is a vector space over $F$. We denot it $F^{\infty}$ and also define a product in $F^\infty$ by associating with each pair of vectors $f$ and $g$ in $F^\infty$ the vector $fg$ which is given by
$$(fg)_n = \sum\limits_{i=0}^n f_ig_{n-i}, \hspace{10 mm} n=0,1,2,...$$
When the book want to prove associativity of the product it goes like this:
$$[(fg)h] = \sum\limits_{i=0}^n (fg)_ih_{n-i} = \sum\limits_{i=0}^n \left( \sum\limits_{j=0}^if_jg_{i-j}\right)h_{n-i}=\sum\limits_{i=0}^n\sum\limits_{j=0}^if_ig_{i-j}h_{n-i}=\sum\limits_{j=0}^nf_j\sum\limits_{i=0}^{n-j}g_ih_{n-i-j}=\sum\limits_{j=0}^nf_j(gh)_{n-j}=[f(gh)]_n$$
1.I think in the third sum it shoud be $f_j$ instead of $f_i$. Tell me if I am wring.
2.I don't understand the fourth equality when the order of the double sum is reversed. How can we prove $\sum\limits_{i=0}^n\sum\limits_{j=0}^if_ig_{i-j}h_{n-i}=\sum\limits_{j=0}^nf_j\sum\limits_{i=0}^{n-j}g_ih_{n-i-j}$
Answer: I think you're right that there is a typo. In the second sum (the first double sum), we have $f_jg_{i-j}$, and in the next expression, the $j$ subscript on $f$ inexplicably changes into an $i$. In the next expression, it changes back to a $j$. It should have been $j$ all along.
Once that is corrected, we can address your second question. It is valid to pull the $f_j$ out of the inner summation, because it has no dependence on $i$. As for the other terms, something a bit more subtle happens.
Consider the double summation $\sum\limits_{i=0}^n\sum\limits_{j=0}^i$. If you imagine an $ij$-plane, the terms in this sum occupy a triangle whose edges are: the $i$-axis from $0$ to $n$, the vertical line from $(0,n)$ to $(n,n)$, and the diagonal line $i=j$ from $(0,0)$ to $(n,n)$. If you want to switch the order of the sum and run through the points in that same triangle, you're going to write
$$\sum\limits_{i=0}^n\sum\limits_{j=0}^i X = \sum\limits_{j=0}^n\sum\limits_{i=j}^n X$$
where $X$ represents whatever expression we have in the summation.
Once that's clear, we can address how the inner sum is re-indexed. We have to see why:
$$\sum\limits_{i=j}^n g_{i-j}h_{n-i} = \sum\limits_{i=0}^{n-j} g_{i}h_{n-i-j}$$
This is the usual re-indexing trick where we want to start at zero instead of somewhere else, so we shift our index. Basically, replace every instance of $i$ on the left-hand side with the expression $i+j$. When doing this, consider that the upper limit ($n$) is really shorthand for $i=n$. After simplifying, you should end up with the right-hand side.
Does this help?
Comment: Why $\sum\limits_{i=0}^n\sum\limits_{j=0}^i X = \sum\limits_{j=0}^n\sum\limits_{i=j}^nX$ is true?
Comment: Have you looked at the triangle I described? Without that picture, it's hard to see.
Comment: You could try to see it this way: The first sum consists of pairs $(i,j)$ where both variables are between $0$ and $n$, and where we always have $j\leq i$. That second inequality is the same as $i\geq j$, so if $j$ is fixed, then $i$ has to start out equal to $j$ and increase from there.
Comment: Taking an idea from the other answer posted here, both $\sum\limits_{i=0}^n\sum\limits_{j=0}^i$ and $\sum\limits_{j=0}^n\sum\limits_{i=j}^n$ are ways of saying we need to sum over all pairs $\{(i,j):0\leq j\leq i\leq n\}$
Answer: Here is a derivation which also could be helpful.

We obtain
  \begin{align*}
\color{blue}{[(fg)h]}&=\sum_{i=0}^n(fg)_ih_{n-i}\\
&=\sum_{i=0}^n\left(\sum_{j=0}^i f_jg_{i-j}\right)h_{n-i}
=\sum_{\color{blue}{0\leq j\leq i\leq n}}f_jg_{i-j}h_{n-i}\tag{1}\\
&=\sum_{j=0}^n\sum_{i=j}^nf_jg_{i-j}h_{n-i}\\
&=\sum_{j=0}^nf_j\sum_{i=0}^{n-j}g_ih_{n-i-j}\tag{2}\\
&=\sum_{j=0}^nf_{n-j}\left(\sum_{i=0}^jg_ih_{j-i}\right)\tag{3}\\
&=\sum_{j=0}^nf_{n-j}(gh)_j\left(=\sum_{j=0}^nf_j(gh)_{n-j}\right)\\
&\color{blue}{=[f(gh)]}
\end{align*}
Comment:

In (1) the representation with indices $0\leq j\leq i\leq n$ helps to identify upper and lower limit of $i$ and $j$.
In (2) we factor out $f_j$. We shift the index $i$ to start from $i=0$ and substitute $i\rightarrow i+j$ in the summation terms accordingly.
In (3) we change the order of summation of the outer sum by $j\rightarrow n-j$.

Note: You are right with 1.) and 2.) is shown above.
Comment: thanks but I think line (3) is not useful because we need $f_j$.
Comment: @OmidSadeghi: You're welcome and you're right. You don't need (3) for your calculation. I just wanted to provide a variation with focus to symmetry. I've added an equivalent expression in parentheses to better see the connection.


Symmetry for finite cyclic groups (Z/pZ)∗

Question: How well is it known that for $i$ such that $1 \leq i \leq \frac{p − 1}2$:
$$
g^{i+(p−1)/2} = g^{i−1+(p−1)/2} − g^i + g^{i−1} \pmod p
$$
Whilst working in the finite cyclic group of prime moduli $(Z/pZ)^*$, given g to be a primitive root of p.
Comment: Let $p=7$, $g=2$, and $i=1$. The LHS is $2^{1+3}\equiv2$ and the RHS is $2^{0+3}-2^1+2^0\equiv1-2+1\equiv-2$. Your equation does not hold.
Comment: i forgot to add for g to be a primitive root of p. sorry. so 2 is not a primitive root of 7
Comment: Isn't it a direct consequence of $g^{(p−1)/2}\equiv−1\bmod p$ ?
Comment: @lhf possibly. But I still found it kind of intriguing that the "second part" of a finite cyclic group is the "mirror: of the "first part" under certain circumstances . I wonder if this property is used anywhere
Answer: If $g$ is a primitive root of $p$, then
$
g^{(p−1)/2}\equiv-1\bmod p
$. Hence
$$
g^{i+(p−1)/2} \equiv g^i g^{(p−1)/2} \equiv -g^i\bmod p
$$
and
$$
g^{i−1+(p−1)/2} − g^i + g^{i−1} \equiv g^{i−1} g^{(p−1)/2} − g^i + g^{i−1} \equiv -g^{i−1} − g^i + g^{i−1} \equiv -g^i \bmod p
$$
Comment: do you know any application of this formula?


How to change color of text in a button

Question: How do you change the color of a text inside a button node?
I tried this:
btn.setStyle("-fx-text-fill: white");

But it only added color to the button.
Comment: can you try `btn.setTextFill(Color.WHITE);`
Comment: Can you try this please `btn.setTextFill(Color.web("#ff0000"));`
Comment: @YCF_L How do I use setTextFill when I want a specific hex code for the color?
Comment: There are many questions and answers on stackoverflow.com
Before, asking a question you need to do some research to check if you question is already there.
Please, read the guidelines before I participating.
Comment: @MohammedFadhl if it is a duplicate, then vote to close it as a duplicate.
Comment: Does this answer your question? [How to change text color of a JButton](https://stackoverflow.com/questions/15393385/how-to-change-text-color-of-a-jbutton)
Comment: @MohammedFadhl that answer is for java swing, not javafx
Answer: In JavaFX there are various ways to set the color of a button's text:
From hex:
private static Button createButton() {
    final Button button = new Button("red");
    button.setTextFill(Color.web("#ff0000"));
    return button;
}

With predefined colors:
private static Button createButton() {
    final Button button = new Button("red");
    button.setTextFill(Color.RED);
    return button;
}

From RGB values:
private static Button createButton() {
    final Button button = new Button("red");
    button.setTextFill(Color.rgb(255, 0, 0));
    return button;
}

From HSB values:
private static Button createButton() {
    final Button button = new Button("red");
    button.setTextFill(Color.hsb(0, 1, 1));
    return button;
}

From color where RGB is within a range of 0.0-1.0
private static Button createButton() {
    final Button button = new Button("red");
    button.setTextFill(Color.color(1, 0, 0));
    return button;
}

Pick whichever suits your needs

How to change color of text in a button


MariaDB conditional insert with placeholders doesn't work with PDO

Question: I have the following tables for my blog:
Table tags which has columns tag_id (A.I.) and tag
Tablepost_tags which has columns post_id and tag_id. It describes which tags belong to which posts.
I am trying to make some SQL query that binds a given tag to a given post_id in post_tags, but if tag doesn't exist in tags it creates it there first.
$query =
SQL
DELIMITER //

BEGIN NOT ATOMIC
    IF NOT EXISTS (SELECT `tags`.`tag` FROM `tags` WHERE `tag`  = :tagname) THEN
       INSERT INTO `tags` (`tag_id`, `tag`) VALUES (NULL, :tagname);
    END IF;
END //

DELIMITER ;

INSERT INTO post_tags (post_id, tag_id)  SELECT :postid, tags.tag_id FROM tags WHERE tags.tag = :tagname;

I then have the following PHP code to execute this procedure:
// all $db variables are given, known and correct.
$pdoconn = new PDO("mysql:host=$dbhost;dbname=$db", $dbuser, $dbpass);
$pdoconn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$taginsert = $pdoconn -> prepare($query);

$id = 0; // The post_id. This is given, known and correct.
$tags = array(); // Array of strings (the tags)
foreach ($tags as $tag){
    try{
        $taginsert -> bindValue(":tagname", $tag, PDO::PARAM_STR);
        $taginsert -> bindValue(":postid", $id, PDO::PARAM_INT);
        $taginsert -> execute();
    } catch(PDOException $e){
        $message = $e->getMessage();
        var_dump($message);
    }
}

$taginsert -> close();

This should be straightforward enough. And indeed, when replacing the placeholders for actual values and executing the raw query from within phpMyAdmin, it works! But when I execute the pdo php code, it just dumps this error:

string(284) "SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'DELIMITER // BEGIN NOT ATOMIC IF NOT EXISTS (SELECT tags.tag FROM tags' at line 1"

  Needless to say this cryptic error message is of no use to me.

I am using php 7.3 with 10.1.30-MariaDB-1~xenial
Comment: Try removing the delimiter, since it's only needed for the command line. Also, PDO can only handle 1 query statement at a time, so you'll have to break it up into two separate queries.
Comment: See https://stackoverflow.com/a/5314879/1007220
Comment: I'm not 100% sure about MariaDB, but I don't believe MySQL supports procedural syntax (like DELIMITER, BEGIN, that form of IF, etc....) outside of stored procedure and function definitions. In the past when necessity has required it, and the connection permitted, I have been able to make "temporary" stored procedures to do what I need, and then drop them after. _(3 querys: create proc, exec proc, drop proc)_
Comment: @aynber that resolved the error, but also gave a new one: (11 is indeed the post it got stuck on)

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT `post_tags` (`post_id`, `tag_id`) SELECT 11, `tags`.`tag_id` FROM `tags`' at line 7.

So yeah, I'll break it up.
Comment: I think the entire task can be done with a single statement.  See IODKU and LAST_INSERT_ID().
Answer: I achieved the desired result with the following php code:
Keep in mind that my error/bounds checking is minimal here because I knew the dataset I was working with.
$pdo = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$postid;
$tags = [];
$tagidStmt      = $pdo->prepare("SELECT tag_id FROM tags WHERE tag = :tagname;"); // $tag
$linkExistsStmt = $pdo->prepare("SELECT * FROM post_tags WHERE post_id = :postid AND tag_id = :tagid;"); // $postid, $tagid
$insertionStmt  = $pdo->prepare("INSERT INTO post_tags (post_id, tag_id) VALUES (:postid, :tagid);"); // $postid, $tagid

foreach ($tags as $tag){
    $tagidStmt -> execute(['tagname' => $tag]);
    $tagid = ($tagidStmt -> fetch())["tag_id"];
    $tagid = intval($tagid);

    $linkExistsStmt -> execute(['postid' => $postid, 'tagid' => $tagid]);
    $linkExists = $linkExistsStmt -> fetch();

    if ($linkExists === false){
        $insertion = $insertionStmt -> execute(['postid' => $postid, 'tagid' => $tagid]);
    }
}


Problema com consulta MySQL e PHP

Question: Estou com o seguinte problema, quando utilizo a clausula WHERE não estou conseguindo utilizar os valores que estão sendo passados por parametro.
Como retorno tenho a seguinte mensagem:

PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in*

TIPOS DE DADOS NO BANCO

date  tipo -> DATETIME
municipio tipo -> INT
entidade tipo -> INT

    public function listLicitacoesEntidadesCidades($date, $municipio, $entidade){

        $stmt = $this->pdo->prepare("
        select
        tab_licitacoes.id,
        tab_licitacoes.cidade_id,
        tab_licitacoes.entidade_id,
        tab_licitacoes.data_abertura,
        tab_licitacoes.data_cancelamento,
        tab_licitacoes.status,
        tab_licitacoes.modalidade,
        tab_cidades.nome,
        tab_entidades.nome_entidade
            from tab_licitacoes
            join
            tab_cidades on (tab_licitacoes.cidade_id = tab_cidades.id)
            join
            tab_entidades on (tab_licitacoes.entidade_id = tab_entidades.id)
                where
                tab_licitacoes.status = 'A'
                and
                tab_licitacoes.data_cancelamento >= :date
                and
                tab_licitacoes.cidade_id = :municipio
                and
                tab_licitacoes.entidade_id = :entidade

                ");
        $stmt->bindValue(':date', $date, PDO::PARAM_STR);
        $stmt->bindValue(':municipio', $municipio, PDO::PARAM_INT);
        $stmt->bindValue(':entidade', $entidade, PDO::PARAM_INT);
        $stmt->execute();

        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $data;

    }
Comment: Se você executar esse select direto no banco causa algum erro?
Comment: Passando valores fixos nas 3 variaveis, exemplo :municipio passar 34 retorna exatamente o que preciso
Answer: Baseado no que você informou nos comentários, já tentou fazer diferente?
Dessa forma:
 public function listLicitacoesEntidadesCidades($date, $municipio, $entidade){

    $stmt = $this->pdo->prepare("
    select
    tab_licitacoes.id,
    tab_licitacoes.cidade_id,
    tab_licitacoes.entidade_id,
    tab_licitacoes.data_abertura,
    tab_licitacoes.data_cancelamento,
    tab_licitacoes.status,
    tab_licitacoes.modalidade,
    tab_cidades.nome,
    tab_entidades.nome_entidade
        from tab_licitacoes
        join
        tab_cidades on (tab_licitacoes.cidade_id = tab_cidades.id)
        join
        tab_entidades on (tab_licitacoes.entidade_id = tab_entidades.id)
            where
            tab_licitacoes.status = 'A'
            and
            tab_licitacoes.data_cancelamento >= ?
            and
            tab_licitacoes.cidade_id = ?
            and
            tab_licitacoes.entidade_id = ?

            ");

    $stmt->execute(array(date("Y-m-d H:i:s", strtotime($date)), $municipio, $entidade));

    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    return $data;

}

EDITADO

Na assinatura do seu método
public function listLicitacoesEntidadesCidades($date, $municipio, $entidade)

seu parâmetro $date é do tipo DATETIME?
Quando você vai atribuir a valor ao parâmetro da query
$stmt->bindValue(':date', $date, PDO::PARAM_STR);

você define o parâmetro como string em PDO::PARAM_STR, então você deve converter $date para string.
$stmt->bindValue(':date', date("Y-m-d H:i:s", strtotime($date)), PDO::PARAM_STR);

Seria isso?
Comment: Eu já havia tentado desta forma, desculpas por não postar. Mas com os outros parâmetros também ocorrem o mesmo problema, é como se não estivesse entendendo os tipos de dados mesmo, tentei forcar a tipagem de dados a todos os parâmetros mesmo assim não funcionou, Mas obrigado pela dica.
Comment: Este erro indica que você está com um número de parâmetros na query diferente daquele que você está preenchendo com suas linhas `bindValue`. Pelo menos no código que você postou isso não está acontecendo. No seu código real, que está executando, não está sobrando ou faltando nada? Está diferente do que você postou aqui?
Comment: Verifica a solução alternativa que postei...
Comment: Já havia tentado, mostra apenas um array vazio, desta forma. contudo há conteúdo na tabela

Problema com consulta MySQL e PHP


Can I bound the following function by an integer?

Question: I am wondering if the following function
$$\frac{x+y}{x^2+y^2}$$
can be bounded in some smart way by an integer.
Comment: Are $x$ and $y$ are integers, too?
Comment: That's not a function. What's the domain supposed to be?
Answer: Note that the function
$$f(x,y)=\frac{x+y}{x^2+y^2}$$
satisfies
$$f(1/n,1/n)=\frac{2/n}{2/n^2}=n, \forall n\in \mathbb{N}.$$ So, the function is not bounded from above.
Also, $$f(-1/n,-1/n)=\frac{-2/n}{2/n^2}=-n, \forall n\in \mathbb{N}.$$ Thus, the function is not bounded from below.
Answer: Your function can take every value if the variables are real numbers.
Each value $m\ne 0$ can be reached for example with $x=0$ and $y=\frac{1}{m}$.
If you have a function of integers than your function is always between $-1$ and $1$ since $|x+y|<x^2+y^2$.


MySQL procedure with sys_exec()

Question: I'm attempting to fire a Laravel console PHP command to push every inserted row to my client UI, but the procedure doesn't seem to work after installing lib_mysqludf_sys libraries for sys_exec()/sys_eval() support.
Environment is the Laravel Homestead Vagrant VM.  This is running Ubuntu 14.04.3 and MySQL 5.6.19-0ubuntu0.14.04.1.  I also compiled and successfully installed the lib_mysqludf_sys libraries.

When using sys_exec(), I get returned exit code 32512 when running the procedure.
When using sys_eval(), I get no output in my debug_msg output when running the procedure.
Using the cmd echoed in debug_msg, it runs without issue manually on the CLI.
No MySQL error.log output

Does anyone know how to further troubleshoot this issue?
DELIMITER $$

DROP PROCEDURE IF EXISTS homestead.debug_msg$$
DROP PROCEDURE IF EXISTS homestead.sessionActivity$$

CREATE PROCEDURE homestead.debug_msg(enabled INTEGER, msg VARCHAR(255))
BEGIN
  IF enabled THEN BEGIN
    select concat("** ", msg) AS '** DEBUG:';
  END; END IF;
END $$

CREATE PROCEDURE homestead.sessionActivity(id BIGINT)
BEGIN
  IF id THEN BEGIN
   DECLARE cmd CHAR(255);
   DECLARE result CHAR(255);
   SET cmd = CONCAT('/usr/bin/php /home/vagrant/Code/Laravel/artisan session:push ', id);
   SET result = sys_eval(cmd);
   #####SET result = sys_exec(cmd);
   call debug_msg(TRUE,cmd);
   #####call debug_msg(TRUE,result);
  END; END IF;
END$$

DELIMITER ;

Here is running with debug_msg displaying the cmd variable:
mysql> CALL homestead.sessionActivity(74499);
+--------------------------------------------------------------+
| ** DEBUG:                                                    |
+--------------------------------------------------------------+
| ** php /home/vagrant/Code/Laravel/artisan session:push 74499 |
+--------------------------------------------------------------+
1 row in set (0.00 sec)

Which runs fine manually:
root@homestead:~# php /home/vagrant/Code/Laravel/artisan session:push 74499
string(259) "new line: some shit eol"
root@homestead:~#

Here is running with debug_message displaying the result variable, using sys_exec(), but again, the PHP command is not ran, and no other output or logging shows errors (and sys_eval() instead of sys_exec() output here would be empty):
mysql> CALL homestead.sessionActivity(74499);
+-----------+
| ** DEBUG: |
+-----------+
| ** 32512  |
+-----------+
1 row in set (0.01 sec)

Curiously, while the lib_mysqludf_sys install creates functions, they don't show in show function status.  I'm not sure if it's related.
mysql> CREATE FUNCTION lib_mysqludf_sys_info RETURNS string SONAME 'lib_mysqludf_sys.so';
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE FUNCTION sys_get RETURNS string SONAME 'lib_mysqludf_sys.so';
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE FUNCTION sys_set RETURNS int SONAME 'lib_mysqludf_sys.so';
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE FUNCTION sys_exec RETURNS int SONAME 'lib_mysqludf_sys.so';
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE FUNCTION sys_eval RETURNS string SONAME 'lib_mysqludf_sys.so';
Query OK, 0 rows affected (0.00 sec)

mysql> show function status;
Empty set (0.01 sec)

mysql>

Answer: The lib_mysqludf_sys calls were being blocked by Apparmor in this case.  A quick aa-complain /usr/sbin/mysqld fixes this issue.

MySQL procedure with sys_exec()


Executa função x minutos após submeter formulário

Question: Boa tarde galera do bem, apareceu um problema para resolver em um site, algo que ainda não havia mexido.
É o seguinte, na página tenho um formulário onde a pessoa pode se cadastrar. Ao realizar o cadastro, eu envio um email para ela confirmando esse cadastro.
Agora, vamos começar a utilizar SMS também, ou seja, a pessoa se cadastra, recebe um e-mail e um SMS confirmando (regras da empresa). Mas meu gestor quer que o SMS chegue depois de uns 5 min que a pessoa realizou o cadastro no site.
No momento, estou enviando o SMS de imediato, mas ele quer que seja feito da maneira como ele falou.
Alguém pode me ajudar ?
Obs.: Eu submeto o formulário na mesma página que faço o insert.
function sendSms(){

            $nome = explode(" ",$_POST['txtNome']); // pega o nome via post , e joga cada palavra em um array

            $corrigir = array(' ','-','(',')','{','}','/','  ');// array que elimina caractres do telefone ,deixando somente os numeros

            $corpoSMS = 'SKY HDTV:Caro(a).'$nome[0].',informamos que seus dados foram enviados para nosso dpt de cadastros.Dentro de 24h,entraremos em contato com maiores informacoes'; //monta o corpo do sms , mantendo o limite de 160 caracteres.

            $tel = str_replace($corrir,'',$_POST['txtCel']);

            $msg = str_replace(' ','+',$corpoSMS);

            //código da página enviapost.php
                $dados_post = array(
                        "" => $tel,
                        "?message=" => $msg,
                        );

                $context = stream_context_create(array(
                    'http' => array(
                    'method' => 'GET',
                    'header' => array(
                    'Content-Type: application/x-www-form-urlencoded'),
                    'content' => http_build_query($dados_post)
                    )
                )
            );

        $host = 'https://meuservidordesms.com.br/'.$tel.'?message='.$msg;
            $result = file_get_contents($host,false,$context);

            if(preg_match("/SUCESSO/", $result)){
                    echo '  ';
                        } else {
                            echo '';
                    }

        }// FUNCAO QUE ENVIA O SMS AO CLIENTE.

Comment: Você já testou o impacto que teria deixar esses envios de SMS empilhados? Não gera gargalo no sistema? Teria algum problema se você salvasse isso em arquivo ou banco e depois rodasse uma tarefa a cada x tempos que lê-se esses dados e enviasse o mesmo. Exemplo de uma tarefa agendada? A grosso modo como se usasse um observer?
Comment: Boa noite, voce teria algum exemplo ou link mostrando como poderia fazer ? Grato
Comment: Uma thread que consulta no banco de dados a cada 5 segundos quais são os próximos SMS para enviar, nunca utilizei Thread no PHP, porém em outras linguagens como Delphi e Java. Segue uma documentação: http://php.net/manual/pt_BR/class.thread.php.
Comment: Talvez isso te ajude http://www.phpclasses.org/package/9047-PHP-Execute-asynchronous-tasks-in-the-background.html
Comment: Você pode utilizar um serviço de filas como: Amazon SQS, Beanstalkd, IronMQ, ...
Answer: Como o Israel falou, talvez seja melhor você ter um serviço rodando no servidor, verificando os registros novos no banco de dados e mandando o SMS na hora programada.
De qualquer maneira, fiquei interessado na sua pergunta e pesquisei um pouco.
Parece que é possível contatar um "script filho" a partir do script que é acessado pelo cliente, usando socket. Esse script responde rapidamente ao "script pai" que em seguida desconecta - a partir daí, o "script filho" continua seu trabalho, em background.
Aqui vai o "script pai":
<?php

echo "Teste de Socket para Script Filho";

// Data para diferenciar o momento do acesso ao da criação do arquivo .txt
date_default_timezone_set('America/Sao_Paulo');
$current_date = date('d/m/Y == H:i:s');

// Criando a conexao socket
$socketParaFilho = fsockopen("www.example.com", 80);

// Criando pacote HTTP
$paraScriptFilho = "POST /script.php?&param=value HTTP/1.0\n";
$paraScriptFilho .= "Host: www.example.com\n";

// A mensagem que sera enviada ao script filho
$dados = "Script Pai: pagina acessada em " . $current_date;
$paraScriptFilho .= "Content-Length: ".strlen($dados)."\n\n";

// Incluindo mensagem com a data em que a pagina foi visitada
$paraScriptFilho .= $dados;

// enviando pacote
fwrite($socketParaFilho, $paraScriptFilho);

// Esperando resposta do script "filho"
$resposta = fread($socketParaFilho, $dataSize);

// Fechando conexao
fclose($socketParaFilho);

?>

Agora o "script filho", note que ele deve se chamar apenas "script.php":
<?php

date_default_timezone_set('America/Sao_Paulo');
$post = file_get_contents('php://input');

// Aqui que acontece a "mágica"
ob_start();
ignore_user_abort(1);
set_time_limit(0);

$resposta = "OK";
echo $resposta;

ob_flush();

// A partir deste ponto, o "script pai" desconecta, e o script filho
// se mantêm em execução

sleep(60);
$arquivo = 'teste.txt';
$data = date('d/m/Y == H:i:s');
$texto = $post . "\r\nScript Filho: texto salvo em " . $data;
file_put_contents($arquivo, $texto);

?>

Depois de acessado o "script pai", é possível até fechar a janela do navegador.
60 segundos depois, um documento .txt será criado no servidor, mostrando a data que a página foi acessada e a data que o "script filho" salvou o documento.
Aqui está o resultado do meu teste:
Script Pai: pagina acessada em 20/07/2015 == 05:00:03
Script Filho: texto salvo em 20/07/2015 == 05:01:03

Eu achei esse exemplo aqui.
PS. Eu não entendo de PHP. Vi esse exemplo e achei que poderia ajudar com a sua questão.
Comment: Bom dia @Daniel , cara , tinha me esquecido dos sockets . Vou tentar aplicar ao meu caso , pois eu só estou fazendo a pagina de controle de cadastros ,o site foi uma agencia quem desenvolveu. Mas acredito que os sockets , vão suprir minhas necessidades. Obrigado


Solving a Recurrence Relationship

Question: Given recurrence relationship:
$g(1) = 5;\\
g(2n) = 4g(n);\\
g(2n+1) = 4g(n).$
I feel lost because of $g(2n)$ and $g(2n+1)$.
Based on my coursebook, there is the common standard form, which can be used in order to find the relation:
$g(n) = A(n)\alpha + B(n)\beta + C(n)\gamma$
$A(n),B(n)$ and $C(n)$ are functions, $\alpha, \beta, \gamma$ are constants.
I suppose this form is for the case when there is 3 constants? Thus in this case the form should be
$g(n) = A(n)\alpha$?
How does one use this knowledge in order to solve the relationship?
=====
$f(1)=α;\\
f(2n)=2f(n)+1;\\
f(2n+1)=2f(n)+β.$
This is the case when I do not have a number, but a constant - how does one solve the relationship?
Comment: You can find $g(2)$ immediately from the first and second relations. Then you can find $g(3)$, $g(4)$ and so on. What's the problem?
Comment: @YuriyS, could you clarify a bit? so I can say that $n=1$, $g(1)=5$, $g(2*1)=4*5$, is that correct? Also, when one can state that the relationship is solved?
Comment: Yes to your first question. And you can find $g(3)$ using the third relation. Then $g(4)$ and $g(5)$ using the known value of $g(2)$ and second and third relations respectively. Then you find $g(6)$ and $g(7)$ using $g(3)$ and so on. In general, the relationship is solved when you introduce a function $g(n)$ which immediately gives you any $g(n)$ without knowing $g(n-1)$, $g(n-2)$ and so on. In other words, $g(n)$ should explicitly depend on $n$
Comment: You should list first 31 terms. Then you can see the pattern. Note that the 16th term to the 31th term are the same.
Comment: @YuriyS, thank you for clarification. How would one solve this case:
$f(1)=\alpha;\\
f(2n)=2f(n)+1;\\
f(2n+1)=2f(n)+\beta\\$

In this case one does not have a number, but just the constant. How would you understand the pattern?
Answer: Here is a  contribution that is not a compact form  but may perhaps be
of some use. Supposing the recurrence
$$f(1) = \alpha,
\\ f(2n) = 2f(n) + \beta,
\\ f(2n+1) = 2f(n) + \gamma.$$
Introduce the base two representation of $n$ which is
$$n=\sum_{k=0}^{\lfloor\log_2 n\rfloor} d_k 2^k.$$
We then obtain the closed form (exact) by inspection which is
$$f(n) = \alpha \times 2^{\lfloor\log_2 n\rfloor}
+ \sum_{k=0}^{\lfloor\log_2 n\rfloor-1}
([[d_k = 0]]\times \beta + [[d_k = 1]]\times \gamma)
 \times 2^{k}.$$
We can deduce some special values from this e.g.
$$f(2^m) = \alpha \times 2^m
+ \beta \sum_{k=0}^{m-1} 2^k
= \alpha \times 2^m
+ \beta \times (2^m-1).$$
Similarly
$$f(2^m-1) = \alpha \times 2^{m-1}
+ \gamma \sum_{k=0}^{m-2} 2^k
= \alpha \times 2^{m-1}
+ \gamma \times (2^{m-1}-1).$$

Solving a Recurrence Relationship


Installing installed app on a device with instant app

Question: Please bear with me as I try to explain this weird issue I'm facing when installing the "installed app" over the "instant app".
Steps to produce the problem:

Install the instant app on the device running Android O.
Install the "installed app".

Problem:

The installed app does not show in the app drawer and if I go into device settings --> apps, I see the app as an instant app (with the lightning icon) but with the size of the installed app. So installed app is actually installed but behaves still like an instant app.
The instant app has only 1 activity and that is the 2nd activity of the installed app. So when I go into the installed app on first launch, I can't go past the 2nd activity as that activity behaves like an instant app i.e. InstantApps.isInstantApp(activityContext) returns true. So trying to go further in the app opens the play store page for the app.

If I install the installed app on a device without the instant app, it works fine.
The default url is defined for the 1 activity in the base feature and 2 activities in the installed app - launcher (home) and the 2nd activity (part of instant app).
What could be the issue here?
Update
I updated the installed app. Now I built the release version of the instant app for testing, and it opens the play store if I click on a feature which is only in the installed app, all good. But after I install the app, I face the same issue, it behaves like an instant app - no icon in the app drawer, lightning icon on the app icon in settings-->apps. How is this happening?
Comment: Do you run into this issue only with O preview build , or do you also see the same behavior on pre-O devices as well?  (current O preview is opp4.170623.014, developer.android.com/preview/download.html)
Comment: Only tried with O as my other devices don't support instant app yet, all countries aren't supported. Tried with opp3.170518.006.
Comment: Try to reproduce this issue with the current O preview build (opp4.170623.014), it is best to stay up-to-date with O preview builds https://developer.android.com/preview/release-notes.html.

If you still can see the same behavior with the latest O preview version, this might be a possible issue in this build. Can you file a bug, then link to it back in here? It would be helpful for all, thanks! https://issuetracker.google.com/issues/new?component=316045&template=1018787
Comment: As a temporary workaround that worked for me, you can manually remove your instant-app (Settings > Apps > Select your instant app > Tap "Clear App"), and then install your installable app from PlayStore.
Comment: I will try with the latest O build. But the point is users won't clear the instant app before installing the installed app, that's why we haven't been able to update our instant app with the changes required for O.
Comment: I tried with the latest O preview build (opp4.170623.014) and the issue still remains. Posted the issue here --> https://issuetracker.google.com/issues/64467803.
Answer: If your device/emulator already has the instant-app installed, you will run into problems like this if you install your installed-app from Android Studio. I'm not sure which Android Studio 3.0 Canary version you are on, but at the moment, there is something strange/broken with it (we'll have to wait for an update).
Unfortunately, for now, you may need to manually install your installed-app with this adb cmd:
adb install -r -t --full <installed-app.apk>

This should properly override the instant-app with the installed-app.
Also see https://issuetracker.google.com/issues/63932235
Comment: Wow, thanks! Thankfully I didn't waste too much time on this. I'm using Canary 6.
Answer: The problem is that you are using the Instant Apps feature which is only meant for experiencing (getting an idea) of the app .If you want to test the application, install it without Instant Apps. Check the link for more information - https://developer.android.com/topic/instant-apps/index.html
Comment: What do you mean? This is not clear at all. And I have read the official documentation on Instant apps.


Android Hide keyboard when changing fragments

Question: When I change fragments. I am using this to close the keyboard because there is an EditText field on the screen. I just feel like there has to be a better way, but I havent found anything on detecting if the keyboard is on the screen.
Activity activity = getActivity();
InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
try
{
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
catch (Exception e)
{

}

Comment: It's difficult to detect the keyboard, the API really only allows you to trigger the keyboard.
Answer: In the activity where you implement the calling to various fragments, put the following...
    InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);

Answer: You can use following code in pause method:
@Override
protected void onPause() {
    super.onPause();

    final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null && inputMethodManager.isActive()) {
        if (getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
}

Answer: The only real way I can think of is using the onConfigurationChanged(Configuration config) method:
Combination of KeyboardHidden and Configuration should do it.
class MyFrag extends Fragment{

  @Override
  public void onConfigurationChanged(Configuration config){
    //Check flags
    switch(config.keyboardHidden){
      case KEYBOARDHIDDEN_NO:
        // do something
        break;
      case KEYBOARDHIDDEN_YES:
        break;
    }
  }

}

This of course relies on you having the manifest and parent activity to accept these as config changes:
<activity ...
  android:configChanges="keyboardHidden|orientation|screenSize|screenLayout"/>

Also you will note the Activity has the same overridable method, the activity will get the method first, then pass it on to the attached Fragments.
For the observant you can do this on the fly using a context:
Configuration config = getResources().getConfiguration();

Hope that helps, it's meant to take into account hardKeyboards as well, but im sure you'll run into some device specific bug!


Interesting pattern in the decimal expansion of $\frac1{243}$

Question: There appears to be an interesting pattern in the decimal expansion of $\dfrac1{243}$:

$$\frac1{243}=0.\overline{004115226337448559670781893}$$

I was wondering if anyone could clarify how this comes about?
Comment: Perhaps what OP finds interesting is the $\dots11\dots22\dots33\dots44\dots55\dots$
Comment: A further observation shows that the pattern is $$000 + 4 | 111 + 4 | 222 + 4 | 333 + 4 | 444 + 4 | 555 + 4 | 666 + 4 | 777 + 4 | 888 + 4 + 1.$$ This suggests that $\frac{1}{243}$ is decomposted into fractions of different repeating periods, namely $$\frac{1}{243} = r + \frac{4}{10^{3}-1} + \frac{1}{10^{27}-1}$$, where $$r = \frac{111222333444555666777888}{10^{27}-1} = \frac{111333667111667334112}{1001001001001001001001001}$$ is the rational number with period $000111222333444555666777888$. But I cannot find a particular pattern anymore...
Comment: What do you regard to be interesting about that that doesn't happen for any other rational number? (Note that any rational number $\frac{a}{b}$ has either a terminating or infinite eventually-repeating decimal expansion)
Comment: the 00, 11, 22, 33, 44, 55 interspersed with 4 5 6 7 8 9, it seems too much to be a coincidence but I don't know the reason for the pattern
Comment: The decimal expansion of $1/42$ also has some cute stuff going on.
Comment: @MichaelHardy: Maybe I'm being dense, but what is the "cute stuff"? :)
Comment: By the way, $243=3^5$. I wonder if this is the only fifth power with this property...
Answer: $\frac{1}{243}=\frac{1}{333}+\frac{10}{8991}$
$\frac{1}{333}=.\overline{003}$
$\frac{1}{8991}=.\overline{000111222333444555666777889}=\frac{111}{998001}=\frac{111}{10^6-2\cdot10^3+1}$
Comment: I saw that subtracting off $.\overline{003}=1/333$ made things even prettier.  Alpha did the subtraction to get $10/8991$.  Then for explanation it seemed useful to divide out the $111$
Comment: This is a fairly nice observation, but actually we have $\frac{1}{8991} = 0.\overline{000111222333444555666777889}$.
Comment: Wow!  Now that's what I call a rabbit-out-of-a-hat, how the heck did you know that?!  But your hint about 8991 lead me to the following document which explains some things nicely  http://www.math.sjsu.edu/~goldston/otherpub.pdf
Comment: sos440 is right, the carry mucks things up.  so the third line in the answer is not exactly correct.  see the pdf i linked in the first comment
Comment: @wim:  fixed.  Thanks.


Why isn't Drupal's core once() function working in my simple test script?

Question: I am trying to console.log a message once and only once in Drupal 10.  I am cutting and pasting examples from https://www.drupal.org/node/3158256 into my file and I am still seeing the message appear multiple times in the console.
I have added the dependencies to the library:
my-library:
  version: VERSION
  js:
    js/my-library.js: { }
  dependencies:
    - core/drupal
    - core/once

And I have this simple test script in which I have cut & paste the example code from https://www.drupal.org/node/3158256
(function ($, Drupal, once) {
  'use strict';

  Drupal.behaviors.myBehavior = {
    'attach': function attach(context, settings) {

      once('init-once', context === document ? 'html' : context)
      .forEach(function initOnce(doc) {
        console.log('init-once', doc);
      });

    }

  };

})(jQuery, Drupal, once);

My goal is simply to console.log a message once and only once. How can I log a message only once?
Answer: core/once isn't for doing something just once, but for attaching a script just once. Then it's up to your script's logic to actually do something just once. You could for example toggle a simple CSS class on the  tag like oops-i-did-it and check in your JS if this class already exists or not before you trigger your magic.
And your libraries definition is missing the core/jquery dependency.
Bookmark this change record: https://www.drupal.org/node/3158256, it gives you a few really nice examples on how to use once() with and without jQuery. (You know that every times you use jQuery a small kitten dies? )
myfeature:
  js:
    js/myfeature.js: {}
  dependencies:
    - core/drupal
    - core/once

(function (Drupal, once) {
  Drupal.behaviors.myfeature = {
    attach(context) {
      // '[data-myfeature]' in the next line can also be 'div.my-class'
      // or '#my-id' etc.
      const elements = once('myfeature', '[data-myfeature]', context);
      // `elements` is always an Array.
      elements.forEach(processingCallback);
    }
  };

  // `value` in the next line is your actual DOM element. Do something with
  // `value` like `value.classList.add('hello-world')`.
  function processingCallback(value, index) {}
}(Drupal, once));

Comment: Haven't heard the jQuery killing kittens thing for literally years, really made me chuckle
Answer: I found something that works:
(function ($, Drupal, once) {
  'use strict';

  Drupal.behaviors.myBehavior = {
    'attach': function attach(context, settings) {

      if ($(once('my-test', 'body')).length) {
        console.log('my test');
      }

    }
  };

})(jQuery, Drupal, once);

Though I can't say I understand the syntax. It seems quite verbose and more difficult to grasp than Jquery .once().
Comment: This isn't good code - jquery isn't needed, and converting to a  jquery object just to test the length, when `once` returns a testable result, is just over-engineering. Leymannx's answer is v. good, that should be preferred
Comment: Jquery is needed, or at least preferable, for the actual feature I was building up to -- but not for the highly simplified console.log example in my answer above.  I ended up not needing `once` for the actual feature, though the answer from leymannx will be a useful reference the next time I consider using `once`.


Entity reference count in a parent node

Question: I have two content types
For example say X and Y
Every Y should refer any one of the X . I want to display how many number of Y is refering a particular X while viewing the X node. Please suggest some module which direclty achieve this requirement.
Answer: You can either use Views and Aggregation to Sum the number of references to show on a list.
But, I recommend using the Computed Field module to write some PHP code that is run on save to store an integer value that is the count of references. This value can be cached by drupal and used within Views and other modules.

Computed Field is a very powerful field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it. (Feeling the power yet? :) ) You
  can also choose whether to store your computed field values in the
  database with other content fields, or have them "calculated" on the
  fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of fields. So start cooking up your PHP based values!
Comment: Do i want to write some code after using computed field module?
Comment: Please read the documentation page on Computed field:
https://www.drupal.org/node/126522

Entity reference count in a parent node


MCMC Metropolis-Hastings initial values

Question: my posterior values that I obtained via Metroplis-Hasting are always around my initial values. For instance if I chose $\theta_0 =(1,2)$ my posterior values, after either taking mean or median, are around (1,2)
Any idea how to get the MH to explore more values?
For the proposal transition I am using T-distribution with  c$\Sigma$ covariance. constant c as suggested by Gelman. I tried to get the empirical bayes estimator and used them as initial values but it does not work.
CODE: USING R
     Trying to maximized log-likelihood function. ββ is of dimenssion 2
ββ[i,]   # Current value
log_post_curr= lik.b(ββ[i,])   # current log-likelihood values
ββ[i+1,] =rmvt(n=1,delta=ββ[i+1,],ΣΣ=sig,df=3) : # Generating new value from      T-distribution centralized at the current value with known covariance matrix. df: degree of freedom

log_post_prop= lik.b(ββ[i+1,]) # log-likelihood value for the proposed ββ

log_prop_curr= log(dmvt(ββ[i,],delta=ββ[i,],ΣΣ=sig,df=3))   # log T-value for the current ββ

log_prop_prop= log(dmvt(ββ[i+1,],delta=ββ[i+1,],ΣΣ=sig,df=3)) # log T-value for the proposed ββ

log_αα = log_prop_curr+log_post_prop - log_prop_prop-log_post_curr # log of the acceptance ratio

ϵϵ[i] = min(1,exp(log_αα))  # Acceptance ratio

u = runif(1)      # Generating a uniform value

if ((u <= ϵϵ[i]))

{
ββ[i,] <- ββ[i+1,]

counter=counter+1     # counting the number of accepted ββ

}

Comment: The correct way is to *edit* your original question, and **not** add an answer. The code you have provided is *not* an answer, and should be removed and included in the original questions.
Comment: Should you not retain the current value,  if you do not accept the proposal? Perhaps proposal tuning or running for more samples (plus thinning, if you wish) is needed?
Comment: How long are you running the algorithm? Did you try values very far away, like (100, 200)?
Comment: I did run for 10000 iterations.
Comment: It is impossible to read your code in the comment. Please edit your question to read the code if you think it will be helpful.
Comment: you can edit your **original** question by clicking on the edit button which is next to the *share* and *flag* button. Adding code in the comments is **not** helpful.
Comment: I repeat, you can edit your original question by clicking on the *edit* button at the bottom of your original question. Adding code in the comments is not helpful.
Comment: Done! Hope it's clear now
Comment: Please put some comments in the code to explain the steps, since it is a little unclear. Also, provide what language the code is in. You can do all this by editing the original question.
Comment: Can you write an explanation of your model and proposal (in words/equations besides the R code)?
Comment: I appreciate your comments. I fixed the errors and now it seems to work perfectly.
Answer: There are several coding issues:
1.The line of code
ββ[i+1,] =rmvt(n=1,delta=ββ[i+1,],ΣΣ=sig,df=3)

seems to show that the proposed value ββ[i+1,] is centred at itself: delta=ββ[i+1,] instead of being centred at the previous value delta=ββ[i,]
Similar corrections apply to the lines
log_prop_curr= log(dmvt(ββ[i,],delta=ββ[i,],ΣΣ=sig,df=3))
# log T-value for the current ββ

log_prop_prop= log(dmvt(ββ[i+1,],delta=ββ[i+1,],ΣΣ=sig,df=3))
# log T-value for the proposed ββ

2.In addition, if the condition u <= ϵ[i]is not satisfied the previous value should be allocated to the new value
ββ[i+1,] <- ββ[i,]

while, if the condition u <= ϵ[i]is satisfied, the previous value should not be replaced by the new value:
β[i,] <- β[i+1,]

3.As an aside, although there is nothing wrong theoretically, you do not need to exponentiate the log Metropolis ratio
ϵϵ[i] = min(1,exp(log_αα))  # Acceptance ratio

as it is more stable and overflow-robust to compare a log uniform to the log-ratio:
if ((log(u) < log_αα))

MCMC Metropolis-Hastings initial values


Ajuda com Update SQL

Question: Preciso aprender como posso atualizar minha tabela.
Tenho a tabela "Pessoa", esta tem a coluna "Descricao". No momento em que foi criada foi adicionado um maxlenght de 100 caracteres, preciso alterar isso para que possa ser adicionado 1000 caracteres.
O detalhe é que eu já tenho 25 clientes, ou seja, foram feitas 25 base de dados, cada uma possui Pessoa>Descricao. Existe alguma forma de eu atualizar todas as base de dados por SQL ou somente uma por vez? Se sim como posso fazer isso?
Detalhe: Estou usando o PostgreSql
Comment: Você precisa do comando SQL para realizar a alteração da coluna na tabela ou quer um script para rodar o comando em todos os 25 database de uma vez?
Comment: Quero saber como rodar o SQL em todos de uma vez...
Comment: Pelo que entendi você quer um script para rodar em 25 instâncias de base de dados "iguais". Você pode criar um procedure e fazer um laço para percorrer todas as suas instâncias e executar o alter table para cada uma. Um SQL que execute em 2 ou mais instâncias não é possível.
Comment: Entendi, nunca usei scripts, você poderia me passar um exemplo de como posso fazer isso?
Answer: O postgres mantêm cada database isolado, sendo assim, se estiver conectado no database x você não consegue realizar consultas no database y.
Claro que existem recursos para a comunicação entre diferentes databases, como o postgres_fdw, por exemplo, mas no seu caso poderia ser utilizado o psql através do shell script.
SENHA_POSTGRES='senha'
USUARIO_POSTGRES='usuario'
LISTA_NOMES_BANCOS='db1 db2 db3'
COMANDO="alter table pessoa alter column descricao type varchar(1000);"

for NOME_BANCO in $LISTA_NOMES_BANCOS ; do
    echo 'Executando consultas no banco '  $NOME_BANCO
    PGPASSWORD=$SENHA_POSTGRES psql -h localhost -d $NOME_BANCO -U $USUARIO_POSTGRES -c "$COMANDO"
done

Na variável LISTA_NOMES_BANCOS serão definidos os nomes dos databases que serão modificados. No for será executado o comando SQL pelo psql de maneira dinâmica para cada banco.

Ajuda com Update SQL


Explain this step-by-step

Question: This question from limits has been bothering me. Could anyone help me.
$\lim_{x\rightarrow 0}{(a^x + b^x +c^x/3) ^{1/x}}$
Answer: If we take exponentials and logarithms, we will get
$$\exp\left(\lim_{x\rightarrow 0}\frac{\log(a^x + b^x + c^x) - \log(3)}{x}\right)$$
Let us examine the inner limit. We can see that the inner limit is of the indeterminant form $\frac{0}{0}$. We apply L'Hopital's rule:
$$\overset{H}{=}\lim_{x\rightarrow 0}\frac{a^x\log a + b^x\log b + c^x\log c}{a^x + b^x + c^x}$$
Can you finish off the limit from here? Don't forget to exponentiate the final result.
Comment: You can only do this because the logarithm is a continuous function. This is a general result which relies on the continuity of the function.
Comment: Thank you for the help. I(sadly) did not know that the logarithm function could be applied inside the limit. Thank you again.

Explain this step-by-step


Why are my prediction intervals a little too narrow?

Question: I'm trying to make a little function to make population-level predictions from a model that includes random effects, which in turn was fit using a package that doesn't support interval="prediction".  (As far as I can tell, the reason why the package doesn't do so is that prediction is fraught when trying to predict within one of the model's levels -- but I just want population-level predictions).
So anyway, testing my code and comparing against the in-built code in predict.lm, my intervals are a little too narrow.  Anybody able to help me figure out why?
set.seed(13)
n=100
x1 = runif(n)
x2 = runif(n)
X = cbind(x1,x2)

y = x1 + x2 + rnorm(n)
m = lm(y~x1+x2)
summary(m)

d = predict(m,interval = "prediction")
auto = d[,3]-d[,1]

getpred = function(vals){
    qt(.975,n-(2+1))*sqrt(var(m$resid)* (1+ t(vals) %*% solve(t(X)%*%X) %*%vals))
    }
man = apply(X,1,getpred)

plot(density(auto),xlim=c(2.1,2.3),ylim = c(0,30))
lines(density(man),col="red")

Thanks in advance!
Comment: Where is your model with random effects ?
Comment: I suppose I could post it. Will do so when back to my comp. Just wanted to first get intervals working where I can test them against a trusted routine.
Answer: You forgot the intercept and did not calculate the residual variance correctly.
Here is how I would do it:
#get the design matrix
Designmat <- model.matrix(eval(eval(m$call)[-2]), as.data.frame(X))
#this is the same as cbind(1,X) for your model

#calculate the standard errors
predvar <- diag(Designmat %*% vcov(m) %*% t(Designmat))
SE <- sqrt(predvar)
SE2 <- sqrt(predvar+summary(m)$sigma^2)

tfrac <- qt(0.975, m$df.residual)

all.equal(auto,tfrac*SE2)
#TRUE

And here is your code fixed (though it is less general this way):
getpred <- function(vals){
  qt(.975,n-(2+1))*sqrt(summary(m)$sigma^2* (1+ t(vals) %*% solve(t(cbind(1,X))%*%cbind(1,X)) %*%vals))
}
man <- apply(cbind(1,X),1,getpred)
all.equal(unname(auto),man)
#TRUE

You can find code for calculation of prediction intervals for mixed-effects models in the r-sig-mixed models FAQ. I also put an example (with some important warnings) on StackOverflow.
Comment: or maybe it would be a whole lot trickier, now that I think about it.  thanks for the helpful answer anyway.
Comment: That's a helpful answer.  I use lme(4) for some things, but mostly I use gam, with random effects specified by s(X,bs="re").  I can't use the code on the FAQ that you cited, but I should be able to do something with less cute syntax along the same lines.