What's the typical role of the constant $e^{-\gamma}$?

Question: I often encounter this constant in my research, but I wonder what typical roles does it play in other areas of mathematics? Wikipedia mentions probability theory but nothing exact.
Also, I am interested to know best keywords to search about this constant.
Comment: It appears in Mertens' third theorem: https://en.wikipedia.org/wiki/Mertens%27_theorems
Answer: This constant appears in Weierstrass factorization of $\Gamma(s)$:
$$
{1\over\Gamma(s)}=se^{\gamma s}\prod_{k\ge1}\left(1+\frac sk\right)e^{-s/k}
$$
and also in Mertens' formula:
$$
\prod_{p\le x}\left(1-\frac1p\right)={e^{-\gamma}\over\log x}\left[1+\mathcal O\left(1\over\log x\right)\right]
$$
Mertens' formula accounts for most appearance of $e^\gamma$ in number theory. For instance, it can be used to deduce the minimal order of Euler's totient function:
$$
\liminf_{n\to\infty}{\varphi(n)\log\log n\over n}=e^{-\gamma}
$$
and the maximal order for divisor sum function (aka Gronwall's theorem):
$$
\limsup_{n\to\infty}{\sigma(n)\over n\log\log n}=e^\gamma
$$
Answer: Number theory: The geometric mean of prime numbers around $n$, is approximately $\color{red}{e^{-\gamma}}\log n$.
Probability: If $u_1=$ random real number in $(0,1)$, and $u_k=$ random real number in $(0,u_{k-1})$, then the probability that $\sum_{k=1}^\infty u_k>1$, is $1-\color{red}{e^{-\gamma}}$.
(To find more, you can try putting $e^{-\gamma}$ in the search bar here on MSE, or at approach0.)
Comment: What is "random real number"? I asked this question but it was deleted: https://math.stackexchange.com/q/4716621/2513


How to raise runtime error when a namelist variable is missing in an input namelist file?

Question: An example code is as follows:
program main
 implicit none
 integer :: ufile
 real :: a, b, c
 namelist /my_nlt/ a, b, c
 open(newunit=ufile,file='my_nlt.txt')
 read(ufile,my_nlt)
 close(ufile)
 write(*,my_nlt)
end program main

And the input file my_nlt.txt contains:
 &my_nlt
 a=1.0
 b=2.0
  /

Here the variable c is missing in the input file.
Running the code compiled by gfortran gives no warnning/error. I am wondering whether there is a compiler option that can be used to raise an error/warning when encountering this situation?
Answer: I am not aware of such an option for gfortran (or any other Fortran compiler).  I would also strongly recommend not relying on such an option should one be found.
Namelist formatting exists to give a certain simplicity and flexibility of input to specific objects.  Desiring a warning with a namelist read not updating all variables is perhaps trying to use the tool inappropriately.
For the program and input of the question, the expected runtime behaviour is for a and b to be defined with the values stated, and for c to be undefined.  Instead, we could define the three variables with a value prior to the read and see whether they are updated by the read:
real, parameter :: SENTINEL=HUGE(0.)
real :: a=SENTINEL, b=SENTINEL, c=SENTINEL
namelist /my_nlt/ a, b, c
open(newunit=ufile,file='my_nlt.txt')
read(ufile,my_nlt)

if (a==SENTINEL.or.b==SENTINEL.or.c==SENTINEL) ERROR STOP

Here SENTINEL would be a value undesired for the variables or unexpected in the input.  A variable not included in a namelist record retains its value prior to the read.
This isn't the same thing as certainly not appearing (especially where there may be no out-of-range input value) but if you want to check that then you'll have to parse the input file manually.  The structure of such a namelist file is well defined.
As a final consideration, is the variable c "present" in the following namelist input record?
&my_nlt a=1., b=2., c=1* /

Comment: Adding to @francescalus' excellent answer, a NAMELIST read where a variable is not named leaves the variable in its previous definition status. I'll note that you can't even rely on a compiler's uninitialized variable checking to detect this.
Comment: @YoujunHu, my comment about using the tool "inappropriately" relates to how namelist input is designed not to affect variables which don't feature in the input record (and may appear in any order, or incompletely), which is in stark contrast to the other form of formatted input. Think of it as a facility like command line arguments: the user expects to be able to give just a selection of values on the command line, perhaps leaving others as "default values" or unspecified.
Comment: @YoujunHu, `c` has a well-defined value from the namelist record `&my_nlt a=1.0,b=2.0, c=2+1 /`.  That value is `20.`.  [If you don't understand why, then that could make a good question.]
Comment: @YoujunHu, it's 20 because `2+1` as input field is interpreted as 2 with exponent 1 (2×10^1).
Comment: If the input file looks like `&my_nlt a=1.0,b=2.0, c=2+1 /`, `c` still gets a value without error (tested using gfortran), but the value is not as we expected. To just test whether a variable presents, maybe the safest way is to parse the input file manually.
Comment: @francescalus mentioned "Desiring a warning with a namelist read not updating all variables is perhaps trying to use the tool inappropriately". I do not understand this. It seems to me that warning for a missing variable is a reasonable enhancement for the robustness of fortran namelist.
Comment: @francescalus, The value I got is indeed `20` and I indeed do not understand why.


Geometry: Proof related to right angled isosceles triangle

Question: ABC is a right angled isosceles triangle. If AD is a bisector of angle BAC then prove that AC + CD = AB.
The right angled isosceles triangle
The right angle is at C.
Comment: What are your own thoughts on this problem?
Comment: Is the right angle located in $C$?
Comment: Are you sure of that?
Comment: Yes I am sure. The right angle is at C. @Dr. Sonnhard Graunber
Comment: I figured out each individual angle but other than that I don't have anything. @Matt
Comment: @Dr.SonnhardGraubner How did you equate AC and CD? ABC is the isosceles triangle here, not ADC.
Answer: After a Theorem of the angle bisector we get
$$BD:DC=\sqrt{2}a:a$$
or
$$\frac{a-DC}{DC}=\sqrt{2}$$
simplifying this we get
$$DC=\frac{a}{\sqrt{2}+1}$$
so $$a+\frac{a}{\sqrt{2}+1}=a$$
and this is true
since
$$\sqrt{2}a+2a=2a+\sqrt{2}a$$
Where $$AC=BC=a$$ and $$AB=\sqrt{2}a$$
Comment: Sorry it was just a typo!
Comment: Is it clear now?
Answer: Since this is an isosceles right triangle the two acute angles are $\pi/4$ radians.  We can, without loss of generality, take sides AC and BC to have length 1 so that AB has length $\sqrt{2}$.  Bisecting angle A gives an angle of $\pi/8$ radians and DC has length $\tan(\pi/8)$ $= \frac{sin(\pi/4)}{1+ cos(\pi/4)}= \frac{\frac{\sqrt{2}}{2}}{1+ \frac{\sqrt{2}}{2}}= \frac{\sqrt{2}}{2+ \sqrt{2}}$.
$AC+ CD= 1+ \frac{\sqrt{2}}{2+ \sqrt{2}}= \frac{2                                      + 2\sqrt{2}}{2+ \sqrt{2}}= \frac{4+ 4\sqrt{2}- 2\sqrt{2}- 4}{4- 2}= \frac{2\sqrt{2}}{2}= \sqrt{2} $


Erro Unsupported operand types

Question: Quando importo o xml de imovel ele faz a conta de acordo com os critérios. Um dos critério é o preço, os mais caros aparecem primeiro, para isso eu dividi o valor do preço por 10 milhões e soma o resultado no ranking dele.
Ex: Imóvel com nota 1500 + (preço de 10.000.000/10.000.000) = 1501
Mas quando faço essa conta, ele trava a importação e dá esse erro:

Erro Unsupported operand types on line 332

Que é a linha onde acaba o if do código abaixo:
if ($tipo==Venda){
$ordem = $ordem + $preco/10000000;
}

Alguém sabe o que pode estar acontecendo?
Comment: Primeiro: há as devidas aspas envolvendo o termo "Venda" na condição? Segundo: quais são os tipos das variáveis?
Answer: Para "depurar" as variáveis, antes da if faça:
var_dump($ordem, $preco);
if ($tipo==Venda){

E então irá notar o problema,  $ordem ou $preco não são números, um deles deve ser um array ou null e então não será possível fazer a operação matemática, o que causa o erro.
Isto deve estar ocorrendo porque esta usando em um while ou for sem checar os valores que estão sendo usados adicionados ao $ordem e $preco, você pode também estar usando a variável em diferentes lugares, tipo tentando reaproveitar uma variável para fazer duas coisas, algo que realmente pode causar muitos problemas.
Outro problema, que talvez não tenha ligação direta, é o if que "parece" estar errado:
if ($tipo==Venda){

O Venda teria que ser assim 'Venda', a não ser que venda seja uma constante (mas isto é outro problema).
Comment: deu isso aqui:
int(1100) string(10) "1638000.00" int(1100) string(10) "6500000.00" int(1600) string(10) "4500000.00" int(100) array(0) { }
Comment: Veja @LeandroTeraoka um deles mostrou `array(0) { }`, ou seja uma das chamadas esta recebendo array, tem que corrigir dentro do seu `while` (creio que seja os resultados do banco)
Comment: desculpa, não entendei, não manjo mt. tem como eu saber quem está vindo como array?
Comment: De onde vem o valor de `$ordem`? É do banco de dados (de um while)? Posta o código todo no pastebin.com pra eu ver
Comment: Perdão, falei banco, mas na verdade o problema deve ser em um for do conteudo do xml, algum deles deve estar ser o preço e o parse do XML deve estar pegando como se fosse uma "tag" vazia o que é convertido para um array vazio. Estou só supondo, sem o código não tem como ajudar mais que isto, se puder dar detalhes ajudaria.
Comment: o código é gigante...rs,
o $preco que está dando erro. eu defini ele para $preco=4500000 antes do if, aí não deu erro e funcionou certinho.
o $preco é definido assim $preco = $property['price'];. ele pega o valor do xml que está em 4500000.00
se eu jogo o $preco no campo preço do banco de dados, ele aparece o valor normal (ex: 450000.00)
Eu testei importando um xml com apenas alguns imóveis e funcionou normalmente
Comment: @LeandroTeraoka tente criar um exemplo minimo que reproduza o erro e me manda.

Erro Unsupported operand types


Filtro de informações de candidatos a emprego

Question: Um programa que filtre informações de candidatos a emprego: O nº de candidatos por sexo.... Tem um erro nesse if, ta retornando só m ou só f
package livroex_pag69;

import javax.swing.JOptionPane;

public class Ex_09_Recrutamento {
    public static void main(String[] args){
        String sexo, exp, esc, continuar ;
        int idade, m = 0, f = 0, numCand = 1;

    do{
        idade = Integer.parseInt(JOptionPane.showInputDialog("Idade: "));
        sexo = JOptionPane.showInputDialog("Sexo [m/f]: ");
        esc = JOptionPane.showInputDialog("Cite a escolaridade:  ");
        exp = JOptionPane.showInputDialog("Possui experiência [s/n]: ");
        numCand++;
        continuar = JOptionPane.showInputDialog("Deseja continuar? [s/n]  ");

        }while(continuar.equals("s"));

        for (int i = 1; i < numCand; i++){
             if(sexo.equals("m")){
                 m++;
             }else{
                 f++;
             }

        }

 JOptionPane.showMessageDialog(null, "Número de candidatos masculino: " + m+
                                     "\n Número de candidatos feminino: "+f);

    }

}

Comment: Obg Icaro, como há o limite de caracteres, me perco nessa parte. valew.
Comment: Sua lógica está incorreta, pois o "for" só será executado quando continuar for diferente de s, logo só haverá apenas um resultado, sempre retornará apenas um sexo, reavalie seu laço de repetição do while
Comment: Ola Thiago, bem vindo ao SOpt, antes de começar de uma olhada em nosso [Tour] -- Fiz uma alteração no titulo e descrição de sua pergunta se minha alteração não representa sua necessidade você pode reverter-la acessando esse [link](https://pt.stackoverflow.com/posts/389175/revisions) e escolhendo a revisão que melhor lhe atende. =D
Answer: Seu código está re-escrevendo as mesmas variáveis toda vez que passa pelo seu do-while, para resolver o seu problema, você deve armazenar os valores em um array, ou qualquer outro tipo de lista se preferir.
Atualmente, a sua impressão sempre está sendo a ultima recebida nos inputs.
EDIT: No caso de não poder usar arrays ou listas, como citado no comentário, você deve alterar a ordem em que acontecem os seus comandos, fazendo com que a condicional e a impressão sejam feitas dentro do loop do-while. Sendo assim, serão impressas após os inputs, a cada iteração do laço.
Comment: Sim, funcionou. Obrigado Pedro. Tenho outras condicionais para por no programa. Valew.
Comment: Fico feliz que tenha te ajudado! Se puder marcar a resposta como correta, eu agradeceria. Valeu!
Comment: Olá, não posso usar arrays ou lists. Deve ser feito um por um.
Comment: Neste caso, você deve inserir a sua condicional de impressão, dentro do laço do-while, para que toda vez que você der input num valor, ele já imprima. Neste caso seu for seria inutilizado, pois você estaria imprimindo na hora do input.
Answer: Vou tentar explicar por partes o que esta acontecendo em seu código.
A cada interação desse bloco seus dados anteriormente informado se perdem, exceto o numCand que é um contador então ele é incrementado
  do {
   idade = Integer.parseInt(JOptionPane.showInputDialog("Idade: "));
   sexo = JOptionPane.showInputDialog("Sexo [m/f]: ");
   esc = JOptionPane.showInputDialog("Cite a escolaridade:  ");
   exp = JOptionPane.showInputDialog("Possui experiência [s/n]: ");
   numCand++;
   continuar = JOptionPane.showInputDialog("Deseja continuar? [s/n]  ");
  } while (continuar.equals("s"));

Nesse outro bloco você esta fazendo um for baseado no contador que foi gerado pelo do while, ou seja, o numCand, porem a variavel sexo e do tipo String e sempre vai conter o valor da ultima interação do do while
for (int i = 1; i < numCand; i++) {
   if (sexo.equals("m")) {
       m++;
   } else {
       f++;
   }

Exemplo:
   Imagina que no do while voce entrou com as informaçoes f, m, f, m.
   Sua variavel sexo vai ficar com o valor m , seu contador numCand vai ficar com o valor 4.
   Quando você chegar no bloco for você vai verficar 4x que a variável sexo é igual a m.

Uma possível solução
Se você não tem a intenção de guardar esses dados e só quer saber quantas pessoas do sexo m e f foram informadas você pode colocar esse if dentro do proprio do while, ficando +/- assim:
  do {
   idade = Integer.parseInt(JOptionPane.showInputDialog("Idade: "));
   sexo = JOptionPane.showInputDialog("Sexo [m/f]: ");
   esc = JOptionPane.showInputDialog("Cite a escolaridade:  ");
   exp = JOptionPane.showInputDialog("Possui experiência [s/n]: ");
   numCand++;
   continuar = JOptionPane.showInputDialog("Deseja continuar? [s/n]  ");

   if (sexo.equals("m")) {
       m++;
   } else {
       f++;
   }

  } while (continuar.equals("s"));


How to get the following isomorphism $\phi$?

Question: There is an exercise of the book "Rings and category of modules":
Let $R$ and $S$ be two rings. $_RM_S$ is a faithfully balanced bimodule. Show that there is a ring isomorphism $\phi: Cen R \rightarrow Cen S$ such that $km=m \phi(k)$ for all $m \in M$ and $k \in Cen R$. ($Cen R$ means the centre of the ring $R$)
I don't know how to get the isomorpism. Thank you for any help.
Answer: Well, all you have to work with is an isomorphism $\lambda:R\to End(M_S)$ and an isomorphism $\rho:S\to End(_RM)$, so start with those.
Let $r\in Cen(R)$. Since $r$ is central, $\lambda(r)$ is not only right $S$ linear, it is also left $R$-linear. That means there exists a unique $s\in S$ such that $\lambda(r)=\rho(s)$. Explicitly, that means $rm=ms$ for all $m\in M$.
The question arises: is $s$ necessarily central in $S$?  Well, you tell me, just compute: for an arbitrary $s'\in S$, $mss'=(rm)s'=\ldots$ You will eventually use the fact $\rho$ is an isomorphism to conclude $s$ is central.
If we call the restriction of $\lambda$ to the center of $R$ as $\bar\lambda$, we are apparently looking at $\phi=\rho^{-1}\bar\lambda:Cen(R)\to Cen(S)$.
This furnishes you an injective homomorphism, but don't forget to show that it is surjective too. One strategy might be to argue by symmetry that a pair of similar maps $\psi=\lambda^{-1}\bar\rho$ is an inverse homomorphism for $\phi$.
Comment: Why explicitly $rm=ms$ and how can I go to $s$ is central from $mss'=(rm)s'=\ldots$. I didnt understand much.
Comment: @BERAT it follows directly from the preceding sentence.
Comment: I couldnt reach $sm=ms$ still trying.
Comment: @BERAT that is the definition of what the previous line means.


Adding a default text

Question: Option 1: Is there any way to write a conditional in Twig that if field1 in Drupal is empty, I can set a default text to say "Bye"
Option 2: I was also trying to use the conditional fields module, to where field2(with the default text "Bye") will only display if field1 is empty. It doesn't seem to work though.
Any help is appreciated thank you
Answer: Solution for option-1 :
{% if node.field_example.value is empty %}
   Bye
{% endif %}

Answer: Never tried with that dependency but option 2 should work, how are you setting the conditional field?
Anyway there's empty fields module that should solve your issue.

Adding a default text


Is it possible to pause an R script that is running?

Question: I am running a some analysis in R which is going to take at least 24 hours to finish. Is it possible to pause the function midway, so that I can take my computer to work and back?
Comment: What operating system do you use?
Comment: Windows 7 (I'm sorry should have mentioned that along with the question)
Comment: Tough. You could try suspend and resume, and hope for the best. Doesn't always pan out though...
Answer: This is not possible AFAIK, but I believe you can just suspend your computer and the processes automatically will be paused.
If you are using Linux, you can also stop and continue a process manually using killall -STOP R and killall -CONT R commands. Take a look at this article and the comment section there, which contain useful information regarding this.
On Windows, you can maybe use the Task Manager or install special software that is capable of doing that. But I really do not know as I do not use Windows on a regular basis.
EDIT: even if you use kill or killall to pause the process, but shutdown the computer, you will lose the data.
Comment: Yes, I've done this with my Mac laptop (just by shutting the lid) and the script starts up again when I open it without any trouble.
Comment: not with 'killall -STOP program', 'killall -CONT program' .. I should update the answer, I guess to avoid confusion.
Comment: Yes, please do. You could also mention 'Ctrl-z' and 'fg' / 'bg' which is job control from bash.  But we do not know the OS the OP is using.
Comment: Unfortunately I am not using Linux, but I guess I'll try suspending the computer and see if that works.


State space models in python statsmodels: including lag state innovation in observation equation

Question: I am trying to fit the following state space model via the (excellent and highly useful) statsmodels state-space module.  The model is a standard local level model but where last period's innovation in the state equation loads into this period's observation equation via a coefficient to be estimated (a simpler version of Menkveld, Koopman and Lucas, JBES (2012) Eq (7) page 215):
$$
\alpha_{t+1} = \alpha_t + \eta_t \\
y_t = \alpha_t + \varepsilon_t + \theta \eta_{t-1}
$$
In state space form, the model can be written as:
$$
\mathbf{\delta_{t+1}} = \begin{pmatrix}  \alpha_{t+1} \\\eta_t \end{pmatrix} =
\begin{pmatrix} 1,0 \\ 0,0 \end{pmatrix} \begin{pmatrix}  \alpha_{t} \\\eta_{t-1} \end{pmatrix} +
\begin{pmatrix} 1 \\ 1 \end{pmatrix} \eta_t
\\
y_t =  \begin{pmatrix} 1,  \theta\end{pmatrix} \delta_t + \varepsilon_t
$$
where $\delta_{t}$ is the state variable $(\alpha_t, \eta_{t-1})'$.
I've simulated the DGP as follows:
import numpy as np

T, k_obs = 5000, 1 # Sample length (rows of y) and number of variables (columns of y)
var_eta, var_eps = 2.8, 0.5  # Variance of the state disturbance and the obs. disturbance

rs = np.random.RandomState(seed=2017)
eta = rs.normal(scale=var_eta ** 0.5, size=T) # Sequence of state-varaible shocks
epsil = rs.normal(scale=var_eps ** 0.5, size=T) # Sequence of obs-varaible shocks

theta = -0.3 # Coefficient on lag state error in observation equation

alpha, y  = np.zeros(T), np.zeros((T, k_obs))

# Update the first two observations of y and alpha:
y[0] = alpha[0] + epsil[0]
alpha[1] = alpha[0] + eta[0]
y[1] = alpha[1] + epsil[1] + theta*eta[0]

# Update remaining obervations as per the DGP
for t in range(2,T):
    alpha[t] = alpha[t-1] + eta[t-1]
    y[t] = alpha[t] + epsil[t] + theta*eta[t-1]

Then I've specified and estimated a state space model as follows:
import statsmodels.api as sm

class llmodel_with_lag(sm.tsa.statespace.MLEModel):
    def __init__(self, endog):
        super(llmodel_with_lag, self).__init__(endog,
                                              k_states=2,
                                              k_posdef=1,
                                             initialization = 'diffuse')

        self['design', 0, 0] = 1.0 # Design matrix is a 1x2: [1,theta]
        self['design', 0, 1] = 1.0 # Theta coefficient on lag state innovation in obs. equation

        self['transition', 0, 0] = 1.0 # Transition matrix is [[1,0],[0,0]]
        self['transition', 0, 1] = 0.0
        self['transition', 1, 0] = 0.0
        self['transition', 1, 1] = 0.0

        self['selection', 0] = 1.0 # Selection matrix is [1,1]
        self['selection', 1] = 1.0

        self['state_cov'] = [0]
        self['obs_cov'] = [0]

        self.positive_parameters = slice(0,2)

    @property
    def param_names(self):
        param_names =  [
            'state_var',
            'obs_var',
            'design_ma'
        ]
        return param_names

    @property
    def start_params(self):
        params = [
            0.1,
            0.1,
            0
        ]
        return params

    # Constrain the variance parameters to be positive,
    def transform_params(self, unconstrained):
        constrained = unconstrained.copy()
        constrained[self.positive_parameters] = (
            constrained[self.positive_parameters] ** 2
        )
        return constrained

    def untransform_params(self, constrained):
        unconstrained = constrained.copy()
        unconstrained[self.positive_parameters] = (
            unconstrained[self.positive_parameters] ** 0.5
        )
        return unconstrained

    def update(self, params, **kwargs):
        params = super(llmodel_with_lag, self).update(params, **kwargs)

        self['state_cov', 0, 0] = params[0] # Variance of the state innov.
        self['obs_cov', 0, 0] = params[1] # Variance of the obs. innov
        self['design', 0, 1] = params[2] # Coefficient on lag state innov in obs. eqn

# Estimation
mod = llmodel_with_lag(y)
modinit = mod.fit(maxiter = 1000)
modfit = mod.fit(start_params = modinit.params,
                 method = 'nm',
                 disp = 0,
                 maxiter = 1000)

When doing this, I am repeatedly getting a very strange result where the coefficients on the lagged state innovation $\theta$ in the observation equation, and the variance of the observation shock, are not estimated correctly, but more curiously, the $\theta$ coefficient always has a z-statistic of exactly 1.000 or -1.000 (so the magnitude of the std. error is equal to the magnitude coefficient).  I've tried this for a number of different parameter values and estimation methods and continue to generate the same z-value of 1 or -1 on $\theta$. The model converges and the condition number on the parameter covariance matrix is finite. I also obtained a similar result using real data so I don't believe the issue is in the DGP itself.
I am not sure what is driving this, but since the coefficient and standard error have virtually identical magnitudes and the condition numbers are fine, this didn't appear to be a problem that the parameters are not identified or that the model being incorrectly specified (though I could be mistaken about this).
Any ideas or help regarding what I am doing wrong or what should be changed to get the estimation working would be much appreciated!
Answer: The problem here is that the $\theta$ and $\sigma_\varepsilon^2$ parameters are not separately identified. In particular, if you work through the Kalman filtering equations, it can be shown that the loglikelihood depends on these two parameters essentially only through the sum $(\theta + \theta^2) \sigma_\eta^2 + \sigma_\varepsilon^2$. (I say "essentially", because depending on what "initialization" method is used, the loglikelihood for the first few periods can depend on the parameters in other ways, but this effect disappears quickly - in the example below, it disappears after 2 observations).
In other words, suppose that the true parameters used to generate the data are $(\bar \sigma_\eta^2, \bar \sigma_\varepsilon^2, \bar \theta)$. Then any other $\sigma_\varepsilon^2, \theta$ pair such that
$(\theta + \theta^2) \bar \sigma_\eta^2 + \sigma_\varepsilon^2 = (\bar \theta + \bar \theta^2) \bar \sigma_\eta^2 + \bar \sigma_\varepsilon^2$
will yield the same loglikelihood as the true parameters.
So, for example, if I am given a particular $\sigma_\varepsilon^2$, then I could solve for the associated $\theta$ by solving the following quadratic equation
$$\theta^2 + \theta - \frac{1}{\bar \sigma_\eta^2} \left ( (\bar \theta + \bar \theta^2) \bar \sigma_\eta^2 + \bar \sigma_\varepsilon^2 - \sigma_\varepsilon^2 \right ) = 0$$
The code snippet below shows how this works in practice:
# Construct the model
mod = llmodel_with_lag(y)
# Ignore the loglikelihood associated with the
# first two periods
mod.loglikelihood_burn = 2

# Collect the true parameters
bar_sigma2_eta = 2.8
bar_sigma2_eps = 0.5
bar_theta = -0.3

# Compute the true value of the key sum that
# appears in the loglikelihood
key_sum = (bar_theta + bar_theta**2) * bar_sigma2_eta + bar_sigma2_eps

# Specify an alternative \sigma_\varepsilon^2,
sigma2_eps = 0.3

# Compute the corresponding alternative \theta
# by solving the quadratic equation
a = 1
b = 1
c = -(key_sum - sigma2_eps) / bar_sigma2_eta

theta_option1 = (-b + (b**2 - 4 * a * c)**0.5) / (2 * a)
theta_option2 = (-b - (b**2 - 4 * a * c)**0.5) / (2 * a)

# Check that these all yield the same loglikelihood
print('Loglikelihood at true parameters')
print(mod.loglike([bar_sigma2_eta, bar_sigma2_eps, bar_theta]))

print('Loglikelihood at sigma2_eps, theta_option1')
print(mod.loglike([bar_sigma2_eta, sigma2_eps, theta_option1]))

print('Loglikelihood at sigma2_eps, theta_option2')
print(mod.loglike([bar_sigma2_eta, sigma2_eps, theta_option2]))

Which prints out:
Loglikelihood at true parameters
-9394.989471741343
Loglikelihood at sigma2_eps, theta_option1
-9394.989471741343
Loglikelihood at sigma2_eps, theta_option2
-9394.989471741343

Comment: Thanks a lot for this very informative answer (and the really awesome package).  I had incorrectly assumed that an issue such as this would show up as very high standard errors (i.e. a lack of curvature on the log-likelihood function).  But in this case with a non-linear relationship between the variables, I guess there are multiple local peaks that all have the same likelihood.

Thanks again.  I would upvote but I don't have enough reputation.


Api's to compare text in java

Question: I have a web-service in java, which is used by various services to insert data in mongodb. But since data is duplicate, we came with a solution to make a key-value pair of data and check it, if it is already present, before inserting in mongodb.
But comparing so many string is difficult task and it will take lot of time.

Do we have any lib/API's available for faster comparison.
Elastic search is for search, will it be good for text comparison too?

My String example
"Message:WSClient.FetchReservation::WS FetchReservation calledSystem.Net.WebException: The operation has timed out at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) at BOTWSClient.ChannelDirectWS.YieldGain.fFetchReservation(String strReservationXML) at BOTWSClient.WSClient.FetchReservation(String RequestXML)"
Comment: Are the diffferent texts exactly the same, or slightly different ?
Comment: They are exactly same. Suppose from 1 million records, 50 thousand exactly same strings are repeated every time.
Answer: If the text is exactly the same you could hash it and just compare hashes. If you don't have too many entries sha1 should suffice.
As JonasCz said, please update you question so we know if the texts are exactly the same (my solution could work) or similar (my solution is not working).
Comment: I have updated my text. So it could be repeated my times.

Api's to compare text in java


Formating dates with =text(month(today()), "MMM")

Question: I... don't know how to process this. Can someone explain what's happening to me?
Today's 20 December 2021. When I put the below formula into Google Sheets, I get "Jan"
=text(month(today()), "MMM")
https://docs.google.com/spreadsheets/d/1uLC0Q0dgChEbfNXjXEketyc64tsurz4vQ9o1QFO87NY/edit?usp=sharing
Comment: The `MONTH()` needs to go!
Comment: get rid of the MONTH part.
Answer: By including "MMM" in the =text() function you're already telling it that you want a month, so there is no need for the extra month().
Removing it would leave the formula as =TEXT(TODAY(), "MMM"), giving the correct result.
Answer: The other responses were super helpful, and it helped me figure out why it was happening.
Google Sheets, by default, processes dates as days since January 1, 1900 (so if you input a "1" and then format it as a date, you'll get January 1, 1990).
In the formula I mentioned above,
=text(month(today()), "MMM")
... the month(today()) section of the code outputs "12". When the "text" formula coerces that value into a month-value, it expects a full date. As a consequence, =text(month(today()), "MMM") asks for the month ("MMM") of date-value "12" (i.e. January 11, 1990).
That's why =text(month(today()), "MMM") outputs "Jan."
To fix the code, as others have said, you need to remove the "month()" section of the formula, therefore,
=text(today()), "MMM")


Usar um método de outra classe para registrar no banco usando DAO

Question: Tenho que registrar dados em um banco, mas um desses dados é calculado por uma outra classe, queria saber como pegar os dados do banco e colocar eles no calculo do método e depois registrar o resultado.
DAO
package persistencia;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import lojabrinquedos.Brinquedo;
import lojabrinquedos.Cliente;
import lojabrinquedos.ClienteBrinquedo;

public class ClienteBrinquedoDAO {
    private static Connection connection;
    private static PreparedStatement st;
    private static PreparedStatement st1;
    private static ResultSet rs;
    private static ResultSet rs1;

    public static int gravaPorCliente(int idBrinquedo, int idCliente, String data, int quantidade, double valorTotal, int matricula) throws Exception {
        int ret = 0;
        ClienteBrinquedo cb = new ClienteBrinquedo();
        Brinquedo brinquedo = new Brinquedo();
        try {
            String sql = "INSERT INTO clientebrinquedo (Brinquedo_idBrinquedo, Cliente_idCliente, data, quantidade, valorTotal, Funcionario_matricula) VALUES (?,?,?,?,?,?)";
            String sql2 = "Select * FROM Brinquedo where idBrinquedo = ?";
            connection = GerenteDeConexao.getConnection();
            st = connection.prepareStatement(sql);
            st1 = connection.prepareStatement(sql2);
            st1.setInt(1, idBrinquedo);
            rs1 = st1.executeQuery();
            if (rs1.next()) {
                brinquedo.setPreco(rs1.getInt("preco"));
                Brinquedo.setDesconto(rs1.getInt("desconto"));
            }
            st.setInt(1, idCliente);
            st.setInt(2, idBrinquedo);
            st.setString(3, data);
            st.setInt(4, quantidade);
            st.setDouble(5, cb.calculaValorTotal());
            st.setInt(6, matricula);
            ret = st.executeUpdate();
            st.close();
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return ret;
    }

}

Método de Calculo
    public double calculaValorBrinquedo() {
        return quantidade * Brinquedo.preco;
    }

    public double converterDesconto() {
        return (100 - Brinquedo.getDesconto())/100;
    }

    public double adicionarImpostos() {
        return calculaValorBrinquedo() + (Brinquedo.preco * impostos);
    }

    public double adicionarLucro() {
        return adicionarImpostos() + (Brinquedo.preco * lucro);
    }

    public double calculaValorTotal() {
        return valorTotal = adicionarLucro() * converterDesconto();
    }

Tentei esse código mas ele fica apenas registrado 220.
Answer: Karlos, não entendi muito bem o que você quer fazer. Porém vou tentar explicara aqui. Caso não entenda pode mandar sua dúvida novamente.
1- Não sei quais dados você quer calcular, mas disse que eles estão no banco. Então faça uma consulta no banco (na sua classe DAO) em um método que tem o retorno do tipo do dado que queira buscar.
2- Em sua classe de cálculos, chame o método da classe DAO para realizar de fato a consulta e retornar o valor que queira, exemplo:
int idade = dao.buscaIdade()

3- Em seu método de cálculo receba o valor como parâmetro,
exemplo:
public void calculaSalario(int idade){
   //....... cálculo aqui
}

4- Guarde o valor do calculo em uma variável.
5- Para registrar no banco o valor do cálculo, receba o valor como parâmetro do método na sua class DAO, exemplo:
public void insereValorCalculado(double salario){
   //...... sql aqui
}

Se ficou difícil de entender, edite a sua pergunta novamente!!
Abç!!


How to improve the speed of drupal website

Question: I have tested my site with testmysite.thinkwithgoogle.com. I got the below report. Speed test score for mobile site and desktop site are not good.  If you could help me pointing to right direction to fix this errors and bring the score higher, it would help me a lot. Resources they provided are in general. I am looking more drupal specific resources.
MOBILE FRIENDLINESS
98/100
GOOD
MOBILE SPEED
57/100
POOR
DESKTOP SPEED
52/100
POOR

Update New result:
Comment: I mean, the pointers are in the report... this is kind of too broad otherwise
Answer: First of all, I would recommend you a very popular module: https://www.drupal.org/project/advagg . This is better than the standard aggregation in Drupal, you need to configure it a bit after you install it.
For the images, you can you something like this: https://www.drupal.org/project/imageapi_optimize . This will optimize your images and should help you pass that.
Comment: I will follow your advise and test. I will let you know the result.
Comment: I used the two modules you recommended. I got better score. How can I have higher score than that?
Comment: @Drupol see http://drupal.stackexchange.com/questions/107311/eliminate-render-blocking-javascript-and-css-in-above-the-fold-content/107332#107332


Search and append text at the end of the line

Question: I have a file in which there is a command on each line. Within the command there is a line which is always P0......xml. I want to append that P0.... to the end of each line with a >> operator in front and .log at the end.
For example,
If a command looks like this:
abcdefg hijkl mno P0qrstuv.xml wxyz abc

I would like to make it:
abcdefg hijkl mno P0qrstuv.xml wxyz abc >> P0qrstuv.log

Please explain your answer as precisely as possible.
Answer: One solution would be to use the substitute command in Ex mode. This should do it.
:%s/\v(P0.+\.xml).*/& >>\1.log/

: puts you into Ex mode
% act on the whole file
s does the substitution
\v specifies that the regex will "very magic" and not the regular vim regex.
(P0.+\.xml) grouping of text the file name
& inserts what was matched
\1 inserts the first grouping (if you would have more than one you could do \2 \3 etc..)
Comment: I believe you want `%s/\v((P0.+)\.xml).*/& >>\2.log/`


Pointer to function with template arguments

Question: How do I create this, without creating a structure?
template <class T>
typedef bool (* FunctionPointer)(T*, T*);

Answer: Using using:
template <class T>
using FunctionPointer = bool (*)(T*, T*);

Live example
Comment: Even better: `template  using Function = bool(T*, T*)`, and then you can spell out `Function * p`. It's polite not to hide pointers in type aliases...


How do I change the simple form below run to Ajax with PHP?

Question: I need to change the form whose markup and php code is as seen below to operate without loading the page. So it will be an Ajax PHP form. I'm pretty new to ajax. Someone please guide me on how to go about        it. I'll be very grateful.
Please note that a copy of the form data filled out by the visitor should be emailed to the visitor.
MARKUP IS AS BELOW:
<!DOCTYPE html>

<meta charset="utf-8" />
<title>Contact form to email</title>

<form action="contact.php" method="post" name="myemailform">
Enter Name: <input name="name" type="text" />
Enter Email Address: <input name="email" type="text" />
Enter Message:<textarea name="message"></textarea>
<input type="submit" value="Send Form" />
</form>

<meta charset="utf-8">
<title>Contact form to email</title>

<form method="post" name="myemailform" action="contact.php">

Enter Name: <input type="text" name="name">

Enter Email Address:    <input type="text" name="email">

Enter Message:  <textarea name="message"></textarea>

<input type="submit" value="Send Form">
</form>

PHP CODE IS (contact.php):
<?php
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];

$email_from = 'email@example.com';

$email_subject = "New Form submission";

$email_body = "You have received a new message from the user $name.\n".
                        "Here is the message: $message.\n";

$aEmails = array();
$aEmails[] = 'firstname.lastname@example.com';
$aEmails[] = $visitor_email;

$headers = "From: $email_from \r\n";

$headers .= "Reply-To: $visitor_email \r\n";

foreach($aEmails as $aEmail) {
mail($aEmail,$email_subject,$email_body,$headers);
}

?>

THE JS CODE:
$('form#myemailform').on('submit',function(e){
$.ajax({
    type: 'post',
    url: 'contact.php',
    data: $('form#myemailform').serialize(),
    success: function (res) {
alert(res);
}
});
e.preventDefault();
});

Thanks in advance.
Answer: Give the id in your form and pass it through ajax something like this:
$('form#myemailform').on('submit',function(e){
$.ajax({
        type: 'post',
        url: '/your/php/page/path',
        data: $('form#myemailform').serialize(),
        success: function (res) {
            alert(res);
        }
    });
    e.preventDefault();
});

In your PHP page you can access all your POST variables. And you are ready to go...
PS: There must be JQuery library imported before running this script.
Comment: Thanks Ronak. But my page is still loading. Please check how have done it above.
Comment: change this: ``
Answer: An example for you

Answer: I would try the following:


How to draw the domain of this function.

Question: $$
\frac{\sqrt{x^2-y}}{\ln(1-x^2-y^2)}
$$
I see, that the domain is real, but:
$$
1) x^2\geq y
$$
and
$$
2) x^2+y^2<1
$$
and
$$
3) x^2+y^2 \ne0
$$
I can draw 1 and 2, but how to draw 3) ?
Comment: If the sum of two non-negative numbers is zero, what does that say about those nunbers?
Comment: do you mean, that I should exclude the point (0,0)?
Comment: @amWhy Surely you don't mean to say the domain is the whole plane without the origin... there are the other two constraints, of course...
Comment: @rschwieb It gets confusing when discussing the domain in contrast to the Image of f(x,y). And I wasn't looking at the original function! (at the top)!
Comment: Normally, we say a domain is "real" if the domain is a subset of $\mathbb R$. In this case, that isn't true, so the domain isn't "real" under any definition that I've heard of.  Rather, the domain is a subset of the "real plane."
Comment: To put it succintly, to draw 3) just undraw the origin :)
Answer: Well, the domain is real in the sense that it's the real plane $\mathbb{R}^2$.
3) is the easiest of them all... it's all of the plane except the origin!

