Proof regarding division with a remainder

Question: Let $a\in\mathbb{Z},n\in\mathbb{N}$. If $a$ has a remainder $r$ when divided by $n$, then $a\equiv r\pmod n$
I've done some of these questions before with modulus and division, but I'm unsure of how to approach it with the addition of a remainder
Comment: How do you define remainders? How do you define $a \equiv r \pmod n$? Personally, I would define both by saying that there exists some $q \in \mathbb Z$ such that:
$$
a = qn + r
$$
Answer: The division algorithm tells us that, when an integer $x$ is divided by a natural number $n$, then $x = qn + r$ for some $q \in \mathbb{Z}$ and $0 \leq r < n$.
Now can you show $n|(x-r)$?
By definition, $x \equiv r \pmod{n} \iff n|(x-r)$.


How to set a file upload monthly quota on a role basis in Drupal 7?

Question: I'm using Drupal 7 and I'm quite a newbie here.
I'm building a small sharing/social network site where users will be able to upload different kind of files (mainly, pictures and zipped archives, but I'm not limiting the kind of files one can upload).
Is there a way to set a per-user upload limit/quota (say, 1Gb/month) on a user role basis?
Edit

Using Amazon S3 and similar services is a viable option.
Users' privacy should be protected, i.e. they should be able to set
access permissions on the files they upload (private, friends-only,
public), and it would be interesting to have the "expiry" option,
i.e. a shared file could expire and be automatically deleted from
server after a while.
I know there is IMCE module, I never tried it but from its
description it seems a bit buggy and not so safe from a privacy perspective.
Answer: The IMCE module allows, "configurable limits for user roles: file size per upload, directory quota, file extensions, and image dimensions."
Comment: Thanks, your answer seems, at present, the only precompiled option. I'm accepting it, although I think I'll write a module myself to plug the quota functionality into Amazon S3.
Answer: User Disk Quota seems to do the job as well


Finding the covariance of two specific random variables $X$ and $Y$

Question: Let there be some constant $c \in [0, 1]$ and let $X$ be some random variable with the mean $\mu$. For convenience we could say that $X \sim N(0, 1)$, but it can be any distribution with a defined mean. Now let $Y$ be another random variable so that samples from $Y$ are generated in the following way:
Sample $u$ from $U(0, 1)$ and $x$ from $X$. If $u<c$, return $x$, otherwise return $|\mu - x|$.
How do we find the joint probability distribution of $X$ and $Y$ so that we can calculate their covariance?
Comment: No need to find the joint distribution for $(X,Y)$.  You just need to compute $E[XY]$ and $E[Y]$ to form $Cov(X,Y) = E[XY]-E[X]E[Y]$.  To compute $E[Y]$ use the law of total expectation (conditioning on something convenient), same with $E[XY]$.  Can you finish?
Answer: I preassume $0<c<1$ and independence where it concerns the samples.
Then $Y=XB+|\mu-X|C$ where $B$ has Bernoulli distribution with parameter $P(U<c)=c$, $B+C=1$ and $X$ and $B$ are independent. With bilinearity of $\text{Cov}$ we find:
$$\text{Cov}(X,Y)=\text{Cov}(X,XB+|\mu-X|C)=\text{Cov}(X,XB)+\text{Cov}(X,|\mu-X|C)$$
For the first term we find:
$\text{Cov}(X,XB)=\mathbb E[X^2B]-\mathbb EX\mathbb E[XB]=\mathbb EX^2\mathbb EB-(\mathbb EX)^2\mathbb EB=\text{Var}X\mathbb EB=c\text{Var}X$
For the second term we find likewise:
$\text{Cov}(X,|\mu-X|C)=(1-c)\text{Cov}(X,|\mu-X|)$
So for finding $\text{Cov}(X,Y)$ it is enough to find $\text{Var}(X)$ and $\text{Cov}(X,|\mu-X|)$.


How do you find the integer values where x^y=z?