The last step would be to look at what the intersection of all three regions would be. Thta is, all three regions determined by your constraints.
The first one gives you the region under a certain parabola, the second one gives you the interior of a certain circle, and the last one we have discussed.
It's a strange shape... try to sketch it!


Partial Measures with Matching Ending Measure

Question: In a hymn I am working on, the first measure is partial and has only an eighth note, but the Time Signature is 6:8.  Someone told me that the ending measure should also be offset in reverse to make up for it so that the first and last measure add up correctly.
[Disclaimer: I'm learning music theory as I go...]
First measure:

Last measure:

Is that right?
Problem is that in Lilypond if I do that, the measure never closes with a full bar.  Isn't it supposed to end with a full bar?
Here is the alternative:

[SOLVED]
Dave's answer below solves the display issue for Lilypond, whilst MattPutnam's answer described the use of the partial measure in the Finale.  I wanted to post the results of the output, though:
Comment: Every modern hymnal would put a double bar at the end of the hymn (and no repeat sign, ordinarily). Compare #218 in *The United Methodist Hymnal* (1989), "It Came Upon a Midnight Clear."
Comment: I've had lots of issues with this in Finale as well. Everyone will know what you mean if you either: 1) use first and second (...) endings 2) just fill the final measure with 6 beats, which is easier but less accurate.
Comment: I've tried a measure with 6 beats, and I've tried a measure with 5.  If I use a complete measure it serves the me the double bar.
Comment: For a hymn where the music will be repeated, it makes sense to follow this traditional practice of balancing the opening and closing bars (it really is a convention from Haydn-era dance music, like minuets).
Answer: LilyPond places bars automatically on full measures.  The partial bar at the end of a stanzaed piece with pickup, however, wants a double bar line (different from the default) anyway.
So you'd write it: d4.~ d4 \bar "|." and LilyPond will place the ending bar line wherever it currently happens to be within the measure.  You don't need to fiddle with the timing in any way.  Just be sure not to write the usual | bar check at the very end of the music.  It does not produce any graphical output but just is in the music in order to check that a full measure has been completed regularly.  And at the very end, it hasn't.
Are you sure you'd not rather consult the LilyPond user list?
You are likely to ask a lot more questions where the answers are just part of your general learning curve, covered already in LilyPond's introductory tutorial and will not really help others in any manner since they do not rise to the level of an actual problem not answered by reading any introductory text.
Answer: You can use an s8 to fill out the measure, and cause the barline to draw.  The s a spacer note -- it takes up time, but doesn't result in anything displayed.
As far as requiring the partial bar at the end: it is my impression that the degree to which it is required is somewhat genre dependent: I've never seen traditional music, or hymns for that matter, where the partial bar wasn't used, however, MattPutnam is (probably) right in that it isn't always required, and probably wouldn't be too confusing.
Comment: You could put in an explicit `\bar "|."`
Comment: I was thinking of doing this, actually.  A spacer note allows for the proper (? aesthetics only according to MattPutnam's answer) display of the offset, and still fills the measure for Lilypond.  I think this is the right answer.
Comment: Actually, when I do this, it completes perfectly - even better than using the half note like in my example.
Comment: I'm not an expert, but I think you are right about it being genre dependent.
Comment: Escept, I guess, that I'm supposed to have a double bar at the end!
Answer: I disliked the aesthetics of using the spacer method, because it left too much space at the end of the measure. So I wrote this function:
end =
  #(define-music-function
    (parser location signature)
    (fraction?)
  #{
    \once \omit Staff.TimeSignature \time #signature
  #})

and then all I have to do is, for example:
\end 3/4 g4 g r \bar "|."

and it displays the last measure correctly without extra space at the end:

I'm not sure what that will do to beaming, to be honest, but I haven't run into problems yet. Presumably the some code can be added to the function to get correct beaming.
Thanks to MattPutnam for the inspiration.
Answer: I think it's not essential that the last measure compensate for the pickup.  I certainly wouldn't be confused or bothered at all by the lack of it, and it might actually confuse people who are new to music.  It doesn't provide any benefit other than aesthetics.
In Finale I would do this by making the last bar a 5/8 bar and having it display as a 6/8 bar so it doesn't generate a time signature change.  My Lilypond skill is weak, but according to this you should be able to make the tine signature invisible.
Comment: Is there a rule for the pickup?  How important is it (you said not essential)?  Really, its just aesthetics!?


Where to place a helper/util function in Spring MVC architecture

Question: I want to know which is the best way to implement a helper function for unzip file in Spring architecture.
For example:

I have the controller where I catch the request to unzip a specified file;
In controller endpoint I make some checks about request and file requested;

And now, I want to know if is much better to have flow like:

MyController -> FileService -> FileServiceImpl -> unzipMethod();
MyController -> FileService -> FileServiceImpl -> FileUtils -> unzipMethod();
MyController -> FileUtils -> unzipMethod().

I'm not sure which of this is the best practice. Can you give me some advices? :)
Answer: My advice would be to Create a util class in .utils package and create a static method unzipMethod() inside that.
and then call from anywhere by using className.methodName()
Answer: Why do you want to use a static method? Wouldn't it better to create a new class that will represent a file? This class can receive a path to the zip archive as a constructor parameter and then it can have a method to unzip the file. Class has a few advantages prior to static method: you can easily test it and you can easily mock it in unit tests.
P.S. You can find more info about "true OOP" here and here.
Answer: Make @Service class for your endpoint and in that service use FileUtils -> unzipMethod(). unzipMethod can be static.
Its good to have service class for your endpoint as in case of some conditional work or processing with unzip file your service can accommodate it.
Answer: I would go with the 2nd option because it will be good according to oops principles and will be independent and reusable.
You might want to have more business logic in future so it is good to have the service and service impl and also you might need the unzip functionality somewhere else in your project so it is good to keep it separately in a util file.


Caracter estranho no início das páginas de site

Question: Estou desenvolvendo um site em PHP e MYSQL e todas as páginas estão exibindo os seguintes caracteres no início da página:
Cada página (index, sobre, contato...) ao ser aberta possui no canto superior esquerdo, bem no topo, essa sujeira. Já tentei mexer em codificação das páginas, banco de dados, nada resolveu.
Alguém consegue me ajudar?
Comment: pelo que descreve, o mais próximo que posso deduzir é "utf8 bom". Remova o utf8-bom:  http://pt.stackoverflow.com/questions/31971/php-file-retorna-unknown-char-entre-cada-letra/31976#31976
Comment: Coloque o código de pelo menos uma pagina
Answer: Tive este problema e resolvi abrindo o arquivo PHP no Notepad++ e fui na Aba Codificação (Encoding) e salvei o arquivo em UTF8 sem bom.
Comment: Se vocÇe estiver usando o Dreamweaver abra a janela de "Preferências" (ctrl+u) no item novo documento e tire a seleção 'Incluir assinatura Unicode (BOM)'.
Comment: Obrigado. Resolvi definindo a codiicação de cada arquivo como UTF-8. Com isso comecei a ter erros ao exibir na tela informações vindas do banco. Mesmo o banco de dados estando codificado em utf-8. Coloquei um "utf8_encode($variavel)" antes de 'printar' qualquer conteúdo e resolveu.


assign cell to coordinates in a 3 by 3 grid

Question: I am reading some coordinates from a file and trying to assign them cell values (0-2) by diving them into a 3x3 grid. For some values the code is assigning negative cell values like for x=268 or x=269. Where am I going wrong?
I have file output.txt as follows with :
76 62
77 62
78 62
79 62
81 62
83 62
86 62
etc

The code to assign cells:
int x_points[99];
int y_points[99];
int i=0;
int x,y;
int max_x, max_y;
int min_x, min_y;

while(out.good())
{
    out>>x;
    out>>y;

        if(i==0)
{
  max_x=x;
  min_x=x;
  min_y=y;
  max_y=y;
 }
 else if (x>max_x)
 {
    max_x=x;
 }
 else
 if(x < min_x)
 {
   min_x=x;
 }
else if (y>max_y)
 {
    max_y=y;
 }
 else
 if(y < min_y)
 {
   min_y=y;
 }
x_points[i]=x;
y_points[i]=y;
i++;
}

for(i=0; i<99; i++)
cout<<x_points[i]<<","<<y_points[i]<<"\n";

int cells_x[99];
int cells_y[99];

float x_width;
float y_width;
int divide = 3;

//To find out the cells. Divide it by 20

x_width=(max_x-min_x)/divide;
y_width=(max_y-min_y)/divide;

cout<<"\nx_width:"<<x_width;
cout<<"y_width:"<<y_width<<"\n";

int x1;
int y1;
for(i=0; i<99; i++)
{
x1=x_points[i]-min_x;
y1=y_points[i]-min_y;

    for(int j=0; j<divide; j++)
    {
        if(j*x_width<=x1 && x1<((j+1)*x_width))
            cells_x[i]=j;

        if(j*y_width<=y1 && y1<((j+1)*y_width))
            cells_y[i]=j;
    }
    cout<<cells_x[i]<<" "<<i<<" "<<cells_y[i]<<"\n";

}

Comment: You would probably find it easier to debug your code and spot mistakes if it were formatted properly.
Comment: I don't know how to format it in stackoverflow. but ill try to improve my formating further.
Answer: The first problem I see is where you try to find the maximum and minimum values of x and y:
if(i==0)
{
    max_x=x;
    min_x=x;
    min_y=y;
    max_y=y;
}
else if (x>max_x)
{
    max_x=x;
}
else if(x < min_x)
{
    min_x=x;
}
else if (y>max_y) /* <-- This should not have an else! */
{
    max_y=y;
}
else if(y < min_y)
{
    min_y=y;
}

As written, it prevents the analysis of y values when an x is a new max or min. This will cause issues with the rest of your program, since max_y and min_y don't actually contain the max and min.
Next up is calculating the x_width and y_width:
x_width=(max_x-min_x)/divide; // should be x_width=(max_x-min_x + 1)/divide;
y_width=(max_y-min_y)/divide; //           y_width=(max_y-min_y + 1)/divide;

If max_x = 8, and min_x = 0, your code would result in x_width = 8/3, or about 2.6666666666666666666666666666667. But 0-8 can be split up into 3 groups of 3. Adding 1 corrects this by calculating the number of points, not the length of the line.
It also prevents you from having a width of 0, which would happen if max_x == min_x. A width of 0 causes trouble in the next section:
for(int j=0; j<divide; j++)
{
    /* an x_width of 0 will cause this to never evaluate to true */
    /* x1 cannot ever be >= to 0 AND < 0 */
    if(j*x_width<=x1 && x1<((j+1)*x_width))
        cells_x[i]=j;

    if(j*y_width<=y1 && y1<((j+1)*y_width))
        cells_y[i]=j;
}

if x_width is zero, then you will never assign a value to cells_x[i], meaning it will still be set to its initialization value, which could be a negative number.
Comment: sorry but when i run the debugger it does contain the respective values.
Comment: Can you attach the actual output you see?
Comment: I have corrected the code but I didn't account for xwidth=0. thanks a million for that one. this should work now.
Comment: could u give a +1 if u liked the question?


How to remove a web site from google analytics

Question: I am Administrator of several web sites on google analytics.
Can i delete some of them?
If yes, how?
Many of you suggested me to remove my profile. So my doubts are:
1. I am administrator of several items. I want remove just some of them.
2. If I remove my profile I will lost all items?
Comment: http://support.google.com/analytics/bin/answer.py?hl=en&answer=1009698
Comment: possible duplicate of [How to remove a website from Google Analytics](http://stackoverflow.com/questions/10303991/how-to-remove-a-website-from-google-analytics)
Comment: @PranavKapoor, I don't want to Add/modify/delete account administrators. I just want to remove a web site from google analytics. I uploaded a picture to make me more clear.
Comment: I did GA consulting and had a similar situation when other admins made me an admin. I couldn't delete the account from my list. I had to contact them to remove me as an admin on their account.
Answer: Here's an updated answer, as of Sept. 2013. This took me awhile to figure out.

Go to the Admin tab.

In the middle column, select the web property that you want to delete from the dropdown.

In the right-hand column, click on "View Settings." ("Property Settings" in dec. 2015)

At the bottom of the next page, select "Delete this view."

It will warn you that you're about to delete all of the data associated with this property. If you're sure, confirm.
Done!
Comment: Intuitive it ain't ;-)
Comment: +1 for pictures. It's hard to understand this just by looking at text directions.
Comment: @DilbertDave: +1 it's as intuitive as most of Google apps. :-)
Comment: They change the options all the time. Now, it has rubbish bin option.
Comment: these days its called rubbish bin for deletion :)
Answer: UPDATED ANSWER
Google Analytics Admin panel has 3 panels, wherein deleting can be done on any of the following :

Account (Contains multiple properties, and views)
Properties (Contains Views, a subset of Account)
Views (subset of properties)

Deleting an Account
Deleting the account, will remove all data pertaining to that account, along with all properties/profiles it contains. This is (usually) as good as removing the entire website data.
To delete the account, follow the following steps : (refer to image below)

Choose the account you want to delete.

Click on Account Settings

Bottom right, a small link that says delete this account.

You will get a confirmation, if you are sure to, click Delete Account
It will give you details, and will confirm deletion (and provide additional info like to remove GA snippet on your website, etc)

Note : If you have multiple accounts linked with your login, the other accounts are NOT touched, only this account will be deleted.

Deleting a property
Deleting a property will remove the selected property, and all the views it holds.
To delete a property, delete all views it contains individually (see below for deleting views)

Choose the property

All profiles related to that property appear on the right
Delete all the views related to the property individually (details in next section).

Deleting a View (profile)
Deleting a profile will remove only data pertaining to that view, if there is a single profile, the property is automatically deleted.

Choose the profile you want to delete

Click View Settings

Click on delete View (Bottom right)

Click Confirm, and that view will be deleted. If there is only a single view in the property, that property gets automatically deleted.

I want to keep the data, but not see them in the list
Sometimes you have a lot of websites, which you want to keep the data, but remove them from the list, since you don't view them often. I thought of a workaround, in case you do not want to delete the data.
Use another account.

Say, your primary account is A, and you make another account B.
Make B an administrator from A
Remove A

Since A was your primary account, you no longer will be able to access it from the list!
And you still have your data saved, just that you'll have to log in via the other (spare) account.

Previous Answer :
These are the steps to delete a profile from Google Support page :

Delete profiles
Remember, too, that when you delete a profile, you also delete all data associated with that profile, and it is not possible to retrieve that deleted data.
To delete a profile:

Click the Admin tab at the top right of any Analytics page.
Click the account that contains the profile you want to delete.
Click the web property from which you want to delete the profile.
Use the Profile menu to select the profile.
Click the Profile Settings tab.
Click Delete this profile at the bottom of the page.
Click Delete in the confirmation message.
Comment: @LorraineBernard : You can remove a either remove a profile, or a user from an analytics account. You **cannot** remove items from the list without removing yourself from that account/profile.
Comment: I don't want to delete an account administrator. I just want to delete a site from the list.
Comment: The issue is 1) I am administrator of several items. I want remove just some of them. 2) If I remove my profile I will lost all items?
Comment: Profiles have been renamed to 'views' - please update the answer.
Answer: Updated Answer (July 22, 2015)
The solution to delete an Account/Property/View is still very similar to @Pranav 웃's answer. Google has just moved a few things around, so I thought I would update.
Step #1
Click Admin Tab at the top of the page