Question: Let's say I give you a number: 2985984, which is equal to $x^y$, where both $x$ and $y$ are integers. How would you find $x$ and $y$ (hint: the answer is 12^6)?
Now, let's say I'll say that $x$ is 12. then you can write:
$12^y = 2985984$.
$log(12^y) = log(2985984)$
$y\times log(12) = log(2985984)$
$y = \frac{log(2985984)}{log(12)}$
$y=6$
A more general form would be:
$y = \frac{log(2985984)}{log(x)}$
How would I find which integer values of $x$ and $y$ would solve this equation?
Comment: This should be loosely equivalent to deciding if an integer is prime (consider the worst case scenario), and so probably proportional to $\sqrt{n}$ in computation time.
Comment: @DavidPeterson:  While screening out perfect powers is a step in determining if a number is prime,  it seems to be an easier problem.  See the description of the [AKS primality test](https://en.m.wikipedia.org/wiki/AKS_primality_test).
Answer: The first step would be to factor $z = 2985984 = 2^{12}3^6.$ In particular, note that $$z = \left(2^2 \cdot 3 \right)^6 = \left(2^4 3^2\right)^3 = \left(2^63^3\right)^2 = \left(2^{12}3^6\right)^1.$$ In general, for $z = p_1^{e_1}p_2^{e_2}p_3^{e_3} \cdots$ for primes $p_i$ and positive integers $e_i$, all $y \mid \gcd (e_1,e_2,e_3,\dots)$ will work. From here, we can find $x = \sqrt [y] z,$ and if $y$ is even $x = - \sqrt [y] z$ also works.
Comment: Remember $x$ can be negative too.
Comment: @Landuros fixed.
Comment: So prime factorization is the fastest way to approach this? As Prime Factorization is one of those NP problems, I was hoping there's a faster way.


$T$ an irreducible linear operator $\Longleftrightarrow T$ cyclic and $\mu_T(x)$ irreducible.

Question: Definitions: Let $V$ be a finite-dimensional vector space over $\mathbb{F}$ and $T$ an operator on $V$. Let $\mu_{T,v}(x)$ denote the minimal polynomial of $T$ with respect to $T$ $($ i.e. the unique monic generator of $\text{ann}(T,v)= \{f(x) \in \mathbb{F}[x]:f(T)(v)=0 \})$ and let $\mu_T(x)$ denote the unique monic polynomial of least degree in $\text{ann}(T)=\{f(x) \in \mathbb{F}[x]:f(T)(v)=0 \text{ for every } v \in V \}.$
I'm reading through my textbooking trying to understand the following theorem:

Theorem. $T$ is an irreducible operator (No non-trivial $T$-invariant subspace) $\Longleftrightarrow T$ is cyclic (there is a $v \in V$ such that $\langle T,v \rangle = V)$ and $\mu_T(x)$ is irreducible.

For the $(\Leftarrow)$ part of the theorem (sketch), assume $V = \langle T,v \rangle$, let $w \in V, w \ne 0$ and then show $\mu_{T,w}(x)=\mu_{T}(x) = \mu_{T,v}(x)$. Then the dimension of the $T$-cyclic subspace generated by $w$, $\dim \langle T,w \rangle=\{f(T)(w):f(x) \in \mathbb{F}[x] \}$ is equal to $\dim \langle T,v \rangle = \dim V$. From this we conclude that $V$ contains no non-trivial $T$-invariant subspace which proves $T$ irreducible.
Question $1$: Why does $\dim \langle T,w \rangle = \dim V = \dim \langle T,v \rangle$ imply that $V$ contains no non-trivial $T$-invariant subspace? It seems that we have proved that every $T$-cyclic subspace $\langle T,v \rangle$ of $V$ has the same dimension as $V$, but I am not clear why this implies that there are no non-trivial $T$-invariant subspaces of $V$. I'm thinking it has to do with the fact that the $T$-cyclic subspaces of $V$ are $T$-invariant.

Corollary. Let $V$ be a vector space, $T$ an operator on $V$, and $v \in V$ such that $\mu_{T,v}(x)$ is irreducible. Let $W$ be a $T$-invariant subspace of $V$. Then either $\langle T,v \rangle \subset W$ or $\langle T,v \rangle \cap W = \{0\}.$

Question $2$. How does this corollary follow?
Comment: What is your textbook?
Answer: Question 1: Let $W \neq 0$ be a $T$-invariant subspace. Choose $0 \neq w \in W$ and consider the $T$-invariant subspace $\left<T, w \right>$. Since $\left< T, w \right> \subseteq W$ and $\dim \left< T, w \right> = \dim V$, we must have $\dim W = \dim V$ so $W = V$.
Question 2: The operator $T|_{\left< T, v \right>}$ is cyclic and so, by the theorem, $T|_{\left< T, v \right>}$ does not have non-trivial invariant subspaces. Since the intersection of $T$-invariant subspaces is $T$-invariant and $W \cap \left< T, v \right> \subseteq \left< T, v \right>$, we must have $W \cap \left<T, v \right> = \{ 0 \}$ or $W \cap \left< T, v \right> = \left< T, v \right>$ which implies that $\left< T, v \right> \subseteq W$.


Calculating power function for ANOVA

Question: There are several functions in R to calculate the power of a test, for example, the pwr-functions of the pwr package.
My question is how we get this function for ANOVA (pwr.anova.test)?
I know that
\begin{align}
1-\beta &= P(H1|H1)   \\
        &= P(F>F_{1-\alpha,k-1,N-k})  \\
        &= 1-P(F\le F_{1-\alpha,k-1,N-k}) \\
        &= 1-P(MQE/MQR\le F_{1-\alpha,k-1,N-k}) \\
~  \\
        &= 1-P\bigg(n k \bigg(\frac{^{\sum(\bar{x}_{i.}-\bar{x}_{..})^2}/_{(k-1)}}
                                   {^{\sum\sum(x_{ij}-\bar{x}_{i.})^2}/_{k(n-1)}} -
                              f^2\!+\!f^2\bigg) \le F_{1-\alpha,k-1,N-k}\bigg)  \\
~  \\
~  \\
        &= 1-P\bigg(nk\bigg(\frac{^{\sum (\bar{x}_{i.}-\bar{x}_{..})^2}/_{(k-1)}}
                                 {^{\sum\sum(x_{ij}-\bar{x}_{i.}^2)}/_{k(n-1)}} - \frac{^{\sum(µ_i-µ)^2}/_k}{\sigma^2}\bigg)\le F_{1-\alpha,k-1,N-k}-nkf^2\bigg)  \\
~  \\
        &= ???...??? \\
        &= 1-P(F_{k-1,N-k}\le F_{1-\alpha,k-1,N-k}-knf^2)  \\
        &=
\end{align}
p.body =  pf(qf(\alpha, k-1, (n-1)*k, low=FALSE), k-1, (n-1)k,
                k*n*f^2, low=FALSE)

With $f^2$ the effect;
$knf^2$ the non-centrality parameter; and
$\sigma^2$ the error variance within groups;
But what does the function which has a $F_{k-1, N-k}$ distribution look like? It has to be the (variance between groups/df) / (variance within groups/df)$-knf^2$, but how can I write these so that I see the distribution? In my calculation I did not see it. I have never found the exact way how to get to this formula. Maybe you can help.
Comment: I don't understand what you are asking (I'm not proficient in English but usually I easily understand mathematical and R questions)
Comment: Your question is still not clear to me but I'm under the impression that from one hand you are interested in the [noncentral F-distribution](http://en.wikipedia.org/wiki/Noncentral_F-distribution), but you have a strange notation ($-knf^2$ sounds like *"minus" $knf^2$*). See also the help of the F-distribution in R by typing `?df`.
Comment: I still don't understand. I can try to explain the power calculation in details, would it answer to your question ?
Comment: Done. Now could you precise your question ?
Comment: First of all, thanks a lot Stéphane. Thats what i mean, ok not exaktly but near. You said that $F \sim F_{m-l,n-m}$ thats clear  but if we write $F=\frac{SS_T/(I-1)}{SS_E/((n-I)}$ like in [link](http://en.wikipedia.org/wiki/Analysis_of_variance) than we will get $F=\frac{\sum(\bar{x}_{i.}-\bar{x}_{..})^2/(k-1)}{\sum\sum(x_{ij}-\bar{x}_{i.})^2/k*(n-1)}$. Now if we look at the probability $1-P(F<=F_{k-1,n-k}) = 1-P(\frac{n*\sum(\bar{x}_{i.}-\bar{x}_{..})^2/(k-1)}{\sum\sum(x_{ij}-\bar{x}_{i.})^2/k*(n-1)}<=F_{k-1,n-k})$ Am I right so far? Now we can add $f^2$ and remove $f^2$ ($f^2$ the effect)
Comment: $= 1-P(n*k(\frac{\sum(\bar{x}_{i.}-\bar{x}_{..})^2/(k-1)}{\sum\sum(x_{ij}-\bar{x}_{i.})^2/(n-1)})<=F_{k-1,n-k,1-\alpha}) =1-P(n*k(\frac{\sum(\bar{x}_{i.}-\bar{x}_{..})^2/(k-1)}{\sum\sum(x_{ij}-\bar{x}_{i.})^2/(n-1)}-f^2+f^2)<=F_{k-1,n-k,1-\alpha}) =1-P(n*k(\frac{\sum(\bar{x}_{i.}-\bar{x}_{..})^2/(k-1)}{\sum\sum(x_{ij}-\bar{x}_{i.})^2/(n-1)}-\frac{\sum(\frac{1}{k}*(µ_i-µ)^2)}{\sigma^2}+\frac{\sum(\frac{1}{k}*(µ_i-µ)^2)}{\sigma^2})<=F_{k-1,n-k,1-\alpha})$ like in [link](http://www.statmethods.net/stats/power.html) for n=n1=...=nk.
Comment: $=1-P(n*k(\frac{\sum(\bar{x}_{i.}-\bar{x}_{..})^2/(k-1)}{\sum\sum(x_{ij}-\bar{x}_{i.})^2/(n-1)}-\frac{\sum(\frac{1}{k}*(µ_i-µ)^2)}{\sigma^2})<=F_{k-1,n-k,1-\alpha}-n*k\frac{\sum(\frac{1}{k}*(µ_i-µ)^2)}{\sigma^2})$. Let us only look at the left side: $n*k(\frac{\sum(\bar{x}_{i.}-\bar{x}_{..})^2/(k-1)}{\sum\sum(x_{ij}-\bar{x}_{i.})^2/(n-1)}-\frac{\sum(\frac{1}{k}*(µ_i-µ)^2)}{\sigma^2})$ how can I write this to see the $F_{k-1,n-k} distribution?
Comment: Sorry but there are many unclear points. For example your final question, what do you mean by "seeing" a Fisher distribution ?
Comment: What I mean is how can I rewrite the sums so that I will have something like $\frac{*/(k-1)}{**/n-k}$ because that is what I need for Fisher distribution. Or did I make any mistakes befor the final calculation?
Comment: I just want to make a small point here. In your last paragraph, you state "It has to be the (variance between groups/df) / (variance within groups/df)". This is an easy misunderstanding. It isn't the *variance*, it would be the *sum of squares* within... etc.
Answer: Power of F-tests for Gaussian linear models
General $F$-test
Any Gaussian linear model can be written $\boxed{Y=\mu+\sigma G}$ where $G$ has the standard normal distribution on $\mathbb{R}^n$ and $\mu$ is assumed to belong to a linear subspace $W$ of $\mathbb{R}^n$.
Usually, the theory of Gaussian linear models treat them with the $Y=X\beta+\sigma G$ writing, corresponding to $W=\text{Im}(X)$. There are good reasons for that but the underlying geometry is clearer with the $\boxed{Y=\mu+\sigma G}$  treatment.
The so-called "ANOVA test" is a particular test of a F-test for a null hypothesis $H_0\colon\{\mu \in U\}$ where $U\subset W$ is a linear subspace. Actually the F-test exactly coincides with the likelihood-ratio test in this situation, and it is based on the  Fisher statistic
$$
F  = \frac{{\Vert P_Z Y\Vert}^2/(m-\ell)}{{\Vert P_W^\perp Y\Vert}^2/(n-m)},
$$
where  $Z=U^\perp \cap W$ is the orthogonal complement of $U$ in $W$, and denoting $m=\dim(W)$ and $\ell=\dim(U)$.
Obviously $\boxed{P_Z Y = P_Z \mu + \sigma P_Z G}$ and
$\boxed{P_W^\perp Y = \sigma P_W^\perp G}$.
When $H_0\colon\{\mu \in U\}$ is true then $P_Z \mu = 0$ and therefore
$$
F  = \frac{{\Vert P_Z G\Vert}^2/(m-\ell)}{{\Vert P_W^\perp G\Vert}^2/(n-m)} \sim F_{m-\ell,n-m}
$$
has the Fisher $F_{m-\ell,n-m}$ distribution. Consequently, from the  classical relation between the Fisher distribution and the Beta distribution, $R^2 \sim {\cal B}(m-\ell, n-m)$.
In the general situation we have to deal with $P_Z Y = P_Z \mu + \sigma P_Z G$ when $P_Z\mu \neq 0$. In this general case one has ${\Vert P_Z Y\Vert}^2 \sim \sigma^2\chi^2_{m-\ell}(\lambda)$, where $\chi^2_{m-\ell}(\lambda)$ is the noncentral $\chi^2$ distribution with $m-\ell$ degrees of freedom and  noncentrality parameter $\boxed{\lambda=\frac{{\Vert P_Z \mu\Vert}^2}{\sigma^2}}$, and then
$\boxed{F \sim  F_{m-\ell,n-m}(\lambda)}$ noncentral Fisher distribution. To compute $P_Z\mu$, note that $P_Z = P_W - P_U$ and $P_W\mu=\mu$, hence the only thing to compute is $P_U \mu$.
Power of the $F$-test
The power of the $F$-test depends on the significance level $\alpha$ which is chosen by the user. The critical value $c$ of the test is the value for which $\Pr_0(F>c)=1-\alpha$ where $\Pr_0$ denotes the probability under the null $H_0$. The power is then $\Pr(F>c)=1-\alpha$ where $\Pr$ denotes the probability under the unknown parameters. As we have seen, $\Pr$ only depends on $\lambda$, $n$, $m$ and $l$.
R code
The effect size in this situation is $\sqrt{\frac{\lambda}{n}}$, and it is more usual to take the effect size rather than the non-centrality parameter $\lambda$ as an input of the power. Thus I have written the following R function which returns the power using the effect size as an argument rather than the noncentrality parameter.
# alpha : significance level eff : effect size ; n : sample size ; m :
# number of parameters of the model ; l : number of parameters of the
# submodel H0 ;
Power <- function(alpha, eff, n, m, l) {
    df1 <- m - l
    df2 <- n - m
    c <- qf(1 - alpha, df1, df2)
    lambda <- eff^2 * n
    pow <- pf(c, df1, df2, ncp = lambda, lower.tail = FALSE)
    return(pow)
}

Example
Power(alpha = 5/100, eff = 0.5, n = 48, m = 5, l = 4)
## [1] 0.92303

The case of ANOVA
The pwr.anova.test() function of the pwr package calculates power of ANOVA for the balanced case only. For example, when there are $3$ groups, $4$ observations per group, the power for $\alpha=5\%$ and for an effect size of $0.5$ is
library(pwr)
pwr.anova.test(3, 4, 0.5, 5/100)
##
##      Balanced one-way analysis of variance power calculation
##
##               k = 3
##               n = 4
##               f = 0.5
##       sig.level = 0.05
##           power = 0.24088
##
## NOTE: n is number in each group

With the general notations of the $F$-test, here $U$ is a one-dimensional subspace corresponding to the assumptions that all group means are equal. The space $W$ has the same dimension as there are groups, here $3$. Thus using my function one get the power as follows:
Power(alpha = 5/100, eff = 0.5, n = 12, m = 3, l = 1)
[1] 0.24088

Comment: @matus $P_U$ is the projector on the vector space $U$.
Comment: I have no clue what variables $P_Z$ and $P_W$ are. Please give definitions.
Comment: +1, however you can use the `pwr` package to compute power for the case of unequal group sizes (despite what its documention implies). For the `n` parameter, you take the average number of observations in each group (I know, unintuitive, but under the hood `pwr` uses only the total sample size to find power). Importantly, for the `f` parameter you take care of computing correctly the effect size, which will be different if the group sizes are equal or unequal. I give an example here of how to compute the correct effect size: https://stats.stackexchange.com/a/637646/164936

Calculating power function for ANOVA


Salvar e atualizar entidades

Question: ou pessoal estou tentando dar uma melhorada no meu método genérico que adiciona e atualiza, segue o código:
public void InsertOrUpdate(T entity)
{
     if (entity.Id == 0)
     {
         context.Set<T>().Add(entity);
     }
     else
     {
        var query = context.Set<T>().Find(entity.Id);
        context.Entry(query).CurrentValues.SetValues(Entity);
     }
     //context.Entry(entity).State = entity.Id == 0 ?
     //                     EntityState.Added : EntityState.Modified;
     context.SaveChanges();
}

já dei uma boa pesquisada na internet e não encontrei algo mais performático ou mais Clean, se alguém poder me ajudar com alguma biblioteca agradeço desde já.
Comment: Está funcionando? tem algum problema, ou é mesmo como está escrito o código que te incomoda?
Answer: Tem isto aqui:
db.Set<Entidade>().AddOrUpdate(meuObjeto);

Aceita, aliás, vários objetos:
db.Set<Entidade>().AddOrUpdate(meuObjeto1, meuObjeto2, meuObjeto3);

Salvar e atualizar entidades


How can I change the precision in the decimal field of CCK?

Question: I have a decimal field.  The field has a minimum precision of 10. Can I change this precision?  I need that the numbers allowed have the next format:  19.1, 20.3.  In other words that the number be  of  2 integers and one decimal.
I select one decimal in the configuration of the decimal field , however the field accepts big numbers.  How can I change this, the solution can be with form_alter.
Thanks.
Answer: yeah, _node_validate is a flexible way. an alternative to a custom module, can be use a Rules module and integration with Rules Forms support module. Also will be useful use a more flexible CCK field, then, this will allow to validate whatever number with the model that you want.
.1. install the modules.
.2. then we need now is indicate to rules in what form must work. You must go to Rules > Form events and enable the option Enable event activation messages on forms. then go to the respective form and click in the Activate events for.. (the name of the form)
.3. go to rules and add a new rule and select in the Event: the respective event on which you want to evaluate this rule. (to this case Rules Forms modules will include the name of your form in the Rules Forms section on the Event select list.
.4. In a condition of rule add a numeric comparison (or whatever other condition that you want, for example a custom php code):
example with numeric comparison:
field Number 1 (php code): $number= $form_state['values']['number'][0]['value']; if ($number < 10 || $number > 100) { echo 1; }
Field Comparison: Equal to
Field Number 2: 1
.5. in the action option, of your rule, add an action like a form error message to warn about change the syntax of the number. in Form element ID add the ID of the field, for example field_color (you can review the name in the list of fields CCK of the content/node type).
.6. Create a new rule if is necessary, like $number= $form_state['values']['number'][0]['value']; if (...) { echo 1; } and add the respective error message.
do not forget enable the rule, to see working your rule!.
(I hope that this information be useful)
Comment: Hi.  Your idea it's works with rules.  I will take it this idea if with node_validation is not possible, because I have many forms for validate.

I am going to try to validate that the number of decimals is not bigger that one.

Thanks for your answer and your time.
Answer: I don't think this is possible via form alter however I would implement these verifications in a hook_nodeapi()  to check that your number is between 10 and 99.9 (2 decimals) and a precision of just one digit.
Put this code in a custom.module:
function mymodule_nodeapi($node, $op, $a3, $a4) {
  if ($op == 'validate') {
    $number = $node->field_mynumber[0]['value'];
    if ($number < 10 || $number > 100) {
      form_set_error('field_mynumber', t('Please select a number between 10 and 99.9.'));
    }
    if (round($number, 1) != $number) {
      form_set_error('field_mynumber', t('Please select a number with a precision of 1 digit.'));
    }
  }
}

Of course you can also add a test on $node->type to restrict this on some of your content types.
PS: answer updated to use D6
Comment: Thanks for your answer and your time.  Your idea is good but your option did not work to me.

I replacement the "field_number" by my field in cck in the code but it doesn't work, what will it be my mistake?

 What's the meaning of "node->language"? I'm sorry for this question.

Thanks again.
Comment: Are you on Drupal 7 because `[$node->language]` is Drupal 7 specific, if you're on D6 you have to remove this part.
Comment: hello.  I put the next code:

function mymodule_node_validate($node, $form, &$form_state) {
  $number = $node->field_mynumber[0]['value'];
  if ($number < 10 || $number > 100) {
    form_set_error('field_mynumber', t('Please select a number between 10 and 99.9.'));
  }
  if (round($number, 1) != $number) {
    form_set_error('field_mynumber', t('Please select a number with a precision of 1 digit.'));
  }
}

and it doesn't work.  I am working with Drupal 6.  I'm sorry, I forgot to put the version of drupal.
Comment: Ok I updated my answer, hook_node_validate is specific to D7.
Comment: Hello.  Very good.  This it works well for validate the numbers between 10 and 100 but it doesn't validate that the number only has one decimal.  Thanks very much.
Comment: What are the number you'd like to validate ? Is 12.34 valid or just 12.3 ? Give me a little more precision to update my answer.
Comment: I'm sorry.  I need numbers as 12.3.  Thanks.

Thanks.
Comment: I updated my answer which was wrong for the precision part ;)
Comment: Thanks for your answer.  I am going to review later and I'll give an answer.
Is it correct this code?  if (if ((round($number, 1) - $number) != 0))

Thanks for your help and your time.
Comment: Yes it is (at least with my tests).
Comment: I tested the code and shows error in the module.  If I delete an " if" doesn't show error but not validate.  Thanks for the idea.  It's a good idea your code.
Comment: Should be corrected, sorry about that.
Comment: If your number is for example `1.23` my code will display an error as `round(1.23, 1)` gives you 1.2 and this is different from `1.23` thus the error in the validation part.
Comment: yes to your opinion.  The problem is mine, I see that the != is not working, but I believe that your code is good.  Thanks.


I am getting java.lang.ArrayIndexOutOfBoundsException error

Question: I am getting java.lang.ArrayIndexOutOfBoundsException error.
public class Trainee implements EvaluationDetails
{
    private int traineeId;
    private String traineeName;
    private double traineeMarks[];

    public Trainee(int id,String name,double Marks[])
    {
        traineeId=id;
        traineeName=name;
        traineeMarks=Marks;

    }

    public int getTraineeId()
    {
        return traineeId;
    }
    public String getTraineeName()
    {
        return traineeName;
    }

    public boolean validateTraineeMarks()
    {
        if(noOfCourses>0 && noOfCourses<8)
        {
            for(int i=0;i<=traineeMarks.length;i++)
            {
                if(traineeMarks[i]>0 && traineeMarks[i]<100)
                continue;
                else
                    return false;
            }
            return true;
        }
        else
            return false;
    }

    public double calculateGPA()
    {
        int GPA;
        int Cp[]=new int[7];
        boolean bool=validateTraineeMarks();
        if(bool==true)
        {
            for(int i=0;i<traineeMarks.length;i++)
            {
                if(traineeMarks[i]>=85 && traineeMarks[i]<=100)
                Cp[i] = 5;
                else if(traineeMarks[i]>=65 && traineeMarks[i]<85)
                Cp[i] = 4;
                else if(traineeMarks[i]>=0 && traineeMarks[i]<=65)
                Cp[i] = 3;
            }
            GPA = //GPA calculation logic
        }
        else
            {
                System.out.println("Improper values for trainee marks");
                return 0.0;
            }

        return GPA;
    }
}

The main class is as shown below:
public class Demo {
public static void main(String[] args)
{

    double marks[]={74.0,57.0,86.0,93.0,56.0,73.5,83.0};
    Trainee t = new Trainee(102,"Dixon",marks);

    System.out.println("Trainee Id:"+t.getTraineeId());
    System.out.println("Trainee Name:"+t.getTraineeName());
    System.out.println("GPA is"+t.calculateGPA());
}
}

The interface is coded as below:
public interface EvaluationDetails
{
    int creditpoints[]={3,3,4,4,2,3,5};
    int noOfCourses=7;
    public double calculateGPA();
}

Comment: In which line you getting error?
Comment: which line u r getting that exception ?
Comment: Why didn't you use the debugger first?
Answer: for(int i=0;i<=traineeMarks.length;i++) should be for(int i=0;i<traineeMarks.length;i++)
the problem is you are trying to access array.length + 1 elemnt
Answer: Your mistake is here:
for(int i=0;i<=traineeMarks.length;i++)
Indexes in java (and all c-like languages) start from 0 and therefore the last index of array is length-1. So, fix your loop definition as following:
for(int i=0;i<traineeMarks.length;i++)
Answer: Here is your mistake:
for(int i=0;i<=traineeMarks.length;i++)

you should go from i=0 to traineeMarks.length-1 so,
for(int i=0;i<traineeMarks.length;i++)

Answer: for(int i=0;i<=traineeMarks.length;i++)
should be
for(int i=0;i< traineeMarks.length;i++)
Answer: for(int i=0;i<=traineeMarks.length;i++) //this is wrong this cause to  java.lang.ArrayIndexOutOfBoundsException

use
 for(int i=0;i<traineeMarks.length;i++)


how to pass either a @input label prop or the content as label to a angular button component?

Question: I am trying to use a label that can come to the component as an @Input() or as content to a button:
@Component({
  selector: 'button[app-button]',
  template: `
  <ng-container *ngIf="label">
    <ng-content>{{label}}</ng-content>
  </ng-container>
  <ng-container *ngIf="!label">
    <ng-content></ng-content>
  </ng-container>
  `,
})

Problem is that the above does work because ng-content can not have content.
Any ideas how to solve this without wrapping the button in another host element?
EDIT: I would like to use it as follows.

<button app-button>I am a label</button>

<button app-button label="Another label"></button>

<button app-button [label]="'Wow a Label'"></button>

Comment: Why do you need `ng-content` in the first case? Can't you just use a `div`?
Comment: I could wrap it in a div, just want to know if it is possible without extra host element wrapper.
Comment: Okay, I don't understand the question then. Can you show us the two different usages of your component and the approximate resulting html you want to have? Or make a Stackblitz to show what you want?
Comment: added some examples of how the component would be used.
Answer: Is this what you want??
@Component({
  selector: 'button[app-button]',
  template: `
  <ng-container *ngIf="label">
      {{label}
  </ng-container>
  <ng-container *ngIf="!label">
    <ng-content></ng-content>
  </ng-container>
  `,
})

Comment: That way the label content does not go as the button child.
Answer: What you actually want is not a Component, but a Directive. If you provide an attribute selector the provided template will be ignored. Inside your Directive you can get access to the host element via ElementRef. So what you want, could be implemented like this:
@Directive({
  selector: 'button[app-button]',
})
export class ButtonDirective implements OnInit {
  @Input()
  label: string;

  constructor(
    private el: ElementRef,
  ) {
  }

  ngOnInit() {
    if (this.label) {
      this.el.nativeElement.innerText = this.label;
    }
  }
}

You could also take a look at the documentation for attribute directives. If you need to modify the host element you could also look into structural directives.
That being said, this doesn't feel like the angular way to do things. I would consider just building an <app-button></app-button> component with this feature.
Comment: yes, I have indeed been fighting with the framework because most of the components I create in other companies are either coming from a design system, or we create with html in mind and html does not care about this wrapping unless I want webcomponents or dom encapsulation. But that was the way angular choose to implement and it is kinda of a pain when you are counting that your html will have no wrapping between two specific elements.


Total number of lines in a 2D grid

Question: I have a 2D grid of $M \times N$ points. I need to find the total number of lines (not line segments) passing through these points including the diagonals. For example:

$M=2,N=2$: Number of lines $= 6$ (2 horizontal, 2 vertical, 2 diagonals)
$M=2,N=3$: Number of lines $= 11$ (2 horizontal, 3 vertical, 6 diagonals)
$M=3,N=3$: Number of lines $= 20$ (3 horizontal, 3 vertical, 14 diagonals)
$M=2,N=4$: Number of lines $= 18$ (2 horizontal, 4 vertical, 12 diagonals)
$M=3,N=4$: Number of lines $= 35$ (3 horizontal, 4 vertical, 28 diagonals)

Can someone help me in finding a general formula to find this?
Comment: By "lines" do you mean distinct lines that pass through at least two of the grid points? By "general formula" do you need a closed form, or will a recursive formula suffice?
Comment: Yes, distinct lines that passes through atleast 2 points and yes a recursive formula will be sufficient.
Answer: The horizontal and vertical lines are straightforward.  You get $M+N$ of those.
Let's take the lower left of the array at the origin so that the top row of points is at $y = M-1$ and the right column is at $x=N-1$.
Let's consider those diagonal lines that have positive slope, with one of the points being the origin.
We get a distinct diagonal for each pair $(x,y)$ for which $x$ and $y$ are relatively prime.  (The line through $(0,0)$ and $(1,2)$ coincides with the one through $(0,0)$ and $(2,4)$.)
For counting the multiplicity, let's consider counting the lines with slope $2/3$ in a $9 \times 11$ grid.
If we start at the origin, this line goes through $(3,2)$.  We can move along the $x$ axis until $(7,0)$, and after that we run out of points.  We can go up a row, start at $(0,1)$ and go over again to $(7,1)$.
But if we go up to the next row, we can only go over to $(2,2)$ before we start running into points that we've drawn lines through.
However, we can continue to go up the left side.  We only can go out to $x=2$ for the reason mentioned above.  We can continue up to $(2,7)$, and that's the last new line for this slope.
So the formula for the number of lines with a rise of $m$ and a run of $n$ in an $M \times N$ grid is
$$L(M,N,m,n) = (m+1)(N-n) + (n+1)(M-m) - (m+1)(n+1) - 2.$$
Then, the total number of all lines (vertical, horizontal, positive slope, negative slope) is
$$T(M,N) = M + N + 2 \sum_{n=1}^{N-1} \sum_{m=1}^{M-1} L(M,N,m,n) C(m,n),$$
where $C(m,n) = 1$ if $m,n$ are coprime, and $0$ if they're not.

Total number of lines in a 2D grid


How to create a histogram-like bar plot for my dataset?

Question: I have the following dataframe df:
time_diff   avg_trips_per_day
631         1.0
231         1.0
431         1.0
7031        1.0
17231       1.0
20000       20.0
21000       15.0
22000       10.0

I want to create a histogram with time_diff in X axis and avg_trips_per_day in Y axis in order to see the distribution of values of time_diff. So, Y axis is not the frequency of repetitions of X values in df, but it should be avg_trips_per_day.
The problem is that I don't know how to put time_diff into bins in order to handle it as a continuous variable.
This is what I try, but it puts all possible values of time_diff in X axis.
norm = plt.Normalize(df["avg_trips_per_day"].values.min(), df["avg_trips_per_day"].values.max())
colors = plt.cm.spring(norm(df["avg_trips_per_day"]))

plt.figure(figsize=(12,8))
ax = sns.barplot(x="time_diff", y="avg_trips_per_day", data=df, palette=colors)
plt.xticks(rotation='vertical', fontsize=12)
ax.grid(b=True, which='major', color='#d3d3d3', linewidth=1.0)
ax.grid(b=True, which='minor', color='#d3d3d3', linewidth=0.5)
plt.show()

Answer: import pandas as pd
import seaborn as sns
from io import StringIO
data = pd.read_table(StringIO("""time_diff  avg_trips_per_day
631         1.0
231         1.0
431         1.0
7031        1.0
17231       1.0
20000       20.0
21000       15.0
22000       10.0"""), delim_whitespace=True)
data['timegroup'] = pd.qcut(data['time_diff'], 3)
sns.barplot(x='timegroup', y='avg_trips_per_day', data=data)

Is this what you want?
Comment: Looks nice. Thanks.
Answer: As you explained yourself, you don't want a histogram, but a simple barplot. But from what I have understood you want to bin time_diff for the plotting.
The following should help you in binning your data and grouping by for the dataframe:
import pandas a pd

n_bins = 10
# bins indexed if want to use for x axis
x_bins = np.arange(n_bins)
# create bins
_, bins = pd.cut(df['time_diff'], bins=n_bins, retbins=True, right=False)
# regroup your data by computed bins indexes
binned_data = df['time_diff'].groupby(np.digitize(df['time_diff'], bins)).mean()

Comment: But how can I assign `binned_data` to `avg_trips_per_day`?


Segundo Like não funciona SQLIte

Question: Bom, ao fazer uma query:
        Cursor cursor = database.rawQuery("SELECT nome, imagem, descricao FROM Marcas WHERE descricao LIKE ? OR nome LIKE ?", new String[]{name});

Somente retorna resultados através da descrição, ou seja, o segundo like não é testado, ou não funciona. Não dá nenhum erro, só não retorna nada. Se eu tiro o segundo like funciona tanto por nome quanto por descricao. Mas o que preciso é pesquisar via nome e descrição.
Como resolver?
Answer: Entaum @genSkywalker que eu saiba, o "OR" funciona sim com "LIKE" no sqlite.
Você precisa montar sua query usando colunatbX LIKE '%string%' OR colunatbZ LIKE '%string%' ou algo do tipo.
Dai @Marcelowq, para resolver da melhor forma, tente fazer algo assin ó:
String ds = "'%"+tuaVarDesc+"%'";
String nm = "'%"+tuaVarNome+"%'";
String cmd = "SELECT nome, imagem, descricao FROM Marcas WHERE descricao LIKE "+ds+" OR nome LIKE "+nm;
Cursor cursor = database.rawQuery(cmd, null);

Lenbrando que na clausula LIKE do sql, o caracter "%" seguido de outro qualquer caracter não-extendido, representa uma sequencia de caracteres na consulta, ou seja, um curinga, assim, se voce usar '%string%', vai retornar qualquer coisa que contenha a palavra string em qualquer posição do texto.
como voce postou pouco código, ficamos sem saber o que vc já tem ai, mas isso resolveria pra voce.
com like eu testei aqui no sqlite e retornou o que eu quiz, em ambas as posições do meu LIKE.
Comment: Mas o que quero é passar uma string e pesquisar tanto em `nome` quanto em `descricao`. Essa string é um parâmetro de quando chama o método na pesquisa.
Comment: mas com isso o parametro passado para "rawquery(...)" faz exatamente isso, ou seja, pesquisa  pela palavra "string" em qualquer posição no campo descricao **OU** no campo nome.
Comment: Então, isso que eu tô dizendo. Quero fazer isso mas não tá dando certo. Mas a query tá certa, Executo ela no sqlite expert e funciona. Só no android que não.
Comment: pode postar mais codigo pra eu poder ter uma ideia mais clara?
Answer: Faltou mais um item "name" no array do segundo parâmetro do método rawQuery. Deveria ficar assim: new String[]{name, name}. Para cada "?" na string SQL do primeiro parâmetro, o método tenta pegar um item no array citado para substituir o "?" correspondente. Como você usa 2 "?", precisa de um Array com 2 items.

Segundo Like não funciona SQLIte


Interesting pattern in plot involving prime numbers

Question: If we plot $f(n) = \dfrac{n+1}{p_{n+1}} - \dfrac{n}{p_n}, n \in \mathbb{N} $, we get an interesting pattern.

Questions:

Why it looks like there's different lines on plot?

Why they have such shape?

How those lines can be approximated?

Why there's like peak at $n \approx 500$?

Why points in lines become sparcer as they are closer to the bottom?
Comment: Hint: observe prime gaps $p_{n+1}-p_{n}=g_n$.
Comment: @Peter When dealing with discrete functions, it is common to plot them like this, and throughout several years of working on Number Theory and Combinatorics, I have never seen anyone get that confusion.
Comment: Graphing this functions is rather confusing than helpful. The picture gives the (wrong) impression that $f(n)$ is not a function at all since there seem to be several distinct values for the same $n$.
Answer: As Vepir suggested in his comment, the curves correspond to consecutive primes with different prime gaps. The one on the top, for example, correspond to pairs of twin primes. That is $$\frac{n+1}{p_{n+1}}-\frac{n}{p_n} = \frac{n+1}{p_{n}+2}-\frac{n}{p_n}$$
The curves can be approximated using the known approximation for the $n$-th prime. For example, we know that $p_n \approx n\,(\log n + \log\log n -1)$.
Here's how it looks that approximation for the curve on the top.

The curves on the bottom corresponds to pairs of consecutive with larger prime gaps, that naturally occur less frequently.
Answer: Note that
$$f(n)={1\over p_{n+1}}-n\left({1\over p_n}-{1\over p_{n+1}}\right)={1\over p_{n+1}}-{ng_n\over p_np_{n+1}}\approx{1\over n\ln n+g_n}\left(1-{g_n\over\ln n}\right)$$
where $g_n=p_{n+1}-p_n$ and we've used the crude asymptotic approximation $p_n\approx n\ln n$. So very roughly, we are looking at the family of curves
$$f_k(x)={1\over x\ln x+2k}\left(1-{2k\over\ln x}\right)$$
with $k=1,2,3,\ldots$.  These curves behave qualitatively much like what the OP has observed; their quantitative disagreement -- the curve with $2k=6$ has a peak value of approximately $.00002$ at $x\approx873$, instead of $.00005$ near $500$ -- is due to the crudeness of the approximation $p_n\approx n\ln n$. Using the better approximation mentioned in jjagmath's answer, $p_n\approx n(\ln n+\ln\ln n-1)$, one gets a curve (for $2k=6$) with a peak of approximately $.00004$ at $x\approx431$, which comes closer to the OP's values.
In answer to the OP's final bullet-point question, the sparsity of the lower lines stems, heuristically, from the fact that large prime gaps (i.e., large values of $2k$) take a while to kick in and remain relatively rare among the first $10{,}000$ primes.


Difference between "crontab -e" & editing crontab file manually?

Question: I noticed some people use "crontab -l" to view cronjobs and "crontab -e" to edit them. However there are also times where people manually modify "/etc/crontab" to view/add/remove cronjobs.
Both methods work fine, the only thing I noticed is that cronjobs added with "crontab -e" doesn't show up inside "/etc/crontab" even though it still runs normally.
I'd like to know what are the differences between these 2 methods? Are there any advantages/disadvantages over each other?
PS. I'm on CentOS.
Answer: The normal per-user crontabs that you edit with crontab -e are located in /var/spool/cron.
/etc/crontab holds a "system-wide" crontab maintained by the system administrator.
There's typically also a /etc/cron.d directory where installed software can add entries.


Are cartesian coordinates "more fundamental" than other coordinates, and are they inherently tied to $\mathbb R^n$?

Question: Are the Cartesian coordinates more "fundamental" than other coordinate systems?  When someone says $\mathbb R^n$ do we implicitly mean the set of points PLUS Cartesian coordinate system?  Sometimes I read "Cartesian space" for $\mathbb R^n$, but of course nobody is calling $\mathbb R^n$ "polar space" (You can see this in the Euclidean space wikipedia page).
This example seems to suggest to me that Cartesian coordinates are the "default" system on $\mathbb R^n$:
If you have a constant function $f=1$ from a subset $S$ of $\mathbb R^n$ into $\mathbb R$, and you do $\iint_{S}{1 \cdot dA}$, that is interpreted as the volume of a box with base area $S$ and height $1$.  This assumes that $S \subset \mathbb R^2$ is in Cartesian coordinates.
Another thing that suggests that Cartesian coordinates are more fundamental:
$\mathbb R^2$ is the "Cartesian product" of $\mathbb R$ with itself.
Comment: The standard basis is merely a convenient choice of basis where the vectors are mutually perpendicular. Any other choice is equivalent to this one (in most situations) by a change of basis. It just makes life easier for the person reading literature.
Comment: When I define $\mathbb{R}^n$ it implicitly includes the cartesian coordinate system as the identity map. Thus, yes, they are preferred in this sense. On the other hand, once that choice is made there are infinitely many other such coordinate systems. From a model-building perspective, yes we can place them where is most convenient. Sometimes, $\mathbb{E}^n$ will be used to denote $n$-dimensional euclidean space since you might want the point-set $\mathbb{R}^n$ to have some other inner product than the standard dot-product. It really depends what you're reading.
Comment: @user93788 Yes, and $\int_a^b f(\theta)\,\mathrm d\theta$ is the area associated with $r=f(\theta)$ on the Cartesian [rather than](https://math.stackexchange.com/a/4676843/21813) the polar plane.
Answer: When I see a notation like $\mathbb{R}^2$ or $\mathbb{R} \times \mathbb{R}$, I tend to think of this as indicating an object considered as coming equipped with projection or coordinate functions $\pi_1: \mathbb{R}^2 \to \mathbb{R}$, $\pi_2: \mathbb{R}^2 \to \mathbb{R}$ which assign to each element of the domain a first and second coordinate. With regard to comments made under the question, note that any choice of linear basis of a 2-dimensional vector space $V$ can be used to produce such a suitable pair of projection functions (giving coordinates with respect to that basis), and one can go on to consider extra structure such as an inner product that makes those basis elements orthonormal elements, etc., so that one effectively derives a cartesian coordinate structure on $V$.
The polar coordinate system is an entirely different creature, being based on a pair of maps $\mathbb{R}^2 \to \mathbb{R}_+$, $\mathbb{R}^2 \to \{angles\}$ that is not inherent in the notation (it's not even well-defined at the origin, or at least not so in any continuous way). In brief, I would say that unless the author explicitly declares some alternative coordinate system, you should think of cartesian coordinate systems (in the sense discussed above) as the default inherent within the very notation.


Basis and dimensions of vector spaces

Question: Basically I know how to determine the basis and dimension of a real vector space or subspace, but I need to know how can I determine the basis and dimension of a complex subspace as Complex and as Real. Example:
Let $V=\{( z,t )\in \mathbb{C} |t-4z=z-t \}$.
Determine the Bases and Dimension of $V$ on $\mathbb{C}$ and on $\mathbb{R}$. And how can I write the answer in the right way?
Thanks in advance.
Comment: The dimension over $\Bbb R$ will be twice that over $\Bbb C$
Comment: $\{1,i\}$ is a basis for $\mathbb C$ over $\mathbb R$
Comment: How would you determine the basis if it said $(z,t)\in\Bbb R$?
Comment: @J.W.Tanner in this case the base of V= span {(5/2 , 1)} with dim(v)=1
Comment: same for $\Bbb C$
Comment: @J.W.Tanner i multipli it by ( 1,i ) so i obtain basis over real numbers, isn't ?
Comment: Essentially yes
Answer: You have the linear equation t- 4z= z- t (and it is to be understood that z and t are complex numbers).  That can easily be written as 2t= 5z.  Taking that common value to be "k", we can write (t, z)= (k/2, k/5). And since a vector space is closed under multiplication by scalars, 10(k/2, k/5)= (5k, 2k)= k(5, 2) is in the space for all k and every member of this space is equal to k(5, 2) for some k.  That is, with k any complex number, {(5, 2)} is a basis for the space and the dimension, over the complex numbers, is 1.
Since we can write k= a+ bi, with a and b real numbers, k(5, 2)= (a+ bi)(5, 2)= a(5, 2)+ b(5i, 2i).  As a vector space over the real numbers, a basis is {(5, 2), (5i, 2i)} and the dimension is 2.

Basis and dimensions of vector spaces


Devo usar dois IF's ou um operador?

Question: Qual a melhor prática para verificar duas condições?
No exemplo que vou dar, não são verificações muito longas mas qual a melhor prática e qual é a diferença? (aconteceu comigo que dei por mim tendo um if enorme então decidi setorizar e dividir em vários ifs. Isso é correto?
Exemplo:
if ( A > X AND  A > Y)
    instrucao aqui....
ENDIF

Ou:
if ( A > X )
    if ( A > Y)
         instrucao aqui....
    ENDIF
ENDIF

Answer: O funcionamento das duas são diferentes, porém ambas devem funcionar.
if ( A > X AND  A > Y)
  instrucao aqui....
ENDIF

Nesse caso dependendo da linguagem ela irá otimizar a verificação consumindo menos ciclos de clocks.
if ( A > X )
   if ( A > Y)
     instrucao aqui....
   ENDIF
ENDIF

Neste outro caso ele ira verificar o primeiro entrar dentro do if e verificar o segundo. Se for uma linguagem compilada a árvore sintática será mais complexa gastando mais ciclos de clock.
Claro tudo depende da linguagem e como a mesma funciona.
No geral as duas são equivalentes ao nível de lógica, porém não a nível de execução.
Answer: Nesse exemplo específico e só nele (se tiver uma outra forma pode não valer) costuma ser mais vantajoso fazer o primeiro, por uma razão simples: é mais simples.
Alguns até podem questionar se é realmente mais simples. Eu considero simplicidade, dentro do conhecimento que todo programador deve ter, e o uso do AND é necessário. Se a pessoa não o entende, pode até achar a segunda forma mais simples, mas aí é por desconhecimento.
Há controvérsias, mas para mim, mais simples é menos linhas. O código se torna mais legível quando escreve menos. Claro, não quer dizer que amontoar seja mais legível, mas colocar menos linhas dispensáveis pode se tornar mais legível. Já vi pessoas dizendo que se separar mais as coisas fica mais legível, mas se isso fosse verdade ela programaria em linguagem de alto nível quase como se fosse Assembly onde cada linha é uma única instrução.
Se tiver muitos operadores relacionais na condição pode separar em várias linhas, mas manter um único comando if, ainda será mais interessante.
Mas na verdade acaba sendo gosto, novamente, neste caso específico. O mais importante é ser consistente, porque é horrível ver um código que muda a forma de escrever, como ocorreu neste código.
Comment: obrigado. nesse caso mesmo as condicoes/verificações eram pequenas mas eu me deparei com condições/verificações bem grandes daí ter surgido a dúvida.
Answer: As duas verificação são válidas, porém caso haja a necessidade de dividir um if em dois o melhor é abstrair em uma função.
Caso a verificação seja simples:
if( A< X || B < X )
    instrução....
endif

Porém caso seja uma validação complexa:
if(valido(parametros))
    instrução...
endif

function valido(parametros)
    validação complexa...
endfunction

isso ajuda muito na manutenção do código, pois um desenvolvedor não precisa ler toda a validação sempre que for alterar algo nessa instrução. apenas saber que ali existe uma validação, e caso seja necessário consultar a validação é só ler a função responsável por isso.
Answer: Em geral, acredito que seja mais fácil realizar a leitura de um único if ao invés de um ou mais deles.
Veja alguns cenários para compararmos as duas opções.
Muitas condições
Pensando em casos com mais ifs, verá que isto:
if ( A > X AND  A > Y AND A > Z)
    instrucao aqui....
ENDIF

Acaba sendo mais simples de entender que:
if ( A > X )
    if ( A > Y)
        if ( A > Z)
            instrucao aqui....
        ENDIF
    ENDIF
ENDIF

Extrair método
Usando um único if, você pode simplificar o significado das condições criando um único método, o que não é possível com um if dentro de outro if.
Como exemplo:
if ( A > X AND  A > Y)
    instrucao aqui....
ENDIF

Você poderia ter um método isAMaiorQueYeX(A, X, Y), dando um nome explicativo para a condição:
if ( isAMaiorQueYeX(A, X, Y))
    instrucao aqui....
ENDIF

Para casos de condição mais complexos, este tipo de artifício fica cada vez mais útil.
Depuração de código e erros
Uma pequena vantagem que existe usando um único if é na depuração de problemas. Caso ocorra um erro de "NullPointer" ou algo parecido, a linha apontada no erro dará direto na condição problemática. Agora, usando várias condições na mesma linha, você não terá certeza de qual condição causou o problema e terá que depurar a aplicação para entender.
E falando em depuração, ela também é facilitada com vários ifs. Como a depuração é feita linha por linha, fica um pouco mais fácil observar o que está acontecendo no código.

Devo usar dois IF's ou um operador?


Facing difficulty in creating Request Object in Front End Java Spring MVC, need to replicate following .NET-MVC code into java

Question: I am developing a front end application using Java Spring-MVC, however I'm facing difficulties in creating Request Object for Hitting Web-Services as I did in .Net-MVC. Can anyone tell me the equivalent classes and methods  in Java for below given code.
I need to replicate these 2 methods from .Net-MVC to Java.
1st Method:
    private HttpWebRequest RequestObj { get; set; }
    public Stream DataStreamObj { get; set; }
    private RequestModel RequestModelObj { get; set;

    public RequestGenerator(String WebserviceUrl)
    {
        RequestObj = (HttpWebRequest)WebRequest.Create(WebConfigurationManager.AppSettings["WebServiceURL"] + WebserviceUrl);
        RequestObj.Method = "POST";GenerateLoginRequest
        RequestObj.ContentType = "application/json";

        RequestModelObj = new RequestModel();
        RequestModelObj.ApiKey = WebConfigurationManager.AppSettings["apiKey"];
        RequestModelObj.DeviceId = Constant.AppConstants.ONE;

    }

2nd Method:
    private string CallWebservice(Dictionary<String, Object> RequestDict)
    {
        try
        {
        HttpWebRequest Request = (HttpWebRequest)RequestDict["request"];
            RequestModel RequestModel = (RequestModel)RequestDict["requestData"];

            //Tell them the length of content
            string Json = JsonConvert.SerializeObject(RequestModel);
            byte[] ByteArray = Encoding.UTF8.GetBytes(Json);

            Request.ContentLength = ByteArray.Length;

            //Write content on stream
            Stream DataStream = Request.GetRequestStream();
            DataStream.Write(ByteArray, 0, ByteArray.Length);
            DataStream.Close();

            //Initiate Call
            HttpWebResponse Response = GetWebResponse(Request);
            DataStream = Response.GetResponseStream();

            StreamReader Reader = new StreamReader(DataStream);
            // Read the content.
            string responseFromServer = Reader.ReadToEnd();
            // Display the content.

            Reader.Close();
            Response.Close();
            return responseFromServer;
        }
        catch (System.Net.WebException ex)
        {
            var response = ex.Response as HttpWebResponse;
            return "";

        }
    }

Answer: RestTemplate class is designed to call REST services, it should come as no surprise that its main methods are closely tied to REST's underpinnings, which are the HTTP protocol's methods: HEAD, GET, POST, PUT, DELETE, and OPTIONS. E.g. it's methods are headForHeaders(), getForObject(), postForObject(), put() and delete() etc.
Read More and Source Code : Spring REST JSON Example
HTTP GET Method Example
1) Get XML representation of employees collection in String format
REST API Code
@RequestMapping(value = "/employees", produces =
MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)
public String getAllEmployeesXML(Model model)
{
model.addAttribute("employees", getEmployeesCollection());
return "xmlTemplate";
}

REST Client Code
private static void getEmployees()
{
final String uri =
"http://localhost:8080/springrestexample/employees.xml";

RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);

System.out.println(result);
}

2) Get JSON representation of employees collection in String format
REST API Code
@RequestMapping(value = "/employees", produces =
MediaType.APPLICATION_JSON_VALUE,  method = RequestMethod.GET)
public String getAllEmployeesJSON(Model model)
{
model.addAttribute("employees", getEmployeesCollection());
return "jsonTemplate";
}

REST Client Code
private static void getEmployees()
{
final String uri =
"http://localhost:8080/springrestexample/employees.json";

RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);

System.out.println(result);
}

3) Using custom HTTP Headers with RestTemplate
REST API Code
@RequestMapping(value = "/employees", produces =
MediaType.APPLICATION_JSON_VALUE,  method = RequestMethod.GET)
public String getAllEmployeesJSON(Model model)
{
model.addAttribute("employees", getEmployeesCollection());
return "jsonTemplate";
}

REST Client Code
private static void getEmployees()
{
final String uri = "http://localhost:8080/springrestexample/employees";

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters",
headers);

ResponseEntity<String> result = restTemplate.exchange(uri,
HttpMethod.GET, entity, String.class);

System.out.println(result);
}

4) Get data as mapped object
REST API Code
@RequestMapping(value = "/employees", produces =
MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)
public String getAllEmployeesXML(Model model)
{
model.addAttribute("employees", getEmployeesCollection());
return "xmlTemplate";
}

REST Client Code
private static void getEmployees()
{
final String uri = "http://localhost:8080/springrestexample/employees";
RestTemplate restTemplate = new RestTemplate();

EmployeeListVO result = restTemplate.getForObject(uri,
EmployeeListVO.class);

System.out.println(result);

}
5) Passing parameters in URL
REST API Code
@RequestMapping(value = "/employees/{id}")
public ResponseEntity<EmployeeVO> getEmployeeById (@PathVariable("id")
int id)
{
if (id <= 3) {
    EmployeeVO employee = new
EmployeeVO(1,"Lokesh","Gupta","firstname.lastname@example.com");
    return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK);
}
return new ResponseEntity(HttpStatus.NOT_FOUND);
}

REST Client Code
private static void getEmployeeById()
{
final String uri =
"http://localhost:8080/springrestexample/employees/{id}";

Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");

RestTemplate restTemplate = new RestTemplate();
EmployeeVO result = restTemplate.getForObject(uri, EmployeeVO.class,
params);

System.out.println(result);
}

HTTP POST Method Example
REST API Code
@RequestMapping(value = "/employees", method = RequestMethod.POST)
public ResponseEntity<String> createEmployee(@RequestBody EmployeeVO
employee)
{
System.out.println(employee);
return new ResponseEntity(HttpStatus.CREATED);
}