Step #2
Once you are on the Admin Page, You need to decide if you want to delete the Account, Property, or View. Make sure to select the desired Account, Property, or View from the Drop Down Menu.
In the following pictures, I will show you how to delete the Account, which removes all information including Properties and Views under that particular account.
Click Account Settings to remove Account, Property Settings to remove Property, and View Settings to remove View.

Step #3
On Account Settings, you will notice a button 'Move to Trash Can'. You will click this to remove the Account, Property or View. You will have to verify Moving the Account to the Trash Can on the next page/picture.

Step #4
When you have verified this is the account you want to delete, go ahead and select 'Trash Account'.
Note: When you Trash an Account it moves all the information to Admin/Account/Trash Can, where it can be recovered within 1 month. Keep in mind that every Account has its own Trash Can. Once that time has lapsed the Account, Property or View will be deleted FOREVER!

Hope this helps someone in the future, since I just struggled trying to figure it out even though its pretty simple now.
Comment: Additional Note: Permenant deletion takes 35 days. Source: https://support.google.com/analytics/answer/1009696?hl=en
Answer:
To delete a web property, you simply need to delete every profile within the property.  Once the last profile has been deleted, the web property with cease to exist in the GA account.  That's all there is to it! -- Source
Answer: After Much Fannying about, deleting this that etc, I found the way to delete a "website" from your list (which is, in fact what the original question was - minus all the flaffing) is