REST Client Code
private static void createEmployee()
{
final String uri = "http://localhost:8080/springrestexample/employees";

EmployeeVO newEmployee = new EmployeeVO(-1, "Adam", "Gilly",
"email@example.com");

RestTemplate restTemplate = new RestTemplate();
EmployeeVO result = restTemplate.postForObject( uri, newEmployee,
EmployeeVO.class);

System.out.println(result);
}

HTTP PUT Method Example
REST API Code
@RequestMapping(value = "/employees/{id}", method = RequestMethod.PUT)
public ResponseEntity<EmployeeVO> updateEmployee(@PathVariable("id")
int id, @RequestBody EmployeeVO employee)
{
System.out.println(id);
System.out.println(employee);
return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK);
}

REST Client Code
private static void deleteEmployee()
{
final String uri =
"http://localhost:8080/springrestexample/employees/{id}";

Map<String, String> params = new HashMap<String, String>();
params.put("id", "2");

EmployeeVO updatedEmployee = new EmployeeVO(2, "New Name", "Gilly",
"email@example.com");

RestTemplate restTemplate = new RestTemplate();
restTemplate.put ( uri, updatedEmployee, params);
}

HTTP DELETE Method Example
REST API Code
@RequestMapping(value = "/employees/{id}", method =
RequestMethod.DELETE)
public ResponseEntity<String> updateEmployee(@PathVariable("id") int
id)
{
System.out.println(id);
return new ResponseEntity(HttpStatus.OK);
}