Select the Account (Website) that you want to delete
In the first column (left hand one)
Click Account Settings
Down the bottom, it says Delete this account.

That's it… Done.
Remember: for this exercise only Account means Website.
Answer: You can also do in this way :
select your profile then go to admin => in admin second column "Property" select the site you want to remove => go to third column "view settings" clic => on the right bottom you ll see delete the view => confirm and it s done , have a nice day all
Answer: Feb 2016 version: Admin tab, then select Property in the middle column, click Property Settings, then the Move To Trash Can button at the top right. No need to delete individual views.
Answer: Update 26/03/2016:
Instead of a link in the bottom right corner of the Settings form, the delete button is moved to the top right corner, saying:
Move To Trash Can

When you click on it, it will ask you for confirmation and move it to Trash Can.
Comment: In some cases the button reads 'Move to rubbish bin' instead.
Answer: What the OP wants to do, is delete additional properties in his Google analytics.
Properties that are not his but belong to someone else.
Apparently, the only way to do this, is to contact the owner of that website who is the administrator, and asked them to remove you.
Or you can just create a new Google account, and add your properties to the new account.
None of these are real good solutions. Thank you Google for caring so much about SEO people.
To add insult to injury, if you go over 25 accounts, you must contact Google to get permission to add another.
Lesson learned: Do not add other peoples websites to your Google analytics account. Create a separate account so that if you have to start over, you don't lose any data from your websites. It's also good to have more than one Google analytics account.
Answer: AS of 2018
Login to your analytics account
Select the account/property you want to delete
Click the  button. (left side bottom menu)
Click on property settings
To the right you will see Move To Trash Can Click on that
You will see the bellow screen. click on Delete Property button

or if you want to delete the account
follow the same steps, but this time click on the Accoutn Settings tab  see below
Now Click on Move to Trash Can (button to the right)
when you see the next screen confirm to delete the account by clicking on the Trash Account button.
How to delete a website from google analytics


symmetric r.v. raised to an odd power

Question: My prof claims that raising a symmetric r.v., like N(0,1), to an odd power gives a distribution with expectation 0.  What's the best way to see this?
Comment: Symmetry and the law of the unconscious statistician. But a word of caution: "...like a N(0,1) random variable..." is sloppy, imprecise wording on the part of your professor. Such a statement is not, in general, true for any old symmetric distribution. The requisite moments must exist (be well-defined) in the first place.
Comment: This assertion is false unless a particularly narrow interpretation of "symmetric" is adopted (and even then @Cardinal's admonition must be heeded): see http://stats.stackexchange.com/a/29010 for more about this. For *familiar* counterexamples in Cardinal's spirit you may contemplate what happens with any Student $t$ distribution with $\nu$ degrees of freedom and you use any odd power greater than or equal to $\nu$.
Comment: This question appears to be a duplicate of http://stats.stackexchange.com/questions/28992/what-is-the-definition-of-a-symmetric-distribution/29010#29010.
Answer: The assertion that a symmetric random variable raised to an odd power has mean 0 is not true in general.
(However, it is true that a standard normal raised to an odd power has mean 0.)
To make a general statement, first we'll need to restrict the original variable to have mean zero. That is, our statement would start "a symmetric random variable with mean 0, raised to an odd power..."
Then, we also need the expectation of that odd power to be finite; this is not the case in general. Consider for example the 5th power of a t-distributed random variable (with $\nu=3$, say$).
[Edit: I've only just noticed that whuber offers the same distribution as a counter example (but as a class of distributions, not just a single combination of power and df).]
The integral doesn't converge to a finite number. Since we have symmetry, if $\int_{0}^\infty x^p f(x) dx$ is finite (equal to $a$, say), then the mean of the odd power will be 0 by symmetry:
$E(X^p)=\int_{-\infty}^\infty x^p f(x)\, dx\:$ (law of the unconscious statistician)
$\qquad\quad=\int_{-\infty}^0 x^p f(x)\, dx +\int_{0}^\infty x^p f(x)\, dx$
$\qquad\quad=\int_{-\infty}^0 x^p f(-x)\, dx +\int_{0}^\infty x^p f(x)\, dx\:$ (by symmetry of $f$)
Then let $y=-x$, $dy=-dx$ (watch the negatives carefully, you get three come into it)
$\qquad\quad=-\int_{0}^{\infty} x^p f(x) dx +\int_{0}^\infty x^p f(x)\, dx$
$\qquad\quad=-a+a=0$
Comment: +1. A more elementary, yet elegant and fully general demonstration, perhaps sheds additional light on the issue.  Note that when $X$ is a symmetric variable (about $0$) then $X$ and $-X$ must have the same distribution.  (This could be taken as a [definition of "symmetric."](http://stats.stackexchange.com/a/29010)) When $n$ is a positive odd number, then (*assuming $X^n$ has an expectation*) it is almost immediate that $$\mathbb{E}(X^n)=\mathbb{E}((-X)^n)=\mathbb{E}(-X^n)=-\mathbb{E}(X^n).$$ Thus the only value $\mathbb{E}(X^n)$ could possibly have is $0$.
Comment: Thanks Glen.  I had already posted that answer in a closely related thread at http://stats.stackexchange.com/questions/28992/what-is-the-definition-of-a-symmetric-distribution/29010#29010, so no need for more than a comment here. I believe the finiteness of expectation is neither the focus of the original question nor the real point of the solution: it is needed only to describe the circumstances under which the assertion in the question is true. As you know, there are many threads on this site that discuss finiteness of expectation.
Comment: @whuber yes, it's certainly much more enlightening than my own post, but it doesn't quite address the issue of what is needed for the expectation to be finite, which I think is important to raise. Still it would be easy to add that to what you have there, and then I think you'd have a top-notch answer..

symmetric r.v. raised to an odd power


jQuery :not(:checked) not working?

Question: I have the following HTML:
<form class="pricing-downloads-right pricing-last-form" action="">

        <input class="pricing-single-level" type="radio" name="sex" value="male">Single Level Download $49.95: Choose a single level (1 to 7) and receive access to all lessons, PDFs and review audio for that level, plus 30 days of online access ($80 value). Email us your level choice after purchase.

        <input class="pricing-3-level-download" type="radio" name="sex" value="male">3 Level Download $99.95: Choose any 3 levels (1 to 7) and receive access to all lessons, PDFs and review audio for those levels, plus 60 days of online access ($190 value). Email us your level choices after purchase.

        <input class="pricing-all-access-package" type="radio" name="sex" value="male">All Access Package $199.9: Receive access to all lessons, PDFs and review audio for all 7 levels, plus 90 days of online access ($300 value).

Which level would you like? (Click all that apply)

        <input type="checkbox" name="vehicle" value="Bike">Level 1

        <input type="checkbox" name="vehicle" value="Bike">Level 2

        <input type="checkbox" name="vehicle" value="Bike">Level 3

        <input type="checkbox" name="vehicle" value="Bike">Level 4

        <input type="checkbox" name="vehicle" value="Bike">Level 5

        <input type="checkbox" name="vehicle" value="Bike">Level 6

        <input type="checkbox" name="vehicle" value="Bike">Level 7

</form>

and jQuery:
jQuery('.pricing-downloads-right input[type=radio]').on('change', function(){
    if(jQuery('.pricing-levels-top-2 input.pricing-single-level:checked').length > 0){
          //since you don't want to target by name
          jQuery('.pricing-levels-2').show();
    }
});

jQuery('.pricing-downloads-right input[type=radio]').on('change', function(){
    if(jQuery('.pricing-levels-top-2 input.pricing-single-level:not(:checked)').lenght > 0){
           //since you don't want to target by name
           jQuery('.pricing-levels-2').hide();
    }
});

So I want .pricing-levels-2 to display when input.pricing-single-level is checked and to hide when it is unchecked.
Right now .pricing-levels-2 displays when input.pricing-single-level is checked but it doesn't hide when unchecked.
What I am doing wrong?
Comment: How do you know which value is selected from Level 1 to Level 7 when all your values for checkbox have the same value, "Bike"
Comment: Change the value of the checkbox.. Mentioned checkboxes will yield only "Bike"
Answer: Try
jQuery('.pricing-downloads-right input[type=radio]').on('change', function () {
    jQuery('.pricing-levels-2').toggle(jQuery('.pricing-levels-top-2 input.pricing-single-level:checked').length > 0);
}).change();

Demo: Fiddle
A possible better way
jQuery(function ($) {
    var $pl2 = $('.pricing-levels-2');
    var $psl = $('.pricing-levels-top-2 input.pricing-single-level');

    $('.pricing-downloads-right input[type=radio]').on('change', function () {
        $pl2.toggle($psl.is(':checked')); // $ps1[0].checked
    }).change();

})

Demo: Fiddle
Answer: you misspelled length:
if(jQuery('.pricing-levels-top-2 input.pricing-single-level:not(:checked)')
    .lenght > 0){

should be
if(jQuery('.pricing-levels-top-2 input.pricing-single-level:not(:checked)')
    .length > 0){

Comment: Oh, it was a grammar problem, not a programming problem.

jQuery :not(:checked) not working?


show users connected to windows telnet server

Question: I can't believe how bad I am at googling windows stuff. How can I list the users connected via telnet to a windows machine? It seems such a basic question, yet I couldn't find a answer. X-(
Also, after I list the users, is there a way to kill a specific user's connection? how?
I'm on a windows server 2003.
Comment: In before "ZOMG TELNET" comments!!
Answer: The command tlntadmn -s  will list information about the current Telnet sessions. This will display something like the following:
C:\Windows\system32>tlntadmn -s
1 telnet session(s)

ID    Domain     UserName      Client     LogonDate LogonTime   IdleTime
                                                               (hh:mm:ss)
--------------------------------------------------------------------------
2396  HORACE     jscott        ::1        7/7/2014 10:02:43 PM  0:01:04

You can end the session using tlntadmn -k ID. Using the above example tlntadmn -k 2396.  tlntadmn -k all to terminate all telnet sessions.


RHEL expand disk size

Question: Notice: I know this type of question has been asked (many times) before, but I have some remarks about the provided answers.
I run a RHEL (7.1) VM on Hyper-V. The VM has 2 IDE disks attached. I need to expand the second disk from 80 GB to 160 GB, so I expanded the disk in Virtual Machine Manager. Now there's some stuff that needs to be done on the Linux side.
Most solutions I've read boil down to this:

Create a new primary partition with fdisk /dev/sdb
Set partition type to LVM (0x8e)
Create a new Physical Volume (pvcreate)
Extend the Volume Group with the new PV (vgextend)
Extend the Logical Volume (lvextend)
Extend the filesystem (xfs_growfs)

An other solution is adding a second disk and adding that disk to the Volume Group. We don't want to go that route and keep only those 2 disks.
This all works great, I've done it before. Now I'm wondering if it's possible to extend the already existing partition (e.g. sdb1) instead of adding a sdb2, because as far as I remember there's a limit on the number of primary partitions? Imagine: what if I need to expand this disk 5 times? Then I have 6 primary partitions.
parted is not an option anymore, because they removed the resize and move commands. GParted could be a solution, but then I have to boot the VM with the GParted live CD, and I want to avoid that.
What are your thoughts?
Answer: Yes!
use partition tool like parted or fdisk. Remove the original partition of the partition on which you have the PV created on, but remember the start and end cylinder/block on there and be sure that you make your new partition start on same place and use more than the original size else you mess up the filesystem on there.
having done that, it is posible that the new partition size will be detected with tool like partprobe, but if it's on the fs mounted on /, then a reboot may be necessary to detect the new partition size. I don't remember.
So having done that, it should now be possible for you to follow the remaining steps from your list.
I have a tip though:
If the whole disk is a PV (ie no partition table on there), then next time when growing the filesystem, there you can just skip to step 4.
Comment: Thanks for your input. Removing the partition was another option I forgot to mention.Deleting "stuff" always seems risky. Also, I didn't know I could add a whole disk as a PV to a VG. Good know!

RHEL expand disk size


Flag a node n days after its creation

Question: Similar to Drupal Answers, I'm creating nodes that are questions. Once I create a question node, I want to have it flagged as 'unanswered' if a user doesn't flag it as 'answered' within 10 days. I have Flags module setup so I can click 'answer/un-answer this question' on the node itself and Views displays the unanswered questions. I'm thinking that the Rules module will be of assistance here, but I do not see a way to start a timer (for lack of better words) in Rules once a node has been created.
Thank you.
Comment: Please note that you can use the "7" tag to flag questions as being about Drupal 7 instead of writing it in your question.  Tagging makes it easier for people to search for your question.
Answer: You'll need to enable Rules Scheduler, which is a sub-module included as part of the Rules module.
You can watch a screencast on how to use Rules Scheduler from Node One here.

Flag a node n days after its creation


Render link in twig with 'entity:node/n' as uri in array

Question: With the module "config pages" I've set some variables global to render in templates.
In mytheme.theme I've added a function:
function mytheme_preprocess(array &$variables, $hook)
{
    $myConfigPage = \Drupal\config_pages\Entity\ConfigPages::config('config_name');
    $variables['my_settings'] = $myConfigPage->toArray();
}

In the config_pages I've created a link field.
I would like to render them, but I get below output.
How can I render the link in Twig?
  ^ array:3 [▼
      0 => array:3 [▼
        "uri" => "entity:node/186"
        "title" => "Title 3"
        "options" => []
      ]
      1 => array:3 [▼
        "uri" => "entity:node/189"
        "title" => "Title 1"
        "options" => []
      ]
      2 => array:3 [▼
        "uri" => "entity:node/195"
        "title" => "Title 2"
        "options" => []
      ]
    ]

Twig:
  {{ dd(my_settings.field_links) }}
  {% for link in my_settings.field_links %}

      {{ dd(link) }}
      {{ link.uri|render }}
      {{ link.title }}

  {% endfor %}

None of above are working.
Answer: You can render a link with core's link function:

This helper function accepts as first parameter the text and as second parameter the uri
Examples:
{{ link(item.title, item.uri, { 'class':['foo', 'bar', 'baz']} ) }}

In your case, this might look like:
{% for link_item in my_settings.field_links %}

    {{ link(link_item['title'], link_item['uri']) }}
    // or
    {{ link("My link text", "entity:node/123") }}
    // or
    {{ link("My link text", "internal:/some/internal/path") }}
    // or
    {{ link("My link text", "route:my.module.route_name") }}
    // or
    {{ link("My link text", "https://drupal.stackexchange.com/") }}

{% endfor %}

Alternatively, and preferably imo, you can just render the field from the config_page entity (as with any content entity).
For example, in your preprocess:
// Load your config page.
$my_config_page = \Drupal::entityTypeManager()
  ->getStorage('config_pages')
  ->load('my_config_page_identifier');
// Build the render array for my links per the config page's `default` view mode.
$vars['my_links'] = $my_config_page->field_links->view('default');

Then, in twig:
{{ my_links }}

Comment: What do you mean you need to use the function split? You can pass `entity:node/123` straight to the link function, e.g. `{{ link('My link text', 'entity:node/123') }}`
Comment: Thanks. So far I understand, but I have "entity:node/123" as array variable. So in Twig I need to use the function 'split'. I was wondering if there isn't a better solution.... I don't like to use to much logic in twig...
Comment: Yes there is. See my answer
Comment: I was confused about the drupal_url() function, but indeed the core link function is what I need. Thanks for the support!
Comment: Also the update for the preprocess function is better. Config pages should have to update their documentation to use above.
Answer: {% for link in my_settings.field_links %}

      {{ link.uri|render }} => {{ link.url|render }} or {{ link.0.url|render }}
      {{ link.title }}

  {% endfor %}

use url instead uri as mentioned above


Python library that can read and write variable assignments inside Makefile files?

Question: I am looking for a solution that would allow me to modify Makefile files from inside Python.
I don't need any special functionality, usually I need only to change variables like: SOMETHING := value but I would prefer to be able to use an existing library than implementing my own, buggy, parser.
Comment: What's the problem you're really trying to solve? Maybe we can suggest a nicer alternative to parsing and modifying source code.
Comment: Yeah, you don't really want to try programatically parsing Makefiles.  Simple templating as suggested by Timo is your best bet...or just pass in values in the environment or on the command line.
Answer: Haven't heard of such Makefile oriented library for Python, but if you only need simple replacements such as SOMETHING := [something_placeholder], then you can just load the template file, replace the placeholder with your value and write it back to disk and give it to make.
Or you could use a templating engine such as Jinja2, but this would be yet another dependency for your application.
Answer: I would suggest to move away from Makefiles, if you want do things in Python.
Use waf or scons instead. They are build tools written in Python to replace Makefiles.
I'd rather use waf then scons, because it is faster and it works with the new Python versions (and some OS projects like ardour switched to it).
http://code.google.com/p/waf/
http://www.scons.org/
Here is a comparison of the two (and others like CMake, Ant):
http://code.google.com/p/waf/wiki/WafAndOtherBuildSystems#II._comparison_between_various_build_tools


how to fix getting undefined for model classes using sequelize?

Question: I am learning to use sequelize with my Next.js app.I set up the sequelize, used the cli to generate migrations, created the model (user) , and when i try to test it, going to the http://localhost:3000/api/app . i get an error -> Cannot read property 'findAll' of undefined.
my model class is coming up as undefined. anyone has any idea?
*director structure
MyApp
...
> database
 - db.js
> migrations
> models
 -user.js
> node_modules
> pages
  > api
     - app.js

db.js
const Sequelize = require('sequelize');

const db = new Sequelize('mydb', 'root', 'pass', {
    host: "localhost",
    port: 3306,
    dialect: 'mysql',
    operatorsAliases:false,
    logging: function () {},
    pool: {
        max: 5,
        min: 0,
        idle: 10000
    },
    dialectOptions: {
        socketPath: "/var/run/mysqld/mysqld.sock"
    },
    define: {
        paranoid: true
    }
});

db.authenticate().then(() => {
       console.log('connection error');
    }).catch(err => {
       console.log('Connection successful');
    });

module.exports = db;

model/User.js
module.exports = (sequelize, DataTypes) => {
    const user = sequelize.define("User", {
        id : {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            autoIncrement:true,
            primaryKey:true
        },
        firstName : {
            type: DataTypes.STRING(50),
            allowNull: false
        }
        lastName : {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        created: {
          type: 'TIMESTAMP',
          defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
          allowNull: false
        },
        updated:{
          type: 'TIMESTAMP',
              defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
              allowNull: false
         }
    });
    return user;
};

pages/api/app.js
const models = require('../../models')

export default (req, res) => {
   models.user.findAll();          //error => Cannot read property 'findAll' of undefined
};

Answer: You define uppercase User in the User.js file, so you have to use it uppercase:
const models = require('../../models');

export default async (req, res) => {
  const users = await models.User.findAll();
  console.log(users);
};

Comment: I think the main problem is in the Sequelize code, because it's not recognizing the `user` in models, that's why it returns `undefined` when you try to call the `findAll()` function, I thought uppercase `User` will help.
Comment: also running into this, any follow up?
Comment: Thanks @Tamas - I uninstalled/installed, added the files again still get the same undefined error. if you think of anything else , on to debug or test this let me know. thank you in advance


VPN is working, except for DNS lookups. Firewall (Cisco ASA 5505) issue?

Question: I've got the following set up:
LAN ->  DHCP / DNS / VPN server (OSX 10.6) -> Cisco ASA 5505 -> WAN

Connecting to the LAN via VPN works fine. I get all the details properly and I can ping any host on the internal network using their IP. However, I can't do any host lookups whatsoever. I've looked through the logs on and found this nugget in the firewall log:
3   Sep 08 2010 10:46:40    305006  10.0.0.197  65371           portmap translation creation failed for udp src inside:myhostname.local/53 dst inside:10.0.0.197/65371

Port 53 is DNS services, no? Because of that log entry, I'm thinking that the issue is with the firewall, not the server. Any ideas? Please keep in mind that I have very little knowledge and experience with this kind of firewall and the little experience I do have is with the ASDM GUI console, not the CLI console.
Comment: As a first step, verify that the VPN client is set to use your internal DNS servers for name resolution. On a Windows client you can check this by running ipconfig/all from a command line.
Comment: I've verified that all the settings are ok. Additionally, I've tried nslookup and specifying the server to be the internal DNS. Pinging any client on the internal network works, including the DNS server so it is indeed reachable. However, all attempts att name resolution ends with a time out. However, trying name resolution with an external server, such as googles, works just fine.
Comment: portmap translation errors indicate a problem with ip address translations. if you are using nat make sure you have an entry for both src/dst ip addresses; if you are using 'nat 0'the same is true.
Comment: [This question](http://serverfault.com/questions/433611/dns-through-cisco-vpn) seems similar in nature.
Comment: Sorry to say but if you don't know how the firewall works, please leave your fingers out of it. In the end you will have gigantic security hole. That said, there is an option in ASDM that shows you what commands are being pushed to the ASA when clicking "Apply", so that might be a possibility to learn what it's doing, since ASDM is doing nothing more than create CLI commands which it sends to the ASA.
Answer: 1) Are your clients establishing the tunnel directly with the ASA or with the "VPN server" in your diagram?
2) Are your VPN clients being given the same IP range as your internal network or a separate range?
Based on the log entry, it sounds like your clients are establishing the tunnel to the ASA and given a different subnet than the internal network.  If this is the case, I think you need a NAT exemption rule on your ASA to tell it not to try and NAT traffic between your internal IP range and your VPN IP range.  This preserves your source (VPN subnet) and destination networks (internal subnet) so the ASA doesn't think it needs a public/private NAT rule for access to the internal network based on the 2 interfaces it is seeing the traffic come through on.  In the GUI this is under: Configuration tab>>Firewall>>NAT Rules although I've had mixed experiences making rules like this in the GUI - might have to go to the CLI.
Comment: 1) Not with the ASA. 2) Same IP range. I think you may very well be right. However, I can't really make sense of the GUI either.
Comment: I'm not sure I'm getting this correctly, should I make an exempt rule going from inside-network/24 to inside-network/24? I tried, but it didn't work. Log still shows the same errors.
Answer: In my experience this should work with the out of the box config of the ASA.  Check for any DHCP settings on the ASA that might be overriding your settings from your LAN DHCP server.
Lines to look for are dhcpd domain, dhcpd dns and dhcpd auto_config.
The setup I use is pretty robust, but has the ASA doing DHCP for the local clients - this means that if the VPN goes down, users still have access to local systems.
Answer: I have no experience with the specific hardware you are working with. However, with openvpn, you need to have bridge the network for dns queries to work. From the sounds of things, you already have a bridged VPN set up (i.e. your client ip address is on the same range as that of the destination network).
When you set up a bridged network like so, your dns server might still be binding to the original ethernet interface instead of the new bridged interface.
If that is the case, the packets will not get router correctly. Get the DNS Server to bind to the bridge interface or even better to the ip address of the bridge interface so that it will work regardless of whether the VPN is active or not.
Answer: I has the same issue with Cisco VPN Client working with USB GSM modem. The problem was solved using the next sentence in ASA Cisco ASA.
group-policy TestVPN attributes
  split-dns value dominioprivado1.com dominioprivado1.org dominioprivado1.net

Where "dominioprivado1.com dominioprivado1.org dominioprivado1.net"  are the DNS zones that contain the servers's names privates.


pygame - observer pattern error

Question: I'm testing out using the observer pattern in a game I'm making. However I'm having some problems with it. My code as well as the error is below, can someone help?
the error:
File "C:\Users\Administrator\PycharmProjects\untitled\Level.py", line 112, in update
    w.update()
  File "C:\Users\Administrator\PycharmProjects\untitled\Entity.py", line 13, in update
    self.notifyObservers()
  File "C:\Users\Administrator\PycharmProjects\untitled\Observable.py", line 15, in notifyObservers
    observer.update(self)
TypeError: unbound method update() must be called with Player instance as first argument (got WorldController instance instead)

level file:
self.world = [WorldController()]
for w in self.world:
            w.update()

Entity file:
class WorldController(Observable):
    def __init__(self):
        super(Observable, self).__init__()
        self._observers = []

    def update(self):
        self.addObserver(Player)
        self.notifyObservers()

class Entity(Observer, pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

class Player(Entity, Observer):
    def __init__(self, x, y):
        super(Observer, self).__init__()
        Entity.__init__(self)
    def update(self, observable):
        print "works!"

observable file:
class Observable(object):
    def __init__(self, **kwds):
        super(Observable, self).__init__(**kwds)
        self._observers = []
    def addObserver(self, observer):
        if not observer in self._observers:
            self._observers.append(observer)
    def removeObserver(self, observer):
        try:
            self._observers.remove(observer)
        except ValueError:
            pass
    def notifyObservers(self):
        for observer in self._observers:
            observer.update(self)

class Observer(object):
    def __init__(self, **kwds):
        super(Observer, self).__init__(**kwds)
    def update(self, observable):
        pass

Answer: class WorldController(Observable):
    def __init__(self):
        super(Observable, self).__init__()
        self._observers = []

    def update(self):
        self.addObserver(Player)
        self.notifyObservers()

should be:
class WorldController(Observable):
    def __init__(self):
        super(Observable, self).__init__()
        self._observers = []

    def update(self):
        self.addObserver(Player())
        self.notifyObservers()

otherwise when you call Player.update(self) you are calling a static method instead of a instance method for Player class
Comment: I got it working right before the reply, but thank you that was the problem, I did a little bit differently though

pygame - observer pattern error


How would I test my login function has been called? Angular2+

Question: I am struggling with how to test if a function has been called between a component and a service.
If there is something I'm missing, please educate me!
Comment: @SourangshuSengupta that would be if you were testing the *service*, the component shouldn't know anything about that.
Comment: I'd recommend reading [the testing guidance](https://angular.io/guide/testing); you shouldn't be unit testing the component with a real service with the real HTTP client.
Comment: Hmm ok then. I will have a read and see what I can come up with.
Any quick hints in the mean time?
Comment: Instead of using `HttpClientModule`, maybe you can use `HttpClientTestingModule`.
Comment: The short answer is: your "form" isn't valid, so the service isn't called. But that's probably just as well: why are you explicitly calling through to the service, even though that's not what you're testing? The point of extracting that logic to a service is that the component doesn't know about it, you shouldn't be calling or even necessarily using the real service, and unit tests should generally never use real HTTP.
Comment: In your `onSubmit()` method, you are checking if the form is valid, and only then calling the service method. Is it possible that `validFormGoodCreds` that you are using in your test is *not* `valid`?? I don't see a valid property on it.
Answer: in your specs, you name the auth service authServ:
(authServ: AuthService) => {
but you're spying on auth:
spy = spyOn(auth, 'login').and.callThrough();
Can you try renaming the auth service authServ => auth?
If this doesn't help, please post the error message(s), otherwise it's hard to debug.
Comment: Apologies for that, I'd been changing code as I copied it over.
Doing as such gets the error: Expected spy login to have been called.
Comment: this means, it hasn't been called. alternatively, for debugging you can set a console.log or a breakpoint, if you use a IDE that allows you to debug angular (e.g. visual studio code)


error: invalid conversion from 'my_type*' to 'int' [-fpermissive]

Question: A execução do meu código retorna este erro escrito no título. Não sei o que fazer para resolver porque, se vocês virem o código, é claro que o tipo do parâmetro é BlockGraph e não int. Quando eu coloco um valor inteiro no lugar de block, não é retornado nenhum erro.
    #include <iostream>
    #include <iomanip>
    #include <vector>

    #define INF 0x3f3f3f3f
    #define BOUND 99.99

    typedef int Vertex;
    typedef double Weight;

    using namespace std;

    class BlockGraph
    {
        private:
            int qtyVertices;
            vector< vector<Weight> > adjMatrix;

        public:
            BlockGraph( int );
            void addEdge( Vertex, Vertex, Weight );
            void displayGraph();
    };

    BlockGraph::BlockGraph( int qtyVertices )
    {
        this->qtyVertices = qtyVertices;

        adjMatrix.resize( qtyVertices+1 );
        for( int i = 1; i <= qtyVertices; i++ )
            adjMatrix[i].resize( qtyVertices+1, BOUND );
    }

    void BlockGraph::addEdge( Vertex v, Vertex u, Weight w  )
    {
        adjMatrix[u][v] = w;
        adjMatrix[v][u] = w;
    }

    void BlockGraph::displayGraph()
    {
        cout << endl << "       ";

        for( int i = 1; i <= qtyVertices; i++ )
            cout << setw(7) << "u";
        cout << endl << "       ";

        for( int i = 1; i <= qtyVertices; i++ )
            cout << setw(7) << i;
        cout << endl << endl;

        for( int i = 1; i <= qtyVertices; i++ ){
            cout << setw(3) << "v" << setw(3) << i << "|";
            for( int j = 1; j <= qtyVertices; j++ ){
                cout << fixed << setprecision(2);
                if( adjMatrix[i][j] == BOUND )
                    cout << setw(7) << "INF";
                else
                    cout << setw(7) << adjMatrix[i][j];
            }
            cout << endl;
        }
    }
                      //it's a inherit!
    class BrainGraph: public BlockGraph
    {
        private:
            int qtyVertices;
            vector< pair<BlockGraph, int> > blocks;
            vector< vector<Weight> > adjMatrix;

        public:
            BrainGraph( int );
            void addBlock( BlockGraph, int );
            BlockGraph* getBlock( Vertex );
    };

    BrainGraph::BrainGraph( int qtyVertices ):BlockGraph( qtyVertices )
    {
            BlockGraph nil(0);
            blocks.push_back( make_pair( nil, 0 ) );;
    }

            // ------------ MÉTODO DA CLASSE CHAMADO --------------
    void BrainGraph::addBlock( BlockGraph block, int sickcells )
    {
        blocks.push_back( make_pair( block, sickcells ) );
    }
            // ------------ MÉTODO DA CLASSE CHAMADO --------------

    BlockGraph* BrainGraph::getBlock( Vertex x )
    {
        return &blocks[x].first;
    }

    int main()
    {
        BrainGraph* brain;
        BlockGraph* block;

        int orderBrain, qtyEdgesBrain;
        int orderBlock, qtyEdgesBlock;
        int sickcells, h;

        Vertex x, y, start, finish;
        Weight w;

        cin >> orderBrain >> qtyEdgesBrain;
        brain = new BrainGraph( orderBrain );

        for( int i = 1; i <= qtyEdgesBrain; i++ ){
            cin >> x >> y >> w;
            brain->addEdge( x, y, w );
        }

        cin >> start >> finish;

        for( int i = 1; i <= orderBrain; i++ ){
            cin >> orderBlock >> qtyEdgesBlock >> sickcells;
            block = new BlockGraph( orderBlock );

            if( sickcells > 0 )
                for( int l = 0; l < sickcells; l++ )
                    cin >> h;

            for( int j = 1; j <= qtyEdgesBlock; j++ ){
                cin >> x >> y >> w;
                block->addEdge( x, y, w );
            }

            // ------------ ERRO NESSA LINHA --------------
            brain->addBlock( block, sickcells );
            // ------------ ERRO NESSA LINHA --------------

            delete[] block;
        }

        brain->displayGraph();

        for( int v = 1; v <= orderBrain; v++ ){
            cout << endl << endl;
            block = brain->getBlock( v );
            block->displayGraph();
        }

        return 0;
    }

O IDE também retorna note:   initializing argument 1 of 'BlockGraph::BlockGraph(int)'|
Answer: Repare na assinatura do método:
void BrainGraph::addBlock( BlockGraph block, int sickcells )

Espera um BlockGraph quando está a passar um BlockGraph*:
BlockGraph* block;
...
brain->addBlock(block, sickcells );

Se quiser manter a assinatura do método tem de trocar a chamada para:
brain->addBlock(*block, sickcells );

Alternativamente pode alterar o método addBlock para receber um BlockGraph* como primeiro parâmetro. Veja qual forma atende melhor os seus objetivos.