REST Client Code
private static void deleteEmployee()
{
final String uri =
"http://localhost:8080/springrestexample/employees/{id}";

Map<String, String> params = new HashMap<String, String>();
params.put("id", "2");

RestTemplate restTemplate = new RestTemplate();
restTemplate.delete ( uri,  params );
}


Probability of completing a task along certain path in a certain time using beta distribution

Question: I have 5 different tasks and the duration of each task in the network are assumed to be beta distributed and I have their beta parameters (p, q, a, b) for each task. These durations are assumed to be independent of each other.
How do I find the probability of completing the first 3 tasks in a certain time?
Any help would be appreciated!
Comment: Why do your beta distributions have 4 parameters? The beta distributions I know have only 2 parameters, see: https://en.wikipedia.org/wiki/Beta_distribution
Comment: @Maarten The answer to your question is right in the link you gave! click your link and look in the contents under section 3 and [section 7](https://en.wikipedia.org/wiki/Beta_distribution#Four_parameters_2) (though the first actual mention of the four parameter case is in section 2; it just doesn't appear in the contents for section 2; sect 7 will be the most directly relevant)
Comment: @DML are these tasks sequential? Or are they being performed in parallel?
Comment: If the tasks are sequential, is the sequence (the order) always the same? Is is randomly chosen 3 out of 5 or always the same 3? Is simulation an acceptable answer for the problem?
Comment: @Glen_b they are sequential.
Comment: @Bernhard they are sequential and the order is always the same, task 1 then task 2 and finally task 3. Any yes simulation would be an acceptable answer. Thanks in advance!
Answer: If you add a lot of beta distributed variables, the sum will eventually follow a normal distribution. But tree will not be enough to go that route.
If the parameters of the beta distributions are given, then it is very easy to set up a computer simulation of the sum of three such distributions.
In R that would be:
# let a to f be the parameters of the beta distributions be know. We assume some random values
a <- 5; b <- 3; c <- 10; d <- 2; e <- 5; f <- 8
n <- 100000

# we draw n triples of beta values and sum them
sum_of_betas <- rbeta(n, a, b) + rbeta(n, c, d) + rbeta(n, e, f)

# Plot histogram of the resulting sums:
hist(sum_of_betas)

# To compute the share of sums that are below 1.5 we can then do
sum(sum_of_betas < 1.5)/n

This is simulation, not a closed form solution. The advantage of this is, that it can easily be adjusted to more complicated situations, if needed.
Edit
Answering the comment: The simulation is based on $n$ replicates. So if you look for small probabilities, you might want to increase $n$ so large, that the simulation output is very similar each time you run the simulation.
In addition to what I coded above, you want beta distributions that do not only range from 0 to 1 but have two more parameters, giving the minimum and the maximum of the distribution. I therefore added variables named minA and minBand so on for the additional parameters. The code then becomes:
# let a to f be the shape parameters of the beta distributions be know. We assume some random values
a <- 5; b <- 3; c <- 10; d <- 2; e <- 5; f <- 8
# let minA to min C be the minimum and maxA to maxC be the maximal values of each beta distr.
minA <- 0; minB <- 1; minC <- 3; maxA <- 1; maxB <- 2; maxC <- 6
# number of random triples is n
n <- 1000000

# we draw n triples of beta values and sum them
sum_of_betas <- minA + (maxA-minA)*rbeta(n, a, b)+
                minB + (maxB-minB)*rbeta(n, c, d) +
                minC + (maxC-minC)*rbeta(n, e, f)

# Plot histogram of the resulting sums:
hist(sum_of_betas)

# To compute the share of sums that are below 7 we can then do
sum(sum_of_betas < 7)/n

Comment: Thanks for your answer but I'm a bit confused, what does n refer to? And what are these a to f in terms of the beta parameters (p, q, a, b)?
Comment: Just as @Marten Buis in his comment above, I am used to beta distributions being defined by two shape parameters and values between 0 and 1. You habe two additional parameters for the lower and upper limit which is just a linear transformation. I edited my answer to give code for that. `n` is the number of random value triples drawn for the simulation. Increase `n` if you need more precision, decrease it, if you need more speed for the computation.


Prove that this group is an abelian group

Question: I'm trying to prove this but can't find the way.

What I think about is this: "We want to prove that $ab=ba$, i.e. if $aa=e$ , $a=a'$ where $a'$ is the inverse and $bb=e$, $b=b'$ where $b'$ is the inverse so $ab=(ab)'=b'a'=ba...$ but this is by definition. I can't reach the point how does it changes based on prime numbers.
Any help would be really appreciated.
Comment: Yikes. That exercise is badly written. Also for future reference, please type your question using MathJax rather than insert an image, to prevent issues like broken links from cropping up in the future. Additionally you'll get a better response if you show what you've tried. MathJax help located here: https://math.meta.stackexchange.com/q/5020/90543
Comment: You have not asked the question properly.
Comment: What is $n$ and what is $\otimes_p$?
Comment: Can restate the question ?
Answer: For prime $p$, $\mathbb Z_p^×$ is cyclic...  ($\therefore$ abelian)
It is also written $\mathbb Z_p^*$, since it is the multiplicative group of nonzero elements of the field $\mathbb Z_p$
In fact, $\mathbb Z_n^×$(the multiplicative group of units in $\mathbb Z_n$) is cyclic for $n=1,2,4$, a power of an odd prime or twice a power of an odd prime...  (as Gauss knew, i believe...)


Breathing when singing (inhalation timing)

Question: I noticed a possibly major detail when listening to some tracks. That is, when a singer breathes in for the next phrase, they do it almost immediately before that phrase.
For example, they would:

Finish a phrase
Pause for 1-2 seconds
Immediately breathe in prior to starting the next phrase

Well, what I tend to do is flip 2 and 3. I wouldn't necessarily say that I'm holding my breath since it's very brief, and I tend to inhale immediately after the phrase to catch my breath instead of holding out for 1-2 seconds. But why do professionals singers do this? Does it make for a consistent tone when not exhausting your breath at the end of a phrase? And Does it add more punch to the following phrase when breathing in right before?
Also, what exactly happens between steps 1 and 2? Are they still exhaling very slowly even after the phrase, or is there no breathing whatsoever?
Comment: Do you actually mean 1-2 seconds, or just a noticeable moment? Because 1-2 seconds is really long time to pause between measures. Often, a full measure will take less than 2 seconds to play, and sometimes less than 1.
Comment: Ah that's my fault. I probably shouldn't have used the word "measure". I meant to use it in a more general way that's not necessarily a musical measure.
Comment: Smooth exhale typically makes a tone easier to sustain
Answer: Standard technique is "breathe, sing" with no hold stage.  Plenty of times you won't have much of a gap, which is why singers practice quickly getting air right to the bottom of their lungs with deep diaphragm-controlled breathing, without gasping, raising their shoulders or other bad habits.  Where there's a longer gap in the music, you can have the luxury of a slower deep breath.  In an even longer gap, "normal" breathing can take over of course.
You've got the idea that there's a technique to breathing to sing.  Good!  I suggest you now book a session with a singing coach
Comment: Thanks for the insight! I guess there is some inaudible release at the end of a phrase then. You raise an interesting topic though. I think that a _subtle_ raise in shoulders or gasping is inevitable to achieve optimal breath support all the while using the diaphragm as the driving force. Alongside, some singers even breathe in with their nose for efficiency. I'm inclined to believe those factors are taught as bad habits for the sake of teaching beginners. What's your thought on this?
Comment: We're not talking about support yet, we're talking about getting breath IN.  The chest, particularly the lower chest expands, the shoulders are relaxed - they come down if anything, certainly not up.  Then the air's somewhere where the diaphragm can do something with it!  A gasp is a shallow breath, into the top of the lungs.  It's no use to a singer.
Don't look for excuses for your bad habits.  Get someone to show you how to do it properly.
Comment: Actually, I started with a pure diaphragmatic inhalation prior to seeking a teacher. He said that such technique is a drill. A means of achieving a good foundation for breath support. Not something that should be used literally in practice. But most of all it's unnatural to breathe purely with the diaphragm. A copious amount of air at the bottom of the lungs is good, we'd both agree. But why limit to just the bottom? Even the air at the top can be useful as long as the force driving is from the diaphragm.
Comment: Ever tried filling the bottom of the lungs WITHOUT filling the top?  :-)
But there's a lot of symbolism in singing tuition.  "Make the sound come from your stomach" or even "Sing through your forehead" are physically pretty meaningless.  But they can help.  I don't think you'll find a teacher who lets you raise the shoulders though.
Comment: I don't think we're on the same page. My point is similar to that of filling an empty cup with water. We're both filling the bottom half just fine. But I'm just trying to add a bit more. At this point, my shoulders ever so slightly raises. This extra air isn't always necessary, but it really helps when singing in the passagio area where there is more compression in the vocal cords.


WDS Not Offering Capture Image

Question: I have installed WDS and added boot and capture images.
I have a server I am trying to capture, however when I do the network boot, I can see WDS and it loads the boot.wim file instead of the capture.wim.Images in WDS
I was expecting to see a screen such as this: Boot Screen but I don't and it boots straight into the first image.
Does anyone have any suggestions?
Answer: I have solved this now. It appears as if the .wim file may have become slightly corrupted.
I used DISM to mount then unmount the file and can now boot into it.

WDS Not Offering Capture Image


Semantic error in Python. Mathematical mistake

Question: I am trying to write a program in Python to calculate the area of a polygon. The formula is :
area = n * s * a / 2
a = s / 2 * tan(pi/n)

My code is:
import math

def area(s,n):
    a = s/(2* math.tan((math.pi/n)))
    b = (n*s*a)/2
    return b

The problem is that it calculates a total different thing. For example: area (2,5) = 3.63, when it is really 6.887.
Does anyone see a mistake?
Comment: Does it help to use 2.0 instead of 2?
Answer: import math

def area(s,n):
    a = s/(2* math.tan((math.pi/n)))
    b = (n*s*a)/2
    return b

area(2, 5)
#>>> 6.881909602355868

def area(s,n):
    a = s/2* math.tan((math.pi/n))
    b = (n*s*a)/2
    return b

area(2, 5)
#>>> 3.6327126400268046

Really though, don't use single letter names. Making things unreadable does nobody any good.
If your mathematics doesn't make semantic sense, rewrite it so that it does. Your confusion is a testament to this.


how to get the default value for a multivalue field

Question: I'm using the Mulitvalue Field module (https://www.drupal.org/project/multivaluefield)
and I created a form like this and it successfully sets the various emails into the configuration file, but when i try to get the default value it, gets an array back.  how do i get the default value for this multivalue field to display it in the form?
<code>$form['comment']['comment_admin_notify_mailto'] = array(
  '#type' => 'multivalue',
  '#title' => $this->t('Comments Topics And Post Approvers'),
  '#cardinality' => MultiValue::CARDINALITY_UNLIMITED,
  'comment_admin_notify_mailto' => [
    '#type' => 'textfield',
    '#title' => $this->t('Person to send notifications for Comments, Topics and Posts'),
    '#default_value' =>  vista_moderation_admin_notify_variable_get_site_email(),
  ],
);
</code>
this is the function code:
<code>function vista_moderation_admin_notify_variable_get_site_email() {

  $moderation_config = \Drupal::config('vista_moderation_admin_notify.settings');
  $site_mail = $moderation_config->get('comment_admin_notify_mailto');
  if (empty($site_mail)) {
    $site_config = \Drupal::config('system.site');
    $site_mail = $site_config->get('mail');
  }
  return $site_mail;
</code>
Answer: i found the answer in the comments of the module which is the documentation :
<code> /**
   * Sets the default value for the child elements.
   *
   * @param array $elements
   *   The elements array.
   * @param array $value
   *   An array of values, keyed by the children element name.
   */
  public static function setDefaultValue(array &$elements, array $value): void {
    // @todo Handle nested elements.
    foreach (Element::children($elements, FALSE) as $child) {
      if (isset($value[$child])) {
        $elements[$child]['#default_value'] = $value[$child];
      }
    }
  }
</code>


Whether my understanding of the Central Limit Theorem is a correct way to look at the idea? + a few small questions

Question: For the last while I've been attempting to truly understand what is being said by the Central Limit Theorem.  I get the general idea, but there are still one or two details that are troubling. To make sure my thinking is correct, I'm going to explain my interpretation of the CLT. At the end I'll ask my questions.
The version of the CLT I'm working with comes from Mathematical Statistics and Data Analysis 3rd ed by Rice. Before stating the theorem the following definition is given

Let $X_{1}, X_{2}, \dots$ be a sequence of random variables with cumulative distribution functions $F_{1}, F_{2}, \dots$ and let $X$ be a random variable with distribution function $F$. We say that $X_{n}$ converges in distribution to $X$ if $$\lim_{n \to \infty} F_{n}(x) = F(x)$$ at every point at which $F$ is continuous.

With that here is the form of the theorem I'm using:

Central Limit Thm:
Let $X_{1}, X_{2}, \dots$ be a sequence of independent random variables having mean $\mu$ and variance $\sigma^{2}$ and the common distribution function $F$ and moment generating function $M$ defined in a neighbourhood of zero. Let $$S_{n} = \frac{1}{n}\sum_{i = 1}^{n}X_{i}$$ Then $$\lim_{n \to \infty} P \bigg(\frac{S_{n} - \mu}{\sigma/ \sqrt{n}} \leq x \bigg) = \Phi(x)\ -\infty < x < \infty$$
where $\Phi(x)$ is the standard normal distribution.

For my purposes the existence of the moment generation function is not important because I'm just attempting to understand the theorem and not prove things here. I should also mention I'm finishing up Spivak's Calculus so some of the ideas in my explanation come from that.
My Thought Process of What's Happening:
We are given a sequence of random variables $X_{1}, X_{2}, \dots$, we are not sure if this sequence of random variables converges or not, one thing we are interested in is if their partial sums eventually converge to a term. The partial sums were defined by:
$$S_{n} = \frac{1}{n}\sum_{i = 1}^{n}X_{i}$$
These partial sums, $S_{n}$ can be seen as a sequence in themselves and they are also random variables as they are a function of the $X_{i}$. The Law of Large Numbers shows that this sequence converges to $\mu$. That is:
$$\lim_{n \to \infty}S_{n} = \lim_{n \to \infty}\bigg(\sum_{i = 1}^{n}X_{i}\bigg) = \mu$$
From this we ask how do the values of our sequence of random variables, $S_{n}$ (question 1) fluctuate around the value $\mu$?
To determine this we standardize our random variables, $S_{n}$:
$$Z_{n} = \frac{S_{n} - \mu}{\sigma/\sqrt{n}}$$
This again is a sequence of random variables, which are a function of the random variables, $S_{n}$. We know that $\lim_{n \to \infty}S_{n} \to \mu$. By calculus since $Z_{n}$ is continuous this means
$$ Z_{1}(S_{1}), Z_{2}(S_{2}),Z_{3}(S_{3}), \dots  \to Z(\mu)\ \textbf{question 2}$$
The CLT is discussing probability, in other words it expresses the probability of a realization of random variable occurring. This is where the cumulative distribution functions come into play.  So given a sequence of distribution functions  $F_{1}, F_{2}, \dots$ and a distribution function $F$ what I'm envisioning occurring based on the convergence of the $Z_{n}$ is:
$$\begin{array}
F_{1}(Z_{1}) & F_{1}(Z_{2}) & \dots & \to & F_{1}(Z) \\
F_{2}(Z_{1}) & F_{2}(Z_{2}) & \dots & \to & F_{2}(Z) \\
\vdots & \vdots & \dots & \to & \vdots \\
F(Z_{1}) & F(Z_{2}) & \dots & \to & F(Z)
\end{array}$$
The reason for this is because the $F_{i}$ are continuous functions and by calculus properties, if $Z_{n} \to Z$ then $F(Z_{n}) \to F(Z)$. Now the value that $F(Z)$ at the end of the convergence will take on is $\Phi(x)$. Thus:
$$\lim_{n \to \infty} P \bigg(\frac{S_{n} - \mu}{\sigma/ \sqrt{n}} \leq x \bigg) = \lim_{n \to \infty} F_{n}(Z) =  \Phi(x)$$
My questions

(Marked as question 1 in the write up): I wrote $S_{n}$, but are we looking at the behaviour of $X_{i}$ or the behaviour of $S_{n}$ around $\mu$?

This has to do with $\lim_{n \to \infty}Z_{n}$. Since we know by the Law of Large Numbers that $\lim_{n \to \infty}S_{n} = \mu$, wouldn't that mean that $\lim_{n \to \infty}Z_{n} = 0$ all the time?

The CLT revolves around the behaviour of the random variables around $\mu$. To this end I can "see" the idea of since my $X_{i}$ are random variables, in turn the $S_{n}$ should also be random values, but again since we are taking things to the limit we end back up at the constant value of $\mu$. What am I missing in my understanding of this process?

Did I explain the ideas relatively correct?

EDIT: Based off of the discussion I've been having with @apprentice, the following is another way to frame my issues:
Based off a simple example of what the CLT is doing. Say we have a population, we take a sample from the population, take its average and plot it on a graph. We repeat this process over many times and by the end of it, based on the CLT the distribution of those mean values will be normally distributed. So now I'm trying to take that idea and translate it to the technical jargon used to define the CLT rigourously.
Comment: For first question, yes it is the value of $S_n$ , the average, is consistent estimator of $\mu$. So it's value fluctuate around $\mu$. For the second question, you have to look the theorem called *Berry–Esseen theorem*, this theorem talk about the rate of convergence, and that is here $n^{-0.5}$.
Comment: @annie_lee...I see. I wasn't trying to get bogged down by the advance theory involved in the development of the CLT just yet. I just wanted the foundation  of the idea to be clear first.
Comment: I'm just talking about the rate of convergence, you can think of for real sequence also, rate convergence matter here to get the limit.
Comment: @annie_lee, I don't know if this is the right way to think about it, but in you talking of rates of convergence is the notion similar to how we define the derivative in calculus as being $\lim_{h to 0}\frac{f(a + h) - f(a)}{h}$?  As in the numerator is converging faster than the denominator?
Comment: maybe, if derivatives diverge then your claim is true, if not then converges to a finite value
Answer: Let's try to gain some intuition for the CLT by applying the Fourier transform.
Let $X_1$ and $X_2$ be independent random variables with density functions $f_{X_1}$ and $f_{X_2}$, respectively. Then, the density function of $X_1 + X_2$ is given by $f_{X_1} * f_{X_2}$, where $*$ denotes convolution. To see this,
\begin{align}
\mathbb{P}(X_1 + X_2 \leq t) &= \iint\limits_{\{x_1 + x_2 \leq t\}} f_{X_1,X_2}(x_1,x_2)dx_1dx_2 \\
&= \iint\limits_{\{x_1 + x_2 \leq t\}} f_{X_1}(x_1)f_{X_2}(x_2)dx_1dx_2 \\
&= \int_{-\infty}^{\infty}\int_{-\infty}^{t}f_{X_1}(u)f_{X_2}(v-u)dvdu \\
&= \int_{-\infty}^{t}\bigg(\int_{-\infty}^{\infty}f_{X_1}(u)f_{X_2}(v-u)du\bigg)dv \\
&= \int_{-\infty}^{t}(f_{X_1} * f_{X_2})(v)dv
\end{align}
where in the second line we used the fact that $X_1$ and $X_2$ are independent and in the third line we made the substitutions $X_1 = U$ and $X_2 = V - U$ (the determinant of the Jacobian is equal to one in this case). By induction, the above result holds for any number of independent random variables --- that is, the density function of $X_1 + \cdots + X_n$ is given by $f_{X_1} * \cdots * f_{X_n}$. Hence, we have linked the sum of independent random variables to convolution.
Now, let $X_1, \dots, X_n$ be independent and identically distributed random variables with common density function, $f_X$, and assume that $\mathbb{E}[X] = 0$ and $\mathbb{V}[X] = 1$ --- that is, normalize the random variables to have mean zero and variance one. Let $S_n = \sqrt{n}^{-1}(X_1 + \cdots + X_n)$ and let $f_{S_n}$ denote the density function of $S_n$. We know from above (plus a technicality due to the fact that the sum is scaled) that $f_{S_n}(x) = \sqrt{n}(f_X * \cdots * f_X)(\sqrt{n}x)$ --- that is, $f_{S_n}$ is a scaled convolution of $f_X$ with itself $n$ times.
We now recall that the Fourier transform turns convolution into multiplication! Let's take the Fourier transform of $f_{S_n}$.
\begin{align}
\mathcal{F}f_{S_n}(s) &= \mathcal{F}(\sqrt{n}(f_X * \cdots * f_X)(\sqrt{n}x))(s) \\
&= \sqrt{n} \cdot \frac{1}{\sqrt{n}} \cdot \mathcal{F}f_X * \cdots * f_X\bigg(\frac{s}{\sqrt{n}}\bigg) \\
&= \bigg(\mathcal{F}f_X\bigg(\frac{s}{\sqrt{n}}\bigg)\bigg)^n \\
&= \bigg(\int_{-\infty}^{\infty} e^{-2\pi i \frac{s}{\sqrt{n}}x}f_X(x)dx\bigg)^n \\
&= \bigg(\int_{-\infty}^{\infty} \bigg(1 + \frac{-2\pi isx}{\sqrt{n}} + \frac{1}{2}\bigg(\frac{-2\pi isx}{\sqrt{n}}\bigg)^2 + \cdots\bigg)f_X(x)dx\bigg)^n \\
&= \bigg(\int_{-\infty}^{\infty} f_X(x)dx - \frac{2\pi is}{\sqrt{n}}\int_{-\infty}^{\infty} x f_X(x)dx - \frac{2\pi^2 s^2}{n} \int_{-\infty}^{\infty} x^2f_X(x)dx + \cdots\bigg)^n \\
&= \bigg(1 - \frac{2\pi^2s^2}{n} + \cdots\bigg)^n \\
&\approx \bigg(1 - \frac{2\pi^2s^2}{n}\bigg)^n \\
&\rightarrow e^{-2\pi^2s^2}
\end{align}
where in the third line we used the fact that the Fourier transform of a convolution is the product of the Fourier transforms, in the fifth line we used the Taylor expansion of $e^{-2\pi i \frac{s}{\sqrt{n}}x}$, and in the seventh line we used the fact that $f_X$ is a density function, $\mathbb{E}[X] = 0$, and $\mathbb{V}[X] = 1$.
Now let's take the inverse Fourier transform of $e^{-2\pi^2s^2}$.
\begin{align}
\mathcal{F}^{-1}e^{-2\pi^2s^2}(x) &= \int_{-\infty}^{\infty}e^{2\pi i xs}e^{-2\pi^2s^2}ds \\
& \text{ }\vdots \\
&= \frac{1}{\sqrt{2\pi}}e^{-\frac{1}{2}x^2}
\end{align} where the omitted details above involve completing the square in the exponent and then expressing the exponential involving the variable $s$ as a Gaussian density so that it integrates to one.
Thus, $f_{S_n}(x) \rightarrow \frac{1}{\sqrt{2\pi}}e^{-\frac{1}{2}x^2}$.
Comment: @dc3rd This is not a proof. I hope it introduced to you some new ideas and provided some intuition.
Comment: This solution is nice and elegant, but it involves concepts I have not studied yet formally so I am not familiar with all of the details. That being the case before I can attempt to work in detail this sort of pretty proof, I need to understand the basics. Which is what I asked about above.
Comment: Definitely introduced some new ideas....especially using Fourier transforms to get the gaussian distribution. I do like the explanation. I guess my frustration with understanding, yet not being able to understand rigourously this concept is frustrating me.....apologies if it came across as I was ungrateful.
Answer: Regarding the first question, we are indeed looking at the behavior of the partial sum $S_n$, but this of course depends on the behavior our random sequence $\{X_i\}_{i \geq 1}$ in hand.
For the second question, again you are correct. Strictly speaking, under the conditions that ensure the CLT holds (in fact under even weaker conditions), we have $Z_n \to 0$ almost surely (and thus in probability).
On the third question,yes the partial process $S_n$ is still random, but we're just saying that this converges to a fixed number as $n \to \infty$ almost surely. I don't think you're missing anything in particular - it's just that the "averaging out" absorbs all the noisiness as $n \to \infty$. However, if we multiply $S_n$ by $\sqrt{n}$, which is "just the right amount", we get a nice normal random variable as a limit.
Regarding the last question, I think you're on a good path of understanding the concepts! However, going through a nice measure theory based probability/stat book should help solidify your understanding.
[EDIT] I misread the question; I thought $Z_i$ is the standardized version of $X_i$, not the partial sum. Under bounded second moments of the original sequence (which we are already implicitly assuming by dividing by $\sigma$), we have $Z_n \to N(0,1)$ in distribution. Thus, $Z_n$ does not converge to any fixed number.
Comment: So with regard to you're comment about my third question, this is the picture I have in my head when you describe this: "I have the Gaussian distribution, if we take the $\lim_{n \to \infty}Z_{n}$ I will get $0$. If I don't take the "full limit", say something like $\infty - 100$, the "value" I would get would be expressed as $\lim_{n \to \infty-100}Z_{n} = c$, where $c \neq 0$. but some other value within the domain. It is these other values and the frequency in which they arise which makes the distribution normal."
Comment: But what troubles me is how are we getting other values for $Z_{n}$ besides $0$ by taking the limit?
Comment: For simplicity, (without loss of generality) let's assume $\mu = 0 $ and $\sigma = 1$. Then, we have $Z_n = \sqrt{n} S_n$. Why would the fact that $S_n$ converges to $0$ almost surely imply that $Z_n$ does to? We are scaling up $S_n$ by $\sqrt{n}$, so this need not be the case.
Comment: This is what is in my head when you say this: $\lim_{n \to \infty}(Z_{n}) = \lim_{n \to \infty}(\sqrt{n}S_{n}) = \lim_{n \to \infty}(\sqrt{n}) \cdot \lim_{n \to \infty}(S_{n}) = \lim_{n \to \infty}(\sqrt{n}) \cdot 0 = 0$.  That's why I'm coming to that conclusion.....SO there is something wrong in how I'm thinking about this then.
Comment: Okay, I see where the confusion is coming from. In general, $\lim_{n \to \infty} a_n b_n = \lim_{n \to \infty} a_n \lim_{n \to \infty} b_n$ is not true. It's true if both sequences converge. However, note that the sequence $n^{1/2}$ diverges in your case.
Comment: Funny, for the last few months I've been trying to drill into my head "Don't just breeze through and discount the initial hypothesis when reading theorems", finally it came to bite me in the rear. Won't be forgetting that again. Ok so since this isn't true in this instance, we are left in a situation where we can't determine absolutely what $Z_{n}$ will converge to. (cont'd below)
Comment: BUT we can minimize it to an interval of values $(-a,a)$. Now since this is originally a function of random variables, $X_{i}$, the possible values of $Z_{n}$ will themselves be random. Now taking the limit of $Z_{n}$ we obtain a value, call it $c$. This value $c$ converges to some value $x$. Now measuring the frequency (probability) with which $c$ occurs is equivalent to measuring the frequency with which $x$ occurs, but we can measure the frequency of $x$ occurring by using a normal distribution. And it is this which makes the CLT so powerful.
Comment: You can't restrict the value to a bounded interval like that because the normal distribution takes the entire real line as its support. Also, there is no guarantee that $Z_n$ converges to some fixed value for any realized sequence. However, I do think that you're getting the main idea. And yes, I agree that the CLT is extremely powerful.
Comment: Saying the interval is $(-a,a)$ was kind of my way of "saying" everything on the real line. It is not semantically correct, I agree, I was just attempting to crystallize things. You said: "there is no guarantee that Zn converges to some fixed value for any realized sequence". So how is it that we get these special "values", $x$, that allow us to use the normal distribution to approximate things?
Comment: $x$ is not a special value in any sense; we're just saying that for any $x \in \mathbb{R}$ we have $\lim_{n \to \infty} P (Z_n \leq x ) = \lim_{n \to \infty} F_{n}(Z) =  \Phi(x)$. Note that this does not imply that $Z_n$ converges to any specific value. The statement is about the distribution of $Z_n$, not it's specific realized sequences.
Comment: Now I'm a bit confused. Is there no relation between the $Z_{n}$ and the $x \in \mathbb{R}$? So with your statement about convergence what I have in my mind is the convergence of a sequence of functions, similar to this (I can't paste the picture here, but it is this google picture:  https://images.app.goo.gl/ik8T5hkTR2YBCLkm7  (just the idea of the picture, not necessarily the uniform convergence part). So for something like in the picture to occur the functions have to converge at all points. So I was thinking that the blue line would be $\Phi(x)$ and the other lines $F_{n}(Z)$
Comment: But in order to get all of the random values of $Z$, it meant that $Z_{n} \to Z$ and what the $F_{n}(Z) = \Phi(x)$ measures is the frequency of the convergence to each of the possible $Z$.....This is the thought I had....which is wrong and needs straightening out based on your explanation.
Comment: here is another way how I'm trying to reconcile things. It's based off thr simple example of what the CLT is doing. Say we have a population, we take a sample from the population, take its average and plot it on a graph. We repeat this process over many times and by the end of it, based on the CLT the distribution of those mean values will be normally distributed. So now I'm trying to take that idea and translate it to the technical jargon used to define the CLT rigourously.


jQuery ,Css display none - block vs. hide- show

Question: I am trying to hide #showMyList, #showMyName these divs. On click button need to show divs.
Both div has separate buttons. I want to see one div at a time. I can give different css (style)to them so that they will look different.
Which one will be more useful jQuery hide() and show()
Or display none and block?
#showMyList, #showMyName{
            height: 100px;
            width: 500px;
            text-align: center;
            border: 1px solid gray;
            background-color: antiquewhite;
            position: absolute;
            top: 200px;
            left:200px;
        }
    </style>

<button id="myList">Show List</button>
<button id="myAcc">Show Name</button>

List

Name

You can Hide both elements and then reveal or show 1 at a time.


Asset Pipeline not including CSS or JS in Grails 3 on external Tomcat 7/8

Question: When I upload the app.war.original from a 3.2.8 app to a tomcat7 or tomcat8 running on a java 1.8.0_51 server, assets are not included in my source, as if the asset:stylesheet and asset:javascript tags didn't exist in my layout.
The app is running fine with :
<code>java -D"grails.env"=prod -jar .\build\libs\app-x.y.z.war
</code>
Answer: Well, that was quartz-monitor plugin pulling an old version of asset-pipeline in my war file.


AMD Geode LX linux : how to instruct driver to enable flat panel?

Question: Platform : PC/104 with AMD Geode LX CPU with integrated graphics. Buildroot framework, kernel 4.18.10.
I am building a custom Linux system with Buildroot. Since I compiled the Geode LX frame buffer driver in the kernel (lxfb), I get a black screen on the flat panel (800x600 LCD), but the VGA output works.
It seems like the driver needs some input, but I can't figure out how to do it. See last struct : https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/drivers/video/geode/geodefb.h?h=linux-4.18.y&id=b5c26f97ec4a17c650055c83cfc1f2ee6d8818eb
Can anyone help me ?
Answer: Stupid me. The answer was in the driver documentation here : https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/fb/lxfb.txt?h=linux-4.18.y
I just need to pass lxfb.mode_option=800x600@75 to the kernel command line, and voilà !


Como calcular diferença de datas que estão uma linha anterior com MYSQL?

Question: Eu tenho uma tabela onde eu registro o momento em que determinada solicitação teve o seu status_id alterado. Essa tabela eu chamo de historico_status_solicitacoes.
Nessa tabela, eu tenho os seguintes campos: id, status_id, solicitacao_id, usuario_id, created_at.
Para cada solicitação que tem o status alterado, um registro é inserido.
Assim:
+----+-----------+----------------+------------+---------------------+
| id | status_id | solicitacao_id | usuario_id | created_at          |
+----+-----------+----------------+------------+---------------------+
|  1 |         1 |              1 |          1 | 2018-10-29 17:28:46 |
|  2 |         2 |              1 |          1 | 2018-10-29 17:38:50 |
|  3 |         3 |              1 |          1 | 2018-10-29 17:48:16 |
|  4 |         4 |              1 |          1 | 2018-10-29 18:58:46 |
|  5 |         5 |              1 |          1 | 2018-10-29 19:31:46 |
|  6 |         6 |              1 |          1 | 2018-10-30 10:20:00 |
+----+-----------+----------------+------------+---------------------+

O que eu preciso fazer? Eu preciso fazer uma consulta, onde eu consiga computar a diferença em minutos entre uma linha e outra, considerando a data menor para a data maior (que no caso pode ser o id também, já que é criado sequencialmente, e o valor maior sempre é o mais recente).
Eu fiz alguma coisa parecida para calcular o saldo atual, usando a linha anterior, mas não faço a minima ideia de como trabalhar com diferença de datas no MYSQL.
Alguém pode dar uma ajuda?
Comment: Não fui eu que negativei, mas por que fazer isso no banco? Não pode passar direto para o front?
Comment: mas tem que pensar na questao de performance também, isso pode pesar mto pro banco, algo que seria simples no front-end.
ps.: tb nao fui eu quem negativei xD
Comment: @WallaceMaxters precisa avaliar, dependendo as vezes uma variavel simples de comparação resolveria. Mas voce, que conhece o sistema, precisa avaliar e testar as opções, pensando não só como a base está agora, mas no futuro.
Comment: @WallaceMaxters, não seria interessante criar uma coluna `diferenca` e na hora de inserir calcular e informar a diferença para o ultimo registro?
Comment: Caramba, não tem 10 segundos que postei a pergunta e já tem um negativo? O que está acontecendo? Poderiam explicar o motivo?
Comment: @GuilhermeCostamilam se forem muitos retornos, eu poderia querer recorrer a uma paginação. E, numa paginação, você não teria o valor anterior caso estivesse na segunda página. Eu até pensei em fazer a pergunta no sentido de levá-la pro lado do Laravel, mas nesse caso, prefiro no banco de dados mesmo.
Comment: @aa_sp sinceramente, dependendo do tamanho da paginação, compensaria mais fazer o cálculo no banco, não? Por que um status poderia se repetir no histórico. Claro que é um caso raro, mas suponhamos que ocorra um caso de eu ter 1000 registros. É bom pensar por esse lado, porque o objetivo do site é ter uma resposta mais canônica, que possa ajudar outros usuários.
Comment: @RobertodeCampos isso aí vai contra a normalização de banco de dados, não? Calcular os dados tem mais chances de ter o valor certo do que uma coluna que pode ser alterada erroneamente.
Answer: Na consulta abaixo ele relaciona com o menor ID que é maior que o atual
SELECT
    A.id,
    A.created_at,
    TIMESTAMPDIFF(SECOND,A.created_at,B.created_at) AS timedifference
FROM historico_status_solicitacoes A
LEFT JOIN historico_status_solicitacoes B ON B.id = (
        SELECT MIN(B2.ID) FROM historico_status_solicitacoes B2 WHERE B2.ID>A.ID
    )

ORDER BY A.id ASC

Answer: Você pode fazer um SUB-SELECT pegando todos os registros com datas menores que a atual, ordenar pela data em ordem decrescente e limitar em 1, se realmente todos os registros tiverem a data sequencial, você sempre pegará o anterior:
select a.id, a.status_id, a.solicitacao_id, a.usuario_id, a.created_at, IFNULL((
    select TIMESTAMPDIFF(MINUTE, DATE_FORMAT(a1.created_at, '%Y-%m-%d %H-%i-00'), DATE_FORMAT(a.created_at, '%Y-%m-%d %H-%i-00'))
    from historico_status_solicitacoes a1
    where a1.id <> a.id AND a1.created_at <= a.created_at
    ORDER BY a1.created_at DESC
    LIMIT 1
), 0) diff
from historico_status_solicitacoes a;

Estou utilizando a função DATE_FORMAT para ignorar os segundos e sempre calcular o minuto cheio.
Veja funcionando no SQL Fiddle.
Comment: +1 boa, cara :D
Answer: Wallace a consulta pode ser feita da seguinte maneira:
SELECT A.id, A.created_at, TIMESTAMPDIFF(SECOND,A.created_at,B.created_at) AS timedifference
FROM historico_status_solicitacoes A INNER JOIN historico_status_solicitacoes B ON B.id = (A.id + 1)
ORDER BY A.id ASC

Só uma observação, nesse caso o resultado será em 'SEGUNDOS', para deixar em uma granularidade maior ( Minutos ou horas), basta trocar o seguinte trecho na sintaxe SQL:

...TIMESTAMPDIFF(SECOND,...
Comment: Boa ideia. O problema é que as vezes o `id` nem sempre pode ser `+1` o subsequente.
Comment: entendi.. é que me baseei nessa parte: (que no caso pode ser o id também, já que é criado sequencialmente).
Comment: Eu acho que me expressei mal. Na verdade, o `id` mais recente sempre terá o valor maior que o anterior.


If $q$ is a monic polynomial, then $qf=qg \implies f=g$

Question:
For a monic polynomial $q\in R[X]$, prove that $qf=qg$ implies $f=g$,
  where $f,g\in R[X]$.

Note: by assumption, rings are commutative.
I don't understand this problem. Can't I just say "perform polynomial division by $q$ on both sides"? Does it not work this way?
Also, if I could show that $R[X]$ is a field, then I could multiply on the left by $q^{-1}$. But $R[X]$ is not necessarily a field. Is there something about $q$ being monic that implies it has a multiplicative inverse?
Thanks!
Comment: $R[X]$ is not a field. You can't, in general, divide by a $q$ if $q$ is not monic, so you'll need that $q$ is monic.
Comment: Is $R$ an arbitrary ring or are there assumptions on $R$?
Comment: Commutative ring. Sorry--let me edit the question
Comment: How does $q$ being monic allow me to divide by it?
Comment: That's what you need to prove. :)
Comment: I see! Let me try:
Comment: I see that we can't divide $aX^n$ by $bX^m$ because $a/b$ is not necessarily an integer. If $b=1$, then we definitely have at least one term $aX^{n-m}$. But what I'm worried about is the case when $\deg(q)>\deg(f)$. We might still not be able to divide them, even if $q$ is monic.
Comment: Don't think division, just show that if $q$ is monic and $qf=0$ then $f=0$.
Comment: How can I take the step after that to say that $qf=qg\implies f=g$?
Answer: Hint: Basically, you need to prove that $qf=0$ implies $f=0$.
This is not true if $q$ is not monic - specifically, if $q$ has a zero divisor for initial coefficient. Take $R=\mathbb Z/4\mathbb Z$, with $q=f=2X$.
Comment: I proved that a monic $q\in R[X]$ does not have a zero divisor (this was earlier in the assignment). It does not have a zero divisor because if $a=a_n X^n +\cdots \in R[X]$ then $qa=a_n  X^{k+n} +\cdots$ and $a_n\neq 0$
Comment: This means that $qf\neq 0$ for all $f\neq 0$.
Comment: Hence, $qf=0$ implies $f=0$.
Comment: That first comment is imprecise. "Does not have a zero divisor" is the wrong use of language. You've proven a monic polynomial is not a zero divisor. But yes, your argument is correct. Now, apply this to $qf=qg$, which would mean $q(f-g)=0$ which means...
Comment: Oh!! Got it! Thank you!


APP nodejs: impedir logs na janela do terminal

Question: Criei um aplicação em Nodejs com Express e quando coloco essa aplicação para rodar (com npm start), ficam aparecendo uns logs na janela do terminal em que estou conectado a cada página que eu acesso das minhas rotas.
É para ser assim mesmo? Tem como desabilitar e é bom que seja desabilitado?
logs na janela do terminal:
GET /javascripts/jquery/jquery-ui.js 304 32.627 ms - -
GET /javascripts/jquery/datepicker-pt-BR.js 304 32.307 ms - -
GET /javascripts/chartjs/Chart.js 304 32.109 ms - -

Answer: Você pode utilizar a seguinte linha de código:
console.log = function(){}

Qualquer chamada a console.log será "ignorada" a partir desse ponto
Se quiser ativar/desativar, pode atribuir console.log a uma variável para depois recuperar
Ex.:
var log = console.log;
console.log = function(){};//Desativa
console.log = log;//Ativa novamente

Comment: ok, obrigado pelo retorno
Comment: grato pelo retorno. Mas eu gostaria de saber se o que causam esses logs na tela é para continuar assim. Se não for para continuar assim, essa maneira que você indicou é única maneira? ou existe algum recurso habilitado por padrão na estrutura básica de projeto que o Express cria, que fica gerando esses logs, e que pode ser desabilitado?
Comment: Não entendo muito de nodejs, mas acho que não há problemas com o log, essa opção que eu passei é genérica em javascript