How to replace dot from integer in javascript

Question: i'm trying to create a multiple stopwatches in one page, i have found a code online that's working as same as i need, but there's a problem, the integer they're rendering is like 4.03 means 4 is like second and 03 is seconds, i want something like 4:03 or if you can give me any other code which works the same way this code is working, Thanks
i expect the output of 4.03 to be 4:03

var Stopwatch = function(elem, options) {

  var timer       = createTimer(),
      startButton = createButton("start", start),
      stopButton  = createButton("stop", stop),
      resetButton = createButton("reset", reset),
      offset,
      clock,
      interval;

  // default options
  options = options || {};
  options.delay = options.delay || 1;

  // append elements
  elem.appendChild(timer);
  elem.appendChild(startButton);
  elem.appendChild(stopButton);
  elem.appendChild(resetButton);

  // initialize
  reset();

  // private functions
  function createTimer() {
    return document.createElement("span");
  }

  function createButton(action, handler) {
    var a = document.createElement("a");
    a.href = "#" + action;
    a.innerHTML = action;
    a.addEventListener("click", function(event) {
      handler();
      event.preventDefault();
    });
    return a;
  }

  function start() {
    if (!interval) {
      offset   = Date.now();
      interval = setInterval(update, options.delay);
    }
  }

  function stop() {
    if (interval) {
      clearInterval(interval);
      interval = null;
    }
  }

  function reset() {
    clock = 0;
    render(0);
  }

  function update() {
    clock += delta();
    render();
  }

  function render() {
    timer.innerHTML = clock/1000;
  }

  function delta() {
    var now = Date.now(),
        d   = now - offset;

    offset = now;
    return d;
  }

  // public API
  this.start  = start;
  this.stop   = stop;
  this.reset  = reset;
};

// basic examples
var elems = document.getElementsByClassName("basic");

for (var i=0, len=elems.length; i<len; i++) {
  new Stopwatch(elems[i]);
}

// programmatic examples
var a = document.getElementById("a-timer");
aTimer = new Stopwatch(a);
aTimer.start();

var b = document.getElementById("b-timer");
bTimer = new Stopwatch(b, {delay: 100});
bTimer.start();

var c = document.getElementById("c-timer");
cTimer = new Stopwatch(c, {delay: 456});
cTimer.start();

var d = document.getElementById("d-timer");
dTimer = new Stopwatch(d, {delay: 1000});
dTimer.start();
<!DOCTYPE html>

<meta charset=utf-8 />
<title>JS Bin</title>

Basic example; update every 1 ms

click start to start a stopwatch

var elems = document.getElementsByClassName("basic");

for (var i=0, len=elems.length; i<len; i++) {
  new Stopwatch(elems[i]);
}

Programmatic example

Note: despite the varying delay settings, each stopwatch displays the correct time (in seconds)

var a = document.getElementById("a-timer");
aTimer = new Stopwatch(a);
aTimer.start();

1 ms

var b = document.getElementById("b-timer");
bTimer = new Stopwatch(b, {delay: 100});
bTimer.start();

100 ms

var c = document.getElementById("c-timer");
cTimer = new Stopwatch(c, {delay: 456});
cTimer.start();

456 ms

var d = document.getElementById("d-timer");
dTimer = new Stopwatch(d, {delay: 1000});
dTimer.start();

1000 ms

Comment: Don't try to get around the restrictions of posting links to external sandbox without entering any code in your question by wrapping those links in a code block. Those restrictions are there for a reason. We shouldn't have to go off site just to review your initial problem. Now we can't even click on the link in the question
Comment: Please add your current relevant code here
Comment: https://jsbin.com/IgaXEVI/167/edit?html,js,output
Answer: You can transform your number into a string, and then use the replace method:
val.toString().replace('.', ':');

Edit:
How to update your render function :
  function render() {
    const timerValue = clock/1000;
    timer.innerHTML = timerValue.toString().replace('.', ':');
  }

Comment: I just edited my answer with the exact code you need to change to make this work from your jsfiddle. I'm not sure what more you want.
Comment: but than it'll not run the timer.
Comment: You only to store the result in a new variable and use this to display it.
Comment: I added the exact code you need to change in your code to make it happen...
Comment: it's not working bro, can you please send me some code example regarding my code which i'm running yet
Comment: No clue why this was down-voted, I've up-voted you
Comment: sorry bro, i can't find timerValue variable.
Comment: @JackRogers Thanks :D
@JawadAjaz the `timerValue` is defined in the render method. The first line of the method in my answer...
Comment: I've copy/pasted your code to actually be in the question now.
Comment: one more thing bro, i want to get the values of all running timers and add them and render it in an another div. is that possible?


Erro ao buscar uma lista no banco

Question: Eae pessoal,
Então estou com uma duvida no meu trabalho da faculdade,
tenho duas tabelas uma USUARIO e USUARIO_AMIGO ambas relacionadas, pelo java estou buscando uma lista de usuário que trás todos os usuários cadastrados, e uma outra lista que trás um amigo de um determinado usuário, so que não consigo trazer esses valores.
Meu codigo ListaTodos e ListaAmigos
public List<Usuario> buscarAmigos(int cdUsuario){
        String sql = "SELECT USUARIO_CD_USUARIO FROM USUARIO_AMIGO "
                + "INNER JOIN USUARIO "
                + "ON USUARIO_AMIGO.USUARIO_CD_USUARIO = USUARIO.CD_USUARIO "
                + "AND USUARIO_AMIGO.USUARIO_CD_USUARIO = ?";
        List<Usuario> amigos = new ArrayList<Usuario>();
        try {
            PreparedStatement st = conn.prepareStatement(sql);
            st.setInt(1, cdUsuario);
            ResultSet resultado = st.executeQuery();
            while(resultado.next()){
                Usuario usuario = new Usuario();
                usuario.setCdUsuario(resultado.getInt("CD_USUARIO"));
                usuario.setDataNasc(resultado.getString("DT_NASCIMENTO"));
                usuario.setFoto(resultado.getString("FOTO_USUARIO"));
                usuario.setLocalizacao(resultado.getString("NM_LOCALIZAO"));
                usuario.setNome(resultado.getString("NM_NOME"));
                usuario.setSobrenome(resultado.getString("NM_SOBRENOME"));
                usuario.setEmail(resultado.getString("EMAIL_USUARIO"));
                usuario.setNmUsuario(resultado.getString("NM_USUARIO"));
                usuario.setSexo(resultado.getString("TP_SEXO").charAt(0));
                amigos.add(usuario);
            }
            st.close();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return amigos;
    }

    public List<Usuario> buscarTodos(){
        String sql = "SELECT * FROM USUARIO";
        List<Usuario> lista = new ArrayList<Usuario>();
        try {
            PreparedStatement st = conn.prepareStatement(sql);
            ResultSet resultado = st.executeQuery();
            while(resultado.next()){
                Usuario usuario = new Usuario();
                usuario.setCdUsuario(resultado.getInt("CD_USUARIO"));
                usuario.setDataNasc(resultado.getString("DT_NASCIMENTO"));
                usuario.setFoto(resultado.getString("FOTO_USUARIO"));
                usuario.setLocalizacao(resultado.getString("NM_LOCALIZACAO"));
                usuario.setNome(resultado.getString("NM_NOME"));
                usuario.setSobrenome(resultado.getString("NM_SOBRENOME"));
                usuario.setEmail(resultado.getString("EMAIL_USUARIO"));
                usuario.setNmUsuario(resultado.getString("NM_USUARIO"));
                usuario.setSexo(resultado.getString("TP_SEXO").charAt(0));
                //usuario.setAmigos(this.buscarAmigos(usuario.getCdUsuario()));
                usuario.setAmigos(this.buscarAmigos(resultado.getInt("CD_USUARIO")));
                lista.add(usuario);
            }
            st.close();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return lista;
    }

Classe de teste
// GET AMIGOS
        try {
            UsuarioDao dao = new UsuarioDao();
            List<Usuario> listaAmigos = dao.buscarAmigos(1);
            System.out.println("Amigos do usuario:");
            for (Usuario u : listaAmigos){
                System.out.println(u.getCdUsuario() + " - " + u.getNome() + " " + u.getSobrenome());;
            }
        } catch (Exception e) {
            System.out.println(e);
        }

        // GET USUARIOS
        try {
            UsuarioDao dao = new UsuarioDao();
            List<Usuario> listaUsuario = dao.buscarTodos();
            System.out.println("Lista de usuario:");
            for (Usuario u : listaUsuario){
                System.out.println(u.getCdUsuario() + " - " + u.getNome() + " " + u.getSobrenome());
            }
        } catch (Exception e) {
            System.out.println(e);
        }

O erro que me retorna
java.sql.SQLException: Nome de coluna inválido
    at oracle.jdbc.driver.OracleStatement.getColumnIndex(OracleStatement.java:3724)
    at oracle.jdbc.driver.OracleResultSetImpl.findColumn(OracleResultSetImpl.java:2799)
    at oracle.jdbc.driver.OracleResultSet.getInt(OracleResultSet.java:438)
    at br.com.younews.dao.UsuarioDao.buscarAmigos(UsuarioDao.java:94)
    at br.com.younews.dao.UsuarioDao.buscarTodos(UsuarioDao.java:131)
    at br.com.younews.teste.TesteUsuarioDao.main(TesteUsuarioDao.java:67)

Minha tabela
Comment: verifiquei todas
Comment: linha 67 - List listaUsuario = dao.buscarTodos();
Comment: Guilherme, edita a pergunta e coloca mais informações sobre as tabelas que você está utilizando pra ficar mais fácil identificar o problema. Um detalhe que achei estranho é que você começou falando que tem uma tabela `AMIGO_USUARIO` e no seu SQL você utiliza `USUARIO_AMIGO`.
Comment: tinha me confundido, corrigido
Answer: Amigo, vejamos melhor a sua situação.
Na sua SQL, temos o seguinte:
 String sql = "SELECT USUARIO_CD_USUARIO FROM USUARIO_AMIGO "
            + "INNER JOIN USUARIO "
            + "ON USUARIO_AMIGO.USUARIO_CD_USUARIO = USUARIO.CD_USUARIO "
            + "AND USUARIO_AMIGO.USUARIO_CD_USUARIO = ?";

Ok, sendo assim, se você executar isso no IBExpert ou sql management studio ou qualquer outra coisa que execute SQL, você terá apenas a sua tupla(linha de resultado) com uma coluna.
USUARIO_CD_USUARIO
==================
1
2
3

Porém, no seu ResultSet você esta buscando por colunas que neste momento não existem na sua Query.
Experimente ao menos, declarar estar colunas na sua SQL.
Algo simples, como:
String sql = " SELECT USUARIO_AMIGO.* "
           + " FROM USUARIO_AMIGO "
           + " INNER JOIN USUARIO ON (USUARIO_AMIGO.USUARIO_CD_USUARIO = USUARIO.CD_USUARIO) "
           + " WHERE USUARIO_AMIGO.USUARIO_CD_USUARIO = ?"

Ou melhor ainda, certifique-se em qual tabela estão os campos que você está tentando utilizar no ResultSet e escreva-os por extenso na sua SQL.
Utilize de preferência sempre TABELA.CAMPO pois isso facilita tanto para você entender o que está buscando da sua base de dados, quanto outra possa que possa vir a dar manutenção no código que você concebeu.
Mas pelo menos tente. Sim, os dados que você quer devem estar todos declarados na sua select, indiferente de como você utilizar ( "SELECT * FROM TABELA" ou "SELECT TABELA.CAMPO FROM TABELA ...")
Comment: Agora faz sentido. Só falta excluir a outra resposta. Leia o [tour] para entender melhor o site. Aliás, bem vindo ao [pt.so]

Erro ao buscar uma lista no banco


How to create an error_log in each's vhosts httpdocs directory

Question: Running a CentOS 6.4 server with Plesk 11 and virtual hosts for each client/domain.
What I'm now trying to accomplish is to auto-create an error_log in each user's httpdocs folder in case of problems with the script running in this directory.
Someone who know how to do this?
Comment: What have you tried? We are not here to do work for you, but rather to help you solve problems based on issues you are having & solutions you have tried.
Comment: @JakeGould I've just tried nothing yet because I haven't found any source to get started with. I found an apache source about creating error logs and virtual hosts but I'm not sure this is the right thing since it says that each virtual host needs its own IP adress.
Answer: You don't have to. Plesk is already configured to create error_logs for every domain. You can find them at <code>/var/www/vhosts/<domainname>/statistics/logs/</code>
Comment: @etangenklo Generally you are right, so I marked your answer as the correct answer. However, if you read my question carefully again, I was asking to put an error_log into the httpdocs folder and only with errors of the script running in this folder, in example php fatal errors or other developing errors. In case if you know a solution for this as well, would be nice if you will update your answer. Thanks.


How to show a field in a view for another field?

Question: I have twig template named views-view-field--banner--block_1--field-banner.html.twig Here I print
{{ output -}}
To put an anchor tag around an image field named field_banner. I also have another field named field_slider_banner_link that I want to print within the href="". But I have no clue how to get the value from that other field into this template.
Answer: If the template provides a row variable (check the available variables in the Twig comments) and is not a table:
views-view-field.html.twig:
{{ view.field.other_field.getvalue(row) }}

See also How can I theme individual fields in a row?
Comment: Thanks it works! But it's printing a `#` behind the value for some reason. Do you know why?
Comment: Don't know, but theming Views fields in templates is not always the best idea. Views is in the first place a UI tool. Did you try the linked topic? Seems to be about your use case.
Comment: Yeah I tried, that doesn't work for me. Also I twig's dump() doesn't work, altough I enabled twig debugging etc.


An open-source CodeIgniter based e-commerce app that I can contribute to?

Question: I'd like to get involved in open source projects to try and get rid of the n00b-hood which seems to cling to me like a gecko to flypaper.
It seems that there are no open source e-commerce solutions built on codeigniter - a search on Google, a search on Github, and a search on Stackoverflow all brought out 0 coherent results.
If anybody knows of such a project, please let me know, so I can start contributing my part to the development - that is the only way i'll ever improve, and i'm sure any mentor would like a little help on their pet project...
Besides, I think Oscommerce (and any of it's numerous cousins) seems a bit immature in it's approach even to a non-ninja like me, and magento is totally undemocratic with it's insistence of innoDB requirement and the impossible complexity of the code architecture.
Comment: before i do that, i want to make sure that somebody else hasn't already... besides, one needs to be a wielder of mighty skill to be proud enough to start their own opensource project. i am no more than a grasshopper - maybe that would be too arrogant a step to take?
Answer: So far I have only found 2 e-commerce solutions that utilise codeigniter.

Total Shop UK - Was announced in this thread
Community Cart - recently updated to v2.01

E-commerce in code-igniter has been talked about a lot. It baffles me why so few have developed apps in this area.
My personal opinion is that there is definitely an opportunity to create a slick e-commerce app using code-igniter now that CI 2.0 is finally here!
Comment: Thanks for the suggestions - Total Shop UK is ANTI-forking. Check this out: http://www.totalshopuk.com/license

I'm trying out Community Cart right now though. Might just start contributing to it :)
Answer: There's also GoCart, which is built on CodeIgniter: http://gocartdv.com/.
Answer: I would check out OpenCart - it's not a codeigniter system but it is based on a MVC model and the source is very organized. You can control most of the templates, it has built in localization and multiple taxes etc..
Comment: Oh my god, I can't thank you enough for suggesting OpenCart. Using OsCommerce for a long time convinced me that the world is usually full of dark, unintuitive ecommerce systems that are very hard to customize for the developer and downright ugly for a non-technical admin to manage.

I'm very happy with the system thanks :)
Comment: You are welcome. I hope it works out for you.
Comment: Thanks for the head's up... I've been trying to install and try this baby out back since you posted this answer, but dang it, I just don't find the time! :)


Estimate Ratio of Normalizing Constants from two datasets

Question: Suppose I have a non-negative function $f:\mathbb{R}^N \to [0, +\infty)$ that defines two different (unnormalized) probability densities on two separate subsets $A, B \subset \mathbb{R}^N$ with $A \cap B = \emptyset$.
$$
\widetilde{p}(x) = \begin{cases} f(x) & \text{if } x\in A \\ 0 & \text{if } x \notin A\end{cases}  \\
\widetilde{q}(x) = \begin{cases} f(x) & \text{if } x\in B \\ 0 & \text{if } x\notin B\end{cases}
$$
Now suppose a set of samples from each
$$
x_1^p,\ldots, x_N^p \sim \widetilde{p}(x) \\
x_1^q, \ldots, x_N^q \sim \widetilde{q}(x)
$$
How can I use these samples to approximate the ratio of normalizing constants
$$
\frac{Z_q}{Z_p} = \frac{\displaystyle \int_B \widetilde{q}(x)dx}{\displaystyle \int_A \widetilde{p}(x)dx}
$$
Comment: @Xi'an what an honor! Thank you! I had a look at some of those papers like the exchange algorithm etc but they all use some other proposal density defined on the same space. In my case, however, I have two disjoint supports. Or rather, the supports are not disjoint but one of the densities is always $0$ when the other is positive
Comment: You are correct, this is not a straightforward application of the above. Since the simulations are constrained to $A$ and $B$ respectively, they bring no information about the relative weights of $A$ and $B$ under $f$. This reminds me of the difficulty of computing the Bayes factor when given only samples from each posterior.
Comment: So evaluating or estimating $f(a)/f(b)$ with $a\in A, b\in B$ would not be possible?
Comment: Do you have an expression for $f$, or just a black-box sampler for $\tilde p$ and $\tilde q$? Would you be able to sample from the density that is proportional to $f$ over another subset of $\mathbb{R}^N$?
Comment: @RobinRyder unfortunately, I don't have an expression for $f$. In fact, I would like to learn about $Z_p$ and $Z_q$ so that I can then learn about $f$!
Answer: [Warning: the following proposals, except one, assume $f$ can be evaluated at arbitrary values. If the only inputs are the sets $A$ and $B$, and the samples $\mathbf x$ and $\mathbf y$, the problem has no solution since any combination $\alpha f_A(x)+(1-\alpha) f_B(x)$ could produce exactly the same samples $\mathbf x$ and $\mathbf y$.]
If an expectation under $f$ [assumed to be a density, i.e. normalised] is known, as in control variate settings, $$\int h(x) f(x)\,\text dx=\mathfrak h>0$$
solving$$\alpha\int_A h(x) \frac{\tilde p(x)}{Z_p} \,\text dx+(1-\alpha) \int_B h(x) \frac{\tilde q(x)}{Z_q} \,\text dx=\mathfrak h\tag{1}$$returns $$\alpha=Z_p$$unless both integrals are identical. Replacing (1) with its Monte Carlo version
$$\sum_{i=1}^N\{\hat\alpha h(x_i)+(1-\hat\alpha)h(y_i)\}=n\mathfrak h$$
returns an estimator of $Z_p$. In the case $f$ is not normalised, two such functions $h$ would be required.
An illustration in the Normal $\mathcal N(0,1)$ case when $A=(-\infty,1)$, $p_A=0.841$, $h(x)=x$, and $\mathfrak h=0$:
for(t in al<-1:1e2){
  x=(x<-rnorm(4e5/p))[x<1][1:1e5]
  y=(y<-rnorm(4e5/(1-p)))[y>1][1:1e5]
  al[t]=1/(1-mean(x)/mean(y))}

resulting in a concentrated approximation of $p_A$:

Another (crude) approach would be to estimate (by a kernel density estimator) the densities on both samples and, assuming continuity of the density $f$ at the boundary, make them meet at this boundary (between $A$ and $B$). As in this example
p=pnorm(1) #A is (-oo,1) and B (1,+oo) and f is dnorm
wh=N<-1:1e5
x=(x<-rnorm(4*N/p))[x<1][1:N] #sample from p over A
y=(y<-rnorm(4*N/(1-p)))[y>1][1:N] #sample from q over B
a=density(x,ker="gaussian",to=1) #KDE of p
hatfa=approxfun(a$x,a$y)
b=density(y,ker="gaussian",from=1) #KDE of q
hatfa=approxfun(a$x,a$y)

leading to
> hatfb(1)/hatfa(1)
[1] 4.917869

as  the estimate of $p_A/p_B$. Repeated simulations show however that the estimator is biased downwards.
As an alternative, once one is using a kernel approximation, one can implement a full (reversible jump) MCMC version for simulating moves between $A$ and $B$, based on the non-parametric density estimator as a proposal:
mm=wh=1:N;wh[1]=x[1] #mm model indicator, 1 stands for A
for (t in 2:N){#Metropolis-Hastings steps
  mm[t]=mm[t-1];wh[t]=wh[t-1]
  if(mm[t]){#propose to move to B
    prop=rnorm(1,sample(y,1),b$bw)
    while(prop<1)prop=rnorm(1,sample(y,1),b$bw)#constrained to B
    if(dnorm(wh[t])*hatfb(prop)*runif(1)<dnorm(prop)*hatfa(wh[t])){
      wh[t]=prop;mm[t]=0}
  }else{#propose to move to A
    prop=rnorm(1,sample(x,1),a$bw)
    while(prop>1)prop=rnorm(1,sample(x,1),a$bw)#constrained to A
    if(dnorm(wh[t])*hatfa(prop)*runif(1)<dnorm(prop)*hatfb(wh[t])){
      wh[t]=prop;mm[t]=1}}
}

resulting in an estimate of the ratio
> mean(mm)/mean(!mm)
[1] 5.127451


Finding CDF for this (simple?) PDF, and is it differentiable/continuous?

Question: Let $\alpha \in (\frac14,\frac12)$ is some constant.
Consider a random variable $X$ with PDF:
$$P(X=s) =\begin{cases}4 &if\ s< \frac12-\alpha\\
2 & if\  \frac12 -\alpha < s \leq \alpha \\
0&if\   s>\alpha \end{cases}
$$
I wish to find the CDF, $F$

Can someone

confirm I wrote the integrals correctly (specifically, the variable of integration?),
that the CDF is correct,
whether the CDF is differentiable?

My attempt:
For $s< \frac12-a$, $$F(s) = \int_0^s 4 dX = 4s
$$
For $\frac12  -a \leq s \leq \alpha$,
$$
F(s) = \int_0^{\frac12 -\alpha} 4 dX+ \int_{\frac12-\alpha}^s 2dX =2-4\alpha+ 2s - 2(\frac12-\alpha)=2-4\alpha-1+2\alpha + 2s \\= 1-2\alpha + 2s
$$
So the CDF $F$ is, for given $\alpha\in (\frac14,\frac12)$,
$$
F(s) = \begin{cases}4s &if\ s< \frac12-\alpha\\
                    1-2\alpha + 2s &if\ \frac12-\alpha<s\leq \alpha\end{cases}
$$
I believe that it is kinked at $s=\frac12-\alpha$ (the slope changes from (4) to (2)), so it is not differentiable? (but it is continuous)

(More background: Suppose we have a  random variable, $Z$, and we define another random variable $X\equiv d(Z,y)$. Note that $Z,y$ are such that $0\leq d(Z,y)\leq \alpha$, where $\alpha \in (\frac14,\frac12)$ is some constant.)
Answer: The choice of the integration variable doesn't really matter, but $X$ (capitalized) is a bit of a weird choice. It's more common to use $x$ if the random variable is denoted by $X$.
Other than that it looks OK, though I didn't check the details. The only thing is that technically $F$ should be defined on all of $\mathbb{R}$, so you should have two more cases (one for $s<0$ and one for $s>\alpha$). These cases are trivial to write down but still important.


Golang doesn't process 2 operations

Question: I'm a new in golang and i don't understand why I can't get next code working:
func ListApps(){
    fmt.Printf("\nPress Q to go back..\n")
    reader := bufio.NewReader(os.Stdin)
    input, _ := reader.ReadString('\n')

    if string(input) == "q" {
        fmt.Printf("OK")
     }
 }

I want to print a message, then scan user's input in console, compare input and print messafe if imput equals string "q". Last check doesn't work for some reasons.
Answer: from TFM:

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter

You are comparing the string without the delimiter.
So just doing:
if input == "q\n" {...}

would work (BTW no need to call string(input) as input is already a string).
Alternatively you can also trim the endline before checking, using strings.TrimRight. This will make the code more portable as it will work on Windows where \r\n is used to delimit lines. So do this:
input = strings.TrimRight(input, "\r\n")
if input == "q" {
    fmt.Println("OK")
}

And I've tested this to work myself.
Comment: @Vnuuk it works for me. could be that your terminal is not using \n but \r\n. Which is why the second approach of trimming would work better, because it will be portable
Comment: Works, thanks! By the way - I'm useing Windows terminal
Answer: Not_a_Golfer is correct on why its not working. However, for simple things like reading from STDIN you're better off using Scanner:
func ListApps(){
    fmt.Printf("\nPress Q to go back..\n")
    reader := bufio.NewScanner(os.Stdin)
    reader.Scan()  // this line scans the STDIN for input

    // error checking...
    if err := scanner.Err(); err != nil {
        panic(err)
    }

    // To access what the scanner got, you use scanner.Text() (reader.Text() in this case)
    if reader.Text() == "q" {
        fmt.Printf("OK")
     }
 }

This will work, regardless of where the input is from (windows command prompt, terminal on linux/OSX, etc)

Golang doesn't process 2 operations


Jacobian Matrix and dot product question

Question: I have a question on how the Jacobian matrix is used in a specific example from Wiki.  I present definitions first and then a question.
The Jacobian is defined as:
$J = \begin{bmatrix} \frac {\partial f}{\partial x_1} ... \frac {\partial f}{\partial x_n} \end{bmatrix} = \begin{bmatrix} \Delta^T f_1 \\ ... \\ \Delta^T f_m \end{bmatrix} = \begin{bmatrix} \frac {\partial f_1}{\partial x_1} ... \frac {\partial f_1}{\partial x_n} \\ ... \\ \frac {\partial f_m}{\partial x_1} ... \frac {\partial f_m}{\partial x_n} \end{bmatrix}$
Wiki then says:
$f(y) = f(x) + J(x) \cdot (y - x)$ is the best linear approximation for $f(y)$ for points close to $x$.
Questions

Does $J(x)$ represent scalar multiplication of the initial point $x$ with the $J$?  I.e. to get the PDs at a point.

If (1) above, how does one distinguish this operation from matrix multiplication?

For $J(x) \cdot (y - x)$ can the dot product, $\cdot$, be omitted as matrix multiplication will result in the same value?  The third form of $J$ is a matrix and dot product $\cdot$ is a vector operation, so this is confusing.
Comment: BTW, that $\Delta^T f$ should probably be $(\nabla f)^\top$.
Answer: The Jacobian matrix $J$ contain partial derivatives $\frac{\partial f_i}{\partial x_j}$ which are themselves functions. The entries of $J(x)$ are these partial derivatives evaluated at $x$, i.e. $\frac{\partial f_i}{\partial x_j}(x)$.
Comment: @Nick No, as I said in my answer, $J(x)$ is a matrix whose $(i,j)$ entry is the real number $\frac{\partial f_i}{\partial x_j}(x)$. There is no multiplication going on in the definition of $J(x)$.
Comment: I thought $J(x)$ would be each entry of $J$ matrix multiplied by $x$.  $J$ seems to represent two different objects.So $J_f(x) = J * x$?
Comment: My confusion was over $J(x)$ with $x$ as supplied argument.  Given what you say, a matrix of functions can all each be evaluated with a single argument $(x)$ supplied to the matrix?
Comment: @Nick Yes, that is how I think it should be interpreted: $J$ is a matrix of functions, and $J(x)$ is the matrix consisting of the evaluations of those functions at $x$.
Answer: As has been said before, $J(x)$ is the Jacobian matrix at the point $x$, as all the functions depend on $x$. The dot does not below there, as we do not take the dot product of a matrix and a vector. Just delete the dot and multiply the Jacobian matrix by the (column) vector $y-x$.
Answer: You don't need to worry about defining Jacobian for this. This is simple Taylor's theorem:
$$
f_i\left(y\right)=f_i\left(x+(y-x)\right)=f_i\left(x\right)+\sum_j \partial_j f_i\left(x\right)\,\left(y_j-x_j\right)+\mathcal{O}\left(\left|y-x\right|^2\right)
$$
for all $i$


Views Contextual Filter on date range

Question: Drupal 7.23, Views 7.x-3.7
I have a Calendar Event content type, with a date field.
In my view, I need to pass a date range as a contextual filter such that if the event's date falls within the specified range, the events is returned.
In other words, something like /events-calendar/2013-09-04/2013-09-30 should return any events happening for the rest of this month.
So far I'm only able to match a single date, not a range.
Any ideas appreciated.
Comment: Could you provide your desired filtering as a pseudocode algorithm? I've seen quite too many ideas how such filtering should really work to dare to guess.
Answer: Assuming that you have set up your contextual filters properly, all you need to do is change the format of the date you pass.
<code>/events-calendar/20130904--20130930
</code>
That above format should do the trick.
Comment: In case anyone's interested, I set up these links in a block, and the code looks like this:
`echo "This Month";`
Comment: Glad it helped :)
Answer: If you are looking for ranges in general within the contextual filters then you should consider using the Views Contextual Range Filter module. Some more details about it:

Views Contextual Range Filter is a simple plugin for Views that adds the option to contextually filter not just by a single value, but also by range.
Numeric, alphabetical and list ranges are all supported. Node ids, user ids and even taxonomy term ids are all special cases of numbers so will work also. Range-filtering on dates is also supported. For this you may use either the absolute date format as dictated by Views, YYYYMMDD, or the relative format, which supports natural language phrases like six months ago, today noon and even first Tuesday of November.
Please be aware that contextual filters are different from exposed filters. This module is about contextual filters only.
You may use the OR operator (i.e. +) and the negate operator. You negate by ticking the "Exclude" box on the Views Contextual filter configuration panel, in the "More" section.
Comment: Adding this a separate answer this is not exactly what you asked for. But might help others who are looking for this.
Comment: I will definitely check this out, as it looks as if it might prove useful elsewhere. Thanks for your input and your answer (sorry I don't have enough reputation points to vote up your answers - kinda new here :-)
Comment: Except that project specifically says that for dates, using the Date module, you don't need the contextual_range_filter module...

Views Contextual Filter on date range


Always the same error when drush sup (to upgrade from 6.x to 7.x) is running for a certain time

Question: i'm hardly trying to upgrade my Drupal 6.x installation to 7.x with the help of drush.
I'm using the command drush sup @dev2 -v -d
Every thing's working fine until Major Upgrade Step 15. I try to use the choice: Automatically enable and upgrade all modules remaining in list.
But when drush updates about 3-6 modules in the list, i'm getting this error and no more modules can't be processed without showing the same error message.
... some other modules processed (votingapi,xmlsitemap,util, dblog_common, etc...)....

Then the part with the error message:
Upgrading Contrib Modules from Drupal 6 to Drupal 7 Step 1

Upgrading module: userpoints

Check your notes, and the UPGRADE.txt files inside each module, to see if any special upgrade instructions apply
There is no UPGRADE.txt file in userpoints
Drush will now do the step 'Begin upgrade of module userpoints'.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Upgrading Contrib Modules from Drupal 6 to Drupal 7 Step 2
Upgrading module: userpoints
Fully remove the old module directory inside sites/all/modules/
Note that Drush builds the target site in a new directory; the modules directory therefore starts off empty, and there is therefore no need to delete anything. If there is for some reason an old
module directory in place, Drush will automatically delete it when downloading the new module.
Skipping optional step.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Upgrading Contrib Modules from Drupal 6 to Drupal 7 Step 3
Upgrading module: userpoints
Download, unpack and move the new module directory to sites/all/modules/
  Drush has a cached version of userpoints at /Users/dennis/.drush/cache/@self-d6-to-dev2-d7/project_cache/disabled/userpoints. The destination directory is /Users/dennis/Sites/dev2/sites/all/modules/userpoints

  Drush will automatically do this step now.
  Calling _drush_recursive_copy(/Users/dennis/.drush/cache/@self-d6-to-dev2-d7/project_cache/disabled/userpoints, /Users/dennis/Sites/dev2/sites/all/modules/userpoints) [1044.77 sec, 102.01 MB]      [debug]

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Upgrading Contrib Modules from Drupal 6 to Drupal 7 Step 4
Upgrading module: userpoints
Enable the module

Then I've this output:
Drush will automatically do this step now.
Backend invoke: /usr/bin/php /usr/local/drush/drush.php --php=/usr/bin/php  --backend=2 --verbose --debug --root=/Users/dennis/Sites/dev2 --uri=default  pm-enable userpoints 2>&1 [1045.13 sec,   [command]
102.03 MB]
/usr/bin/php /usr/local/drush/drush.php --php=/usr/bin/php  --backend=2 --verbose --debug --root=/Users/dennis/Sites/dev2 --uri=default  pm-enable userpoints 2>&1 [1045.13 sec, 102.04 MB]         [notice]
Bootstrap to phase 0. [0.01 sec, 4.96 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 5.25 MB] [bootstrap]
Cache HIT cid: 5.9-commandfiles-0-beab8c3c129fe63a55d60d824a695615 [0.02 sec, 5.27 MB]                                                                                [debug]
Bootstrap to phase 0. [1045.34 sec, 12.42 MB]                                                                                [bootstrap]
Bootstrap to phase 6. [1045.37 sec, 12.42 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [1045.37 sec, 12.43 MB]                                                                                [bootstrap]
Initialized Drupal 7.22 root directory at /Users/dennis/Sites/dev2 [1045.41 sec, 14.49 MB]                                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [1045.41 sec, 14.49 MB]                                                                                [bootstrap]
Initialized Drupal site default at sites/default [1045.41 sec, 14.5 MB]                                                                                [notice]
Cache HIT cid: 5.9-commandfiles-2-c32acd775c18a90c5b41d0fc9accf5ab [1045.42 sec, 14.5 MB]                                                                                [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [1045.42 sec, 14.5 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [1045.43 sec, 14.51 MB]                                                                                [bootstrap]
Successfully connected to the Drupal database. [1045.43 sec, 14.52 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [1045.44 sec, 15.52 MB]                                                                                [bootstrap]
Cache HIT cid: 5.9-commandfiles-5-efa59ca0aabb00a052dd01ef436dba54 [1045.64 sec, 41.46 MB]                                                                                [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_login() [1045.64 sec, 41.57 MB]                                                                                [bootstrap]
Successfully logged into Drupal as Gast (uid=0) [1045.65 sec, 41.76 MB]                                                                                [bootstrap]
Found command: pm-enable (commandfile=pm) [1045.65 sec, 41.76 MB]                                                                                [bootstrap]
Cache MISS cid: 5.9-commandfiles--a96edeebec832dfcac7c4c036542fd68 [1046.3 sec, 44.46 MB]                                                                                [debug]
Cache SET cid: 5.9-commandfiles--a96edeebec832dfcac7c4c036542fd68 [1046.3 sec, 44.47 MB]                                                                                [debug]
The following extensions will be enabled: userpoints
Do you really want to continue? (y/n): y
WD system: userpoints module enabled. [1046.76 sec, 51.18 MB]                                                                                [info]
WD actions: 3 orphaned actions (heartbeat_activity_delete_action, userpoints_action_grant_points, user_block_ip_action) exist in the actions table. Verwaiste Aktionen entfernen [1048.31 sec,        [info]
60.01 MB]
userpoints was enabled successfully. [1048.51 sec, 59.85 MB]                                                                                [ok]
Command dispatch complete [1048.51 sec, 59.79 MB]                                                                                [notice]
 Timer  Cum (sec)  Count  Avg (msec)
 page   3.085      1      3084.86

Peak memory usage was 61.74 MB [1048.51 sec, 59.78 MB]                                                                                [memory]

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Upgrading Contrib Modules from Drupal 6 to Drupal 7 Step 5
Upgrading module: userpoints

5. Run update.php again (you should have run it once already when upgrading core) and check for any message output.

Drush will automatically do this step now.
Backend invoke: /usr/bin/php /usr/local/drush/drush.php --php=/usr/bin/php  --backend=2 --yes --verbose --debug --root=/Users/dennis/Sites/dev2 --uri=default  updatedb 2>&1 [1048.99 sec, 102.08  [command]
MB]
/usr/bin/php /usr/local/drush/drush.php --php=/usr/bin/php  --backend=2 --yes --verbose --debug --root=/Users/dennis/Sites/dev2 --uri=default  updatedb 2>&1 [1048.99 sec, 102.09 MB]               [notice]
Bootstrap to phase 0. [0.01 sec, 4.96 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 5.25 MB] [bootstrap]
Cache HIT cid: 5.9-commandfiles-0-beab8c3c129fe63a55d60d824a695615 [0.02 sec, 5.27 MB]                                                                                [debug]
Bootstrap to phase 0. [1049.17 sec, 12.42 MB]                                                                                [bootstrap]
Bootstrap to phase 2. [1049.19 sec, 12.42 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [1049.2 sec, 12.43 MB]                                                                                [bootstrap]
Initialized Drupal 7.22 root directory at /Users/dennis/Sites/dev2 [1049.22 sec, 14.49 MB]                                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [1049.22 sec, 14.49 MB]                                                                                [bootstrap]
Initialized Drupal site default at sites/default [1049.22 sec, 14.5 MB]                                                                                [notice]
Cache HIT cid: 5.9-commandfiles-2-d0694fde84f442a7d33c2119cff575f2 [1049.23 sec, 14.5 MB]                                                                                [debug]
Found command: updatedb (commandfile=core) [1049.23 sec, 14.5 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [1049.8 sec, 28.17 MB]                                                                                [bootstrap]
Cache HIT cid: 5.9-commandfiles-3-ff795e0864da9d3c245f6727a8655b23 [1049.81 sec, 28.18 MB]                                                                                [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [1049.81 sec, 28.18 MB]                                                                                [bootstrap]
Successfully connected to the Drupal database. [1049.81 sec, 28.18 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [1049.81 sec, 28.19 MB]                                                                                [bootstrap]
Cache MISS cid: 5.9-commandfiles-5-6989c0ea5e3787ed00051dc86fc1390b [1049.99 sec, 45.45 MB]                                                                                [debug]
Cache SET cid: 5.9-commandfiles-5-6989c0ea5e3787ed00051dc86fc1390b [1050.01 sec, 45.45 MB]                                                                                [debug]
The following updates are pending:

userpoints module :
  7000 -   Update profile category setting, allow multiple categories to be displayed.
  7001 -   Add a few indexes to speed up contrib modules that query the `points` columns.   Add index on points columns in userpoints and userpoints_txn, as well as on the two  uid columns in userpoints_txn. No need to add a uid index in userpoints, as the  compound uid_tid index is used instead when needed.   Since these indexes are added in a 6.x update as well, they need to be conditional  in this update. Otherwise users get errors, which is bad.
  7002 -   Increase length of operation and entity_type columns.
  7003 -   Create the {userpoints_total} table.
  7004 -   Filling the {userpoints_total} table.

Do you wish to run all pending updates? (y/n): y
Backend invoke: /usr/bin/php /usr/local/drush/drush.php --php=/usr/bin/php  --backend=2 --verbose --debug --yes --root=/Users/dennis/Sites/dev2 --uri=default  updatedb-batch-process 31 31 2>&1   [command]
[1051.01 sec, 48.89 MB]
/usr/bin/php /usr/local/drush/drush.php --php=/usr/bin/php  --backend=2 --verbose --debug --yes --root=/Users/dennis/Sites/dev2 --uri=default  updatedb-batch-process 31 31 2>&1 [1051.01 sec,      [notice]
48.9 MB]
Bootstrap to phase 0. [0.01 sec, 4.96 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 5.25 MB] [bootstrap]
Cache HIT cid: 5.9-commandfiles-0-beab8c3c129fe63a55d60d824a695615 [0.02 sec, 5.27 MB]                                                                                [debug]
Bootstrap to phase 0. [1051.19 sec, 12.42 MB]                                                                                [bootstrap]
Bootstrap to phase 2. [1051.21 sec, 12.42 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [1051.21 sec, 12.43 MB]                                                                                [bootstrap]
Initialized Drupal 7.22 root directory at /Users/dennis/Sites/dev2 [1051.23 sec, 14.49 MB]                                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [1051.24 sec, 14.49 MB]                                                                                [bootstrap]
Initialized Drupal site default at sites/default [1051.24 sec, 14.5 MB]                                                                                [notice]
Cache HIT cid: 5.9-commandfiles-2-d0694fde84f442a7d33c2119cff575f2 [1051.25 sec, 14.5 MB]                                                                                [debug]
Found command: updatedb-batch-process (commandfile=core) [1051.25 sec, 14.5 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [1051.76 sec, 28.17 MB]                                                                                [bootstrap]
Cache HIT cid: 5.9-commandfiles-3-ff795e0864da9d3c245f6727a8655b23 [1051.76 sec, 28.18 MB]                                                                                [debug]
PDO::__construct(): MySQL server has gone away environment.inc:517 [1051.76 sec, 28.19 MB]                                                                                [warning]
SQLSTATE[HY000] [2006] MySQL server has gone away [1051.76 sec, 28.23 MB]                                                                                [bootstrap]
Drush was not able to start (bootstrap) the Drupal database.                                                                                [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with
the --uri parameter on the command line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
  Drupal version    : 7.22
  Site URI          : default
  Database driver   : mysql
  Database hostname : 127.0.0.1
  Database username : root
  Database name     : dev2db
  Default theme     : garland
  Administration theme: garland
  PHP configuration : /private/etc/php.ini
  Drush version     : 5.9
  Drush configuration:
  Drush alias files : /Users/dennis/.drush/aliases.drushrc.php
  Drupal root       : /Users/dennis/Sites/dev2
  Site path         : sites/default
  Modules path      : sites/all/modules
  Themes path       : sites/all/themes
  File directory path: sites/default/files
  Temporary file directory path: /tmp
  %paths            : Array

 [1051.77 sec, 102.18 MB]
PHP Fatal error:  Call to undefined function batch_get() in /usr/local/drush/commands/core/drupal/batch.inc on line 80
PHP Stack trace:
PHP   1. {main}() /usr/local/drush/drush.php:0
PHP   2. drush_main() /usr/local/drush/drush.php:19
PHP   3. _drush_bootstrap_and_dispatch() /usr/local/drush/drush.php:64
PHP   4. drush_dispatch() /usr/local/drush/drush.php:95
PHP   5. call_user_func_array() /usr/local/drush/includes/command.inc:175
PHP   6. drush_command() /usr/local/drush/includes/command.inc:175
PHP   7. _drush_invoke_hooks() /usr/local/drush/includes/command.inc:208
PHP   8. call_user_func_array() /usr/local/drush/includes/command.inc:334
PHP   9. drush_core_updatedb_batch_process() /usr/local/drush/includes/command.inc:334
PHP  10. _update_batch_command() /usr/local/drush/commands/core/core.drush.inc:1107
PHP  11. drush_batch_command() /usr/local/drush/commands/core/drupal/update_7.inc:246
PHP  12. _drush_batch_command() /usr/local/drush/includes/batch.inc:93

Fatal error: Call to undefined function batch_get() in /usr/local/drush/commands/core/drupal/batch.inc on line 80

Call Stack:
    0.0007     710016   1. {main}() /usr/local/drush/drush.php:0
    0.0298    5201720   2. drush_main() /usr/local/drush/drush.php:19
    0.1111   13019960   3. _drush_bootstrap_and_dispatch() /usr/local/drush/drush.php:64
    0.1753   15203400   4. drush_dispatch() /usr/local/drush/drush.php:95
    0.2077   15213792   5. call_user_func_array() /usr/local/drush/includes/command.inc:175
    0.2077   15214408   6. drush_command() /usr/local/drush/includes/command.inc:175
    0.2079   15215232   7. _drush_invoke_hooks() /usr/local/drush/includes/command.inc:208
    0.2087   15260392   8. call_user_func_array() /usr/local/drush/includes/command.inc:334
    0.2087   15261008   9. drush_core_updatedb_batch_process() /usr/local/drush/includes/command.inc:334
    0.2128   15873488  10. _update_batch_command() /usr/local/drush/commands/core/core.drush.inc:1107
    1.1880   32966920  11. drush_batch_command() /usr/local/drush/commands/core/drupal/update_7.inc:246
    1.1904   33063392  12. _drush_batch_command() /usr/local/drush/includes/batch.inc:93

Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Call to undefined function batch_get() in /usr/local/drush/commands/core/drupal/batch.inc, line 80 [1052.29 sec, 102.18 MB]
The external command could not be executed due to an application error. [1052.43 sec, 102.18 MB]                                                                                [error]
Finished performing updates. [1052.43 sec, 49.08 MB]                                                                                [ok]
Command dispatch complete [1052.43 sec, 49.03 MB]                                                                                [notice]
 Timer  Cum (sec)  Count  Avg (msec)
 page   3.138      1      3138.28

Peak memory usage was 50.98 MB [1052.43 sec, 49.02 MB]                                                                                [memory]
updatedb failed for userpoints [1052.63 sec, 102.22 MB]                                                                                [error]

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Upgrading Contrib Modules from Drupal 6 to Drupal 7 Handle Update Errors
Upgrading module: userpoints

If you have errors when you run the update.php script:

Note any error messages you see. Restore your site to its previous state, using the file and database backups you created before you started the upgrade or update process. Do not attempt to do
further updates or upgrades on a site that had update problems. Consult one of the support options listed on http://drupal.org/support.
Drush cannot do this step; you must perform it manually.

What would you like to do?
 [0]  :  Cancel
 [1]  :  I will do this step manually.

You can see, it is processing the userpoints module in this case. But for example, when i directly choose to update this module, there is no error message.
Please help me with this. Every suggestion is appreciated.
Comment: I'd make sure first that mysql don't go away
Comment: Right, this is the problem, but how?
Comment: Increase wait_timeout in your my.cnf. Also see the comments here https://drupal.org/node/587250
Comment: I already set my timeout to 6000,but this didn't help. As you can see there is no more information, why mysql gone away. I also looked into the mysql general log, but there is also no error or something else, which could cause mysql to go way. Could it be that drush ignores the parameters in my.cnf, and i have to put a "db_query('SET wait_timeout = 600'); " somewhere manually? Thanx for your advice so far.
Comment: No, drush doesn't ignore .my.cnf. What version of mysql?
Comment: I use version 5.6.12.
Comment: Well, we're going offtopic I guess. In addition to `wait_timeout`, other reasons are `max_allowed_packets` and since mysql 5.5 `open_files_limit`, due to changes in the memory allocator of InnoDB. See http://dev.mysql.com/doc/innodb-plugin/1.0/en/innodb-performance-use_sys_malloc.html for reference.
Answer: Follow the advice in the error message: restore the site to its previous state. To do this, just run drush sup again, select the appropriate restore option, and then cancel drush sup.  (Don't run with --auto).
From here, you just need to get userpoints working.  You said: "When I directly choose to update this module, there is no error message."  After userpoints has updated, run drush sup again; it should continue, and allow you to upgrade your other modules.
If you can't get userpoints to upgrade, ask for help in the userpoints issue queue.  First search it and see if there are any existing issues related to the upgrade path.
Comment: No, userpoints is not the problem. Its something with the batch process itself that cause mysql to go away. As i mentioned above, i have no problem upgrading all the modules on by one. Thanx for your help.
Comment: I think that jonhattan is on to the right answer above. Given the number of times that you'll do a major upgrade, you might consider just doing it once (restarting as necessary), and then use drupal-to-drupal migration to update content until your migration is done. See: https://drupal.org/project/migrate_d2d
Comment: But can anyone please tell me, how to get more information how this error was caused, cause "MySQL server has gone away" doesn't tell me enough. Possibly i can dig deeper to get there, but how? Maybe something like "SQL : INSERT INTO ...." , or anything else.
Comment: That's never happened to me.  Maybe try asking in a mysql support board?  c.f. http://dba.stackexchange.com/questions/tagged/mysql


gdb: see unused struct typedef

Question: I am having trouble seeing all the typedefs of a struct I defined. In particular, if a typedef is not used, gdb does not show it when the type is printed. Here's an example:
struct D
{
  typedef double dtype;
  typedef int itype;
};

int main(int /*argc*/, char** /*argv*/)
{
  D::dtype t;

  t = 2;
  return 0;
}

When I run gdb, I then type ptype D, but I get only the following
(gdb) ptype D
type = struct D {
    typedef double dtype;
}
(gdb)

Is there a way to print all the typedefs even if they are not used?
Miscellaneous info:

I have set print type typedefs on
I compiled with debug symbols: g++ -g -o test main.cpp
gdb version is 7.10
gcc version is 5.3
Comment: Yes, but you cannot nest typedefs into structs in C. I.e. this very issue does not exist in C.
Comment: Why is this tagged [С] in addition to [С++]? This appears to be a C++-specific question.
Comment: Well, the typedef keyword exists also in C, no?
Comment: Yes.  This is not a valid C program
Comment: Ah, ok. I code mostly in C++ and did not now that. I'll take it down.
Comment: I think this is just an optimization that GCC is making. Since the second `typedef` is never used, there's no need to store information about it in the executable file.
Comment: Have you tried `-O0` to disable all optimizations?
Comment: -O0 should be the default, at least according to gcc webpage https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html. Anyways, I tried, and got the same result.
Answer: GCC by default omits unused types from debug info.  If you really need this type to appear in the debug info, use -fno-eliminate-unused-debug-types.  However, as the manual warns, this will bloat the resulting debug info.
Comment: YES! Thank you, that worked! And you're right, this should be an extreme solution. Point is, in the real code (not the example I posted) the second typedef SHOULD be used, but I can't access it from gdb, which makes me think it is not used. However, I wanted to check whether or not it was correct to start with.

Thanks!

gdb: see unused struct typedef


Why does this chord progression function?

Question: I'm learning music theory in school and I stumbled into this chord progression at home. I think it is cool but I want to know why it is cool.
The chord progression is: Cmaj7 Gmaj7 B♭maj Amin7
Is it just because I have heard the chord progression before?
Comment: It would be interesting:  what is the next chord after Amin7. I am attending a D7 and then the progression could be in Gmaj and the function would be IV7-I7-bIII7-(IIm7-V7) but it can also stand alone ...
Comment: Try to remove or change things note by note until it becomes uncool. Remove all tensions, just C G Bb Am. Still cool? Play just the bass notes - still cool? Does "Cmaj7 Ebmaj7 Bbmaj7 Dbmaj7" sound cool too? "Cm7 Gm7 Bbm7 Fm7" sound cool? How about "Cm7 Gm7 Bbm7 Fm7 Abm7 Ebm7 F#m7 C#m7 Em7 Bm7 Dm7 Am7" repeat from start, sound cool?
Answer: It's a common progression in classical harmony if the middle chords are in first inversion. One has C,B,Bb,A as a bass line with chords above, C,G6,Bb6,a (with appropriate sevenths if wanted). It's a portion of the "lament descent" which is often used to express sadness; with a different bass, this interpretation may not hold. A nice continuation would be f6m,G which moves chromatically from tonic to dominant.
Comment: wonderful description: *the "lament descent" which is often used to express sadness*! It sounds really sad, especially with the major 7 chords and the inversions like you say. I will use this progression in my next composition. But how will have been the voice leading in classical music? Do you have some examples - as it's a common progression?
Comment: Bach's St Matthew Passion (or the other one) and Dido's Lament by Purcell. Also the entire "32 Variations in C Minor" by Beethoven uses this construction. Beethoven uses a different harmonization from the usual Baroque forms.
Comment: would we need a `C` _minor_ chord to consider this the lament bass? The examples from Bach, Purcell, and Beethoven are minor key.
Comment: Normally it is in a minor key (not necessarily a minor but any minor key). I suppose one could start in a major and adjust the voice leading according. Other  (diatonic based patterns) are sometimes used in either mode. The cycle of fifths works in both major and minor (maybe a bit better in minor because of the ii0-V-i ending whereas in a major key the v00i occurs early in the pattern sometimes this vii0-iii or vii0 is skipped in a major key(, The "Romansa" is used either way as I,V, vi, iii (or I64), IV, I6, ii6 (or IV) V or i,v,VI,III (or i64) IV, I6, ii6 (or IV) V. Either work.
Answer:
is it just because I have heard the chord progression before?

Probably because of this.
It is a most common progression in Pop music. It won't be easily described by functional harmony, even not by modes. I hear the progression in G-Major but it mustn't be.
It reminds me of the even more common "Don't go chasing waterfalls" (TLC) e.g. C-G-Bb-F!
(If we start this turn with Bb we get: Bb-F-C-G and this would be the circle of 5th in the direction of the sharps.)


Modificar propriedade de um botão ao fechar modal bootstrap

Question: Tenho uma tabela com um botão para adicionar um comentário sobre o item daquela linha. Nesse botão tenho um class = adicionar que me permite aplicar à todos com essa classe a ação de abrir um modal do bootstrap. Meu problema é que não sei identificar qual desses botões foi o ativador do modal para mudar o estilo dele, que ao invés de ficar um + para adicionar, deve ficar um ícone para visualizar. Alguém teria uma solução de como saber qual botão .adicionar foi acionado depois que o usuário clicar no botão btn_add_observacao?

            #
            Aluno
            Nota
            Obs.
            Ação

            1
            Rafael
            6.58

                <button type="button" class="btn btn-xs btn-success adicionar" title="Adicionar Observação" data-toggle="modal" data-target="#modal_observacao">

                </button>

                <button type="button" class="btn btn-xs btn-danger remover">
                     Remover
                </button>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Observação

                Digite no espaço abaixo a observação para esse pedido
                <textarea class="form-control" id="texto_observacao" name="texto_observacao" rows="5"></textarea>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="btn_add_observacao" name="btn_add_observacao" >Adicionar</button>

Comment: Poste a parte relevante de seu código o para entendermos melhor.
Comment: Poste o código javascript que você já tem... (apenas as partes relevantes)
Comment: Ainda não fiz o javascript. Através dos atributos `data-` nos botões, o js do bootstrap faz aparecer e esconder o modal.
Answer: A partir do Bootstrap v3.0.0, podes apurar o elemento que fez abrir a modal da seguinte forma:
$('#id-da-modal').on('show.bs.modal', function (e) {
    var $botaoQueAbriu = $(e.relatedTarget);
});

Ver demonstração no JSFiddle.


How can I logon to windows automatically using a smartcard?

Question: Is it possible to logon to Windows automatically using a smartcard? I don't want to have to enter the PIN when the computer boots up.
This is supposed to be like the auto-login feature where you can store the default username and password in the registry so you aren't prompted and are logged in automatically.
Answer: While I have no full answer, the snippets may help a bit. Actually a smart card for login is intended to provide a two factor authorization. You must posess the card and know the PIN. If I understand correctly, you want a one-factor authorization, where just the posession of the card is sufficient. From the card view it is possible, to have an authorization key on the card, which is always usable. This may happen either by directly stating an access rule "ALWAYS" for the key in question, or by requiring a PIN but have this PIN disabled (like for mobile phone SIMs). I have no idea, whether your target version of Windows accepts a disabled PIN and consequently does not pop up an entry form but directly starts the login process.
Comment: Thanks for the answer. What I'm trying to do is automate the login process. I hoped that there would be a way to automate the entry of the PIN at the Windows login screen but I haven't been able to find any method as yet.


C# Verify Json string via signature and RSA public key

Question: I'm creating an IAP plugin for the local Android market that I think has similar API as google play.
I build an Android side and it will return all response from the market to the unity c# side.
All part working fine but I can't figure out how to verify the signature of the response.
I'm new in cryptography and searching day to day about this.
Please correct me if I'm wrong.

They use a hash algorithm to sign data and encrypt that hash with private key.
I must decrypt signature with public key and compare hashes.

This is my public key (Base64):
MIHNMA0GCSqGSIb3DQEBAQUAA4G7ADCBtwKBrwDltnT/AaF3oMt+F3lza5JEvce0GLS1L9v9Z53lQ3LNluGk0eI2ukgWm7tAiIOLQgn11Sb9mW2VWkYTWGnZ1AZtY0GwdUQJUr7u3CWNznE6XH4UCVOVhGDCLnFrG8BcfDelhcfReGZQ3izOefhc4Oq6vZf5PfLwximK+FH27fR6XL8vg3yyK4LSwT764Dfd6H3IGes6EdTx/C3C690jdyMvhi2Q3qBiqfepHzW/jV8CAwEAAQ==

This key is in ASN.1 DER format.
I break it out and find this data:
SEQUENCE
  SEQUENCE
    OBJECT IDENTIFIER 1.2.840.113522.214.171.124 rsaEncryption(PKCS #1)
    NULL
  BIT STRING
    SEQUENCE
      INTEGER 969837669069837851043825067021609343597253227631794160042862620526559…
      INTEGER 65537

As I read on net first INTEGER is Modules and second INTEGER is Exponent

So in c# write a code like this =>
var parameter = new RSAParameters
{
    Modulus = HexToByteArray(/* "first_INTEGET" */),
    Exponent = BitConverter.GetBytes(/* "second_INTEGER" */)
};

Market send me a Json like this:
{"orderId": "0j8oJgE0Bett-neB", "purchaseToken": "0j8oJgE0Bett-neB", "developerPayload": "payload", "packageName": "com.some.market", "purchaseState": 0, "purchaseTime": 1520676644872, "productId": "card-1"}

The signature is like this:
hTFeQd25PZJ2DhGmXd0eO+C+oBeWsg983I4e5ztXtKAUrOIaNBaqAxHU3vW8acBs1I9fE5cxx/DI/sQGY4QSvpDnSm9aYz3do3joHPOXIVvXjSJfejxwzp9DKMUPd6LrgtxkaGevG+94NuKHFxpCdZlovEPXRJZyEznbASuYLqeW0KjP3jnvvw2O5iNlQRdh98h4Q18bSsaxq9zaRKExFLHkhNf/yO5m84kRB1G8

I'm searched for a method to do this but I don't know which method is true for me.
My verify code is this:
using (var rsa = new RSACryptoServiceProvider())
{
    rsa.ImportParameters(parameter);
    var hash = new SHA1Managed();
    bool dataOK =
    rsa.VerifyData(hash.ComputeHash(Encoding.UTF8.GetBytes(json)), CryptoConfig.MapNameToOID("SHA1"), Encoding.UTF8.GetBytes(signature));
}

How truly convert signature to byte[] to verify? (with encoding or what???)

I'm searching a lot but more search more confuse.
Am I going the wrong way or using wrong method or ...?

Why should workflow be complicated?

Can anyone help me, please?
Thanks.
Comment: The modulus and the public exponent are simply decimal integers, not hex.
Comment: Create a BigInteger using it, then call the `ToByteArray()` method, then reverse the order of the bytes using a simple method you have to write. `BigInteger.ToByteArray()` returns a little-endian array but RSAParameters fields are big-endian.
Comment: signature is base-64 also by the way, why are you using `Encoding.UTF8.GetBytes` for it?
Comment: As for "Why should workflow be complicated?" - that's because ASN.1 DER is not "native" format for .NET cryptography, for whatever reason. Usually other formats are used (such as raw public\private keys, or keys in xml format). So it's complicated because there is no built-in way to convert ASN.1 DER encoded key to format expected by .NET (but you can find code to do that on internet). Also you might have better luck with BouncyCastle (custom crypthography library for .NET).
Comment: Thanks a lot, How can i convert this long decimal to byte array?
Comment: From `MSDN` `BigInteger Available since 4.0`. I working with Unity with Mono similar to 3.5, Just 0.5 version distance to Solve this problem :)
Comment: Oh, I Saw '/' in it and forget that it's one of the Base64 chars. thanks.
Answer: OK, I'll answer in order:

They use a hash algorithm to sign data and encrypt that hash with private key. I must decrypt signature with public key and compare hashes.

No, that's not correct. You should use a signature verification method, as you're currently doing. Seeing signature as encryption of a hash is incorrect; even the latest RSA standards go out of their way to explain this. For RSA the internal padding method is different. For ECDSA there is no direct encryption/decryption possible using the same scheme.

As I read on net first INTEGER is Modules and second INTEGER is Exponent

Yes, although it is spelled modulus, not modules. It is the public exponent, there is also a private exponent for the private key. Also without the caps.

How truly convert signature to byte[] to verify? (with encoding or what???)

Standard Base 64 is already mentioned in the comment section. Note that the key and signature size are not common (but that's OK in itself).

Why should workflow be complicated?

Well, somebody has to code it in the end and crypto is hard. But to make it easier for you: the entire ASN.1 structure is called a SubjectPublicKeyInfo structure; if you look on the internet you will find pre-made code to import from such a structure.

To finally verify the structure: make sure that you use the correct signature format (RSA-PKCS#1 v1.5 or RSA-PSS) and that you know exactly which binary data is fed to the signature generation function. For instance, the signature over the JSON could be in ASCII or UTF-8 or it could be in UTF-16 LE or BE.
Better ask the creator of the signature.
Comment: You're welcome. Note that the signature itself **is** the byte array. How it is encoded depends on the protocol.
Comment: You're my new Cryptography hero. first hero in that type :)


How are Band Scores and Piano Scores Similar or Different?

Question: There are two sites I'm looking at that for a the same music book (same ISBN), one lists it as a 'band score' and the other a 'piano score'.
I want to buy music for the piano, so if it's really a band score, it might not have music for the piano. However, I don't know what constitutes a band score. Are band scores like short scores in that the music is playable by all instruments or does it have music for piano with accompaniment staves for other instruments in a band (or is it something else entirely)?
Furthermore, is it safe to imply that all 'band scores' within this context have music for piano players?
Comment: Well, it may help to peek at this http://otaku.com/products/36191 :-) .
Answer: I think in this context, "Piano Score" is a mistranslation. That would usually indicate an arrangement that has been condensed from an original instrumentation down to piano plus solo instrument or voice.
Carl Witthoft's link contains the following image:

The instrumentation is drums, guitars, and voice (and I would call this a "Band Score"). If the products you're looking at all have the same ISBN, they're all the same book -- if the Piano Score version was actually different material, it would have a different ISBN.
This doesn't mean that all Band Scores don't have keyboards in them, but it appears at though this one doesn't, or at least the song that is included in that product image. Perhaps other songs in the book do have a keyboard part, but clearly the music is not being condensed down for a single piano player.
Comment: Yeah, going by the picture it doesn't seem to be arranged for a piano, at least for that page. However, by that link there are also 260 pages, and there's 18 songs, which is about 14.5 pages per song. The longest piano score piece I've come across has been ~5 pages. For these types of things is it plausible to have a score for say drum/guitar/vocals together, and then also have a separate score for other instruments such as the piano for the sake of not having 5+ staves together, making readability a pain?
Comment: No, whenever I've seen scores in this format, the piano or keyboard is alongside the other instruments. The word "score" indicates that everything is together (and not in "parts").
Comment: Thanks. Contacted the seller and they confirmed as you said, all songs are only drums/guitar/vocals.
Answer: It depends on what book/score it is, as each is different.
If the "band score" only has 1 copy, I would assume it's a complete list for all instruments, sort of like a conductor's score, which shows all instrument notes at once.
The "piano score" likely is a shortened, piano-only version of the band score.
This will vary from piece to piece. It might even mean the piece was originally not written for piano (but rather a band), and re-written for piano in the correct clefs.


Trying to redirect a docker container to another through nginx

Question: As the title say trying to reverse proxy.
Using an app with port 500 inside container with port exposed for 5000.
The nginx is on another container with port 80 exposed and publish to 8080.
Both containers are in the same network that I've created.
On Nginx container I've deleted the default.conf and created a new one
as follows:
server{
  listen 80;
  location \ {
    proxy_pass "http:0.0.0.0:5000";
    proxy_set_header Host $host;
    proxy_redirect          off;
    proxy_set_header        X-NginX-Proxy true;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

I also restarted the nginx so it starts with this .conf
when trying to access using the url: http://172.17.0.1:8080/ which is the gateway to the network i only get 404 not found.
On the Nginx container i get this message

"/etc/nginx/html/index.html" is not found (2: No such file or
  directory), client: 172.17.0.1, server: , request: "GET / HTTP/1.1",
  host: "172.17.0.1:8080"

Its like he is not redirecting only searching for the index file of the default.conf
Through nginx -T i can see that the configuration above is loaded.
Any one can help with the forwarding of this?
Comment: a typo here perhaps (or maybe the issue)

> location \ { ... }

the \ (backslash) is an escape character there, shouldn't be "/"?
Comment: rip im dead. That was the forwarding problem. Although now i have a new error. Connection refuse. After using nmap to check if the exposed port of the container is open it seems filtered the 5000. As a result is refusinghte connection :/
Answer: the location should be / not \
and also try to put the other container name or it's IP in the proxy_pass
Comment: yea it was /.
I the ip is correct since they are inside the same net work. But getting connection refused now (tried the docker ip of te network and did not work too just to be safe). New problem pop up.
Comment: what's the output of you trying to telnet from inside the container to the other one's IP and port ?
Comment: # telnet n2 5000
Trying 172.18.0.3...
telnet: Unable to connect to remote host: Connection refused
Comment: are you using publish or expose for the docker ports you can check the following URL for more help https://nickjanetakis.com/blog/docker-tip-59-difference-between-exposing-and-publishing-ports
Comment: expose since its the same network, testing inside the nginx container


Drupal ignoring changes to settings.php

Question: I made a copy of one of my drupal sites and I'm attempting to set it up to use a different database but for some reason it's ignoring changes to my settings.php file. My settings.php file is in sites/default/settings.php and contains the following
$databases['default']['default'] = array (
        'database' => 'my_db_database',
        'username' => 'my_db_user',
        'password' => 'my_db_password',
        'host' => 'my_db_host',
        'port' => '3306',
        'driver' => 'mysql',
        'prefix' => '',
        'collation' => 'utf8mb4_general_ci',
);

However the changes I made to it don't seem to take. It's still using the old database. As a test I even put in incorrect information and tried commenting everything out to see if I can break it, but there was no effect. I also checked to make sure there was no local.settings.php file.
Is there something that needs to be done to reload the settings.php file. If not is there a way to see what settings.php file is being used in case there's another file overriding it?
UPDATE: Turns out the issue was a dummy mistake on my part. The domain was pointing to the wrong server. However I'm not closing this question because I believe these answers could be helpful to others in similar situations.
Comment: Maybe related to (compiled) PHP code caching. Modern PHP versions come with Opcache. If your webserver is using PHP in FastCGI or PHP-FPM mode, you may have to restart the PHP services and/or your webserver for code changes to take effect. Also flushing your Drupal caches might be of help.
Comment: Can you share the rest of your settings.php file? Are there any includes in it?
Answer: The settings.php file is usually 444 as permission, check if the "last modified" is as you aspect, otherwise you need to change the permissions temporaly to 777 in order to overwrite it
Answer: Check with including namespace.  Also, check if any other code override configuration or do you enabled settings.local.php. Add this code to the bottom of settings.php
 $databases['default']['default'] = array (
  'database' => 'my_db_database',
  'username' => 'my_db_user',
  'password' => 'my_db_password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

Drupal ignoring changes to settings.php


Inserir variável em script

Question: Tenho o seguinte script funcionando normalmente
@echo off

if %time:~0,8%  LEQ 11:59:59 goto manha
if %time:~0,8%  LEQ 17:59:59 goto tarde
if %time:~0,8%  LEQ 23:59:59 goto noite

:manha
    echo "BOM DIA"
    Pause

:tarde
    echo "BOA TARDE"
    Pause

:noite
    echo "BOA NOITE"
    Pause

Gostaria de inserir uma variável para poder utilizar em outras linhas, Exemplo do codigo abaixo que não deu certo:
@echo off

if %time:~0,8%  LEQ 11:59:59 goto manha
if %time:~0,8%  LEQ 17:59:59 goto tarde
if %time:~0,8%  LEQ 23:59:59 goto noite

:manha
    set saudacao= "BOM DIA"

:tarde
    set saudacao= "BOA TARDE"

:noite
    set saudacao= "BOA NOITE"

echo %saudacao% , Resto da frase
pause

Alguem sabe no que estou errando?
Agradeço desde já!
Answer: Amigo, neste segundo script falta colocar o goto após cada sentença:
Exemplo:
@echo off

if %time:~0,8%  LEQ 11:59:59 goto manha
if %time:~0,8%  LEQ 17:59:59 goto tarde
if %time:~0,8%  LEQ 23:59:59 goto noite

:manha
    set saudacao= "BOM DIA"
    goto fim

:tarde
    set saudacao= "BOA TARDE"
    goto fim
:noite
    set saudacao= "BOA NOITE"
    goto fim
:fim
   echo %saudacao% , Resto da frase
   pause

Comment: Obrigado mais uma vez! :D
Comment: Por favor amigo finalize os dois itens e se puder me avalie. Abraços.
Comment: preciso de 15 de rep. para avaliar ;/ sorry

Inserir variável em script


Drush DB connection on MAMP

Question: I have a slight issue in connecting Drush to my MAMP localhost DB. Already tried multiple solutions like changing host from localhost to 127.0.0.1, and editing MAMP files like this suggestion.
It seems my socket location is slightly different from most examples I see on the web, being var/mysql/mysql.sock rather than tmp/mysql.sock. I installed via homebrew, if that's helpful.
Super new to drush, and command line in general, so any help much appreciated. All file transfers (like dl) work fine, just anything DB related throwing an error. Thanks!
<code>    PDO::__construct(): [2002] No such file or directory (trying to connect  [warning]
via unix:///var/mysql/mysql.sock) environment.inc:523
Command pm-enable needs a higher bootstrap level to run - you will need  [error]
to invoke drush from a more functional Drupal environment to run this
command.
The drush command 'en views' could not be executed.                      [error]
Drush was not able to start (bootstrap) the Drupal database.             [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
 * connect the database through a socket. The socket file may be wrong or
the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version        :  7.24
 Site URI              :  http://default
 Database driver       :  mysql
 Database username     :  root
 Database name         :  DB_name
 Default theme         :  garland
 Administration        :  garland
 theme
 PHP executable        :  /usr/bin/php
 PHP configuration     :
 PHP OS                :  Darwin
 Drush version         :  6.1.0
 Drush configuration   :
 Drush alias files     :  /Users/UserName/.drush/pantheon.alias
                          es.drushrc.php
 Drupal root           :  /Applications/MAMP/htdocs/landmark/landmark-l
                          earning
 Site path             :  sites/default
 File directory path   :  sites/default/files
</code>
Comment: Did you just try installing drupal via the install.php file?
Comment: Yes, D7 is up and running on localhost, no issues there. The issue is solely around connecting Drush to that DB. Thanks for checking!
Comment: you also tried the symlink ? (like: `ln -s /tmp/mysql.sock /var/mysql/mysql.sock`)
Comment: Remy, yes, just tried that as well with no luck. Does the unix:/// in front of the socket path affect that?
Comment: The background for truly troubleshooting and arriving at the answer above is clearly explained over in this gem of a post:  http://drupal.stackexchange.com/a/174128/3167  which is conveniently hidden away due to a non-generalized post title, so I'm sharing here for the next time I stumble upon this issue and forget exactly what to search for to find that post!
Answer: OK, finally got it working:
<code>sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock
</code>
Thanks to Remy for putting me on the right track, and This drupal.org post.
Seems it was that I needed to make a directory first... Rookie move.
Comment: for people who already have the symlink http://drupal.stackexchange.com/a/143930/9449

Drush DB connection on MAMP


how to display Action bar above TabNavigation bar in android

Question: here is my code to create action bar
<code>// enabling action bar app icon and behaving it as toggle button
    ActionBar actionBar=getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);
    actionBar.setBackgroundDrawable(new ColorDrawable(color.white));
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    for (int i=1; i <= 3; i++) {
        Tab tab = actionBar.newTab();
        tab.setText("Tab " + i);
        tab.setTabListener(this);
        actionBar.addTab(tab);

    }
</code>
here is output of my code

But I wont display like this

Please anyone help me for this
Thanks in advance...
Answer: Quoting docs

The tabs provided by the ActionBar are ideal because they adapt to
  different screen sizes. For example, when the screen is wide enough
  the tabs appear in the action bar alongside the action buttons (such
  as when on a tablet, shown in figure 7), while when on a narrow screen
  they appear in a separate bar (known as the "stacked action bar",
  shown in figure 8). In some cases, the Android system will instead
  show your tab items as a drop-down list to ensure the best fit in the
  action bar.

Figure 7  and 8 can be viewed @ http://developer.android.com/guide/topics/ui/actionbar.html
If you are looking for slidingtab's
https://developer.android.com/samples/SlidingTabsBasic/src/com.example.android.common/view/SlidingTabLayout.html
Similar to
Android - Google Play like tabs
Comment: thanks.. I run app on diff device it work.. but according to device tab is moving?


Comparing non-nested models estimated by Weighted Least Squares

Question: It's very common for social scientists to have binary or ordinal indicators (e.g., yes/no interview items or likert-rated questionnaire items). It's also very common for them to model their ordered/non-ordered categorical data with structural equation model (SEM)/factor analytic (FA) techniques using weighted least estimators (e.g., WLS, robust WLS or WLSMV).
Yet, as far as I can tell, there is no established method for comparing two SEM/FA models which are not nested. With maximum likelihood estimators, people usually use AIC and BIC but they are not available for WLS estimation. I've seen some use fit statistics such as CFI, TLI, and RMSEA, but have not managed to find an empirically grounded criteria indicating a substantial change in model fit (e.g., compared to the less restricted model, an increase in RMSEA of say .05 suggests that the model fit worsened meaningfully).
Can anyone recommend an empirically credible criteria for model comparison using WLS estimation for non-nested models? If there is no empirically tested criteria, perhaps share your experience of what you see in the field.
Answer: My understanding of the field is that the establishment and verification of ubiquitous fit statistics or fit criteria for WLS estimation is still an open topic.  That is to say, there are no established statistics, nor are there rigorously empirical criteria that have been well-established (via simulation research) to assess model fit, in general, let alone for model comparison.  This is not to say that there are not criteria that have not been proposed, but they have not been universally accepted.  (Of course, if I have missed something in the literature...please share any useful references).
As the fit statistics are sparse or currently non-existent, the ability to compare nested and non-nested models also is not readily available.  However, there is one advantage to binary and ordinal predictors that can be exploited.  It is possible to compare the contingency tables of the observed counts to the predicted counts.  Thus, one could at least ask if different models predict equally well or better just based on chi-squared statistics.  Of course, this requires non-zero entries...and the larger the number of variables being predicted, the more likely this will be an issue.
Happy to elaborate on anything (if I can), and I hope this is helpful.  Again, if I am not as current with the literature as I should be, any and all corrections are welcome.
Comment: Would you give the same reply today?


Superimposed JPanels not lining up

Question: I am trying to make a paintable JPanel, with optional gridline display. To do this, I have a custom JPanel, which makes another JPanel that holds just the gridlines. That way, I can show / hide the grid lines without ever removing what is on the canvas.
All seems to be working, except for some weird alignment issues I can seem to pin down. When I start drawing some squares, they are only a few pixels above the gridlines. How can I fix this so that both panels are displaying EXACTLY on top of one another?
Here is an example of the issue:

package com.carvethsolutions.guilib.customcomp;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/**
 * A custom component for displaying a grid
 */
public class GridCanvas extends JPanel implements MouseListener {

/**
 * Width and height of the canvas, in pixels
 */
private int width, height;

/**
 * How many pixels represent one square on the grid
 */
private int gridScale;

/**
 * The separate panel that holds the grid lines
 */
private JPanel gridPanel;

private boolean gridLinesVisible = true;

/**
 * Holds color selections
 */
private Paintbrush paintbrush;

public GridCanvas() {
    super();
    width = 500;
    height = 500;

    setupComponent();
}

public GridCanvas(int width, int height) {
    super();
    this.width = width;
    this.height = height;

    setupComponent();
}

/**
 * Private function to prepare the component.
 */
private void setupComponent() {
    gridScale = 50;
    this.setPreferredSize(new Dimension(width,height));
    this.setBackground(Color.WHITE);

    this.addMouseListener(this);

    gridPanel = new JPanel() {
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            // Vertical Lines
            for (int x = gridScale; x <= width; x += gridScale) {
                g.drawLine(x, 0, x, height);
            }

            for (int y = gridScale; y <= height; y += gridScale) {
                g.drawLine(0, y, width, y);
            }
        }
    };

    gridPanel.setVisible(gridLinesVisible);
    gridPanel.setPreferredSize(this.getPreferredSize());
    this.add(gridPanel);

    this.setSize(gridPanel.getSize());
    paintbrush = new Paintbrush(Color.black);
}

/**
 * Enable or disable grid lines from appearing on the Canvas
 */
public void toggleGridlines() {
    gridLinesVisible = !gridLinesVisible;
    gridPanel.setVisible(gridLinesVisible);
}

/**
 * Invoked when the mouse button has been clicked (pressed
 * and released) on a component.
 *
 * @param e
 */
@Override
public void mouseClicked(MouseEvent e) {
    int x = e.getX() / gridScale;
    int y = e.getY() / gridScale;

    System.out.println("mouseClicked Event : (" + x + ", " + y + ")");

    this.getGraphics().setColor(paintbrush.getColor());
    this.getGraphics().fillRect(x * gridScale, y * gridScale, gridScale, gridScale);
}

/**
 * Invoked when a mouse button has been pressed on a component.
 *
 * @param e
 */
@Override
public void mousePressed(MouseEvent e) {

}

/**
 * Invoked when a mouse button has been released on a component.
 *
 * @param e
 */
@Override
public void mouseReleased(MouseEvent e) {

}

/**
 * Invoked when the mouse enters a component.
 *
 * @param e
 */
@Override
public void mouseEntered(MouseEvent e) {

}

/**
 * Invoked when the mouse exits a component.
 *
 * @param e
 */
@Override
public void mouseExited(MouseEvent e) {

}
}

Comment: So? The super.paintComponent takes care of that for you. You are not painting correctly at all as per @camickr's answer. If you do it all within a single paintComponent method, you can easily turn on and off grid lines using a simple boolean field while leaving the squares in place.
Comment: minimize your GUI and then re-show it to see how "correctly" you're painting. Are your images durable when you do this?
Comment: (1-) `The whole point is to have the gridlines toggleable` - which is addressed in my answer. `Clearly I'm painting correctly since I see the squares being painted.` - clearly you are not for the reasons I gave you.
Comment: Myself, I wouldn't use overlying JPanels. Instead I'd try to keep things simpler, such as a single drawing JPanel or a grid of components.
Comment: The whole point is to have the gridlines toggleable, which Camickr and you both seem to ignore
Comment: You can't unpaint something (like the gridlines) without unpainting everything else as well
Comment: Clearly I'm painting correctly since I see the squares being painted. Thanks for your help though :)
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169995/discussion-between-dtroll-mc-and-dontknowmuchbut-getting-better).
Answer:
To do this, I have a custom JPanel, which makes another JPanel that holds just the gridlines. That way, I can show / hide the grid lines without ever removing what is on the canvas.

Well, that is the wrong approach. Your panel should have properties:

paint the gridlines or not
a 2D array to control which squares should be filled.

Your paint logic is wrong:
this.getGraphics().setColor(paintbrush.getColor());
this.getGraphics().fillRect(x * gridScale, y * gridScale, gridScale, gridScale);

You should never use getGraphics(...) on a component to do custom painting. The first time Swing determines the components needs to be repainted you will lose all the painting. For example if you resize the frame.
Instead. custom painting must be done in the paintComponent() of the component. Then you:

first paint the gridlines if required
iterate through the 2D array and paint any squares as required.

Read the section from the Swing tutorial on Custom Painting for more information and working examples.
Or instead of the 2D Array, use an ArrayList to contain objects to be painted. This object could simply be a Point object to control the x/y location of a square to be painted, or is could be an object that contains complete information about the object to be painted such as location/color/shape. Check out Custom Painting Approaches for a working example of this approach.

Superimposed JPanels not lining up


Como configurar um Anonymous Global Scopes no Laravel?

Question: Dentro da minha model estou utilizando um Anonymous Global Scopes para faltar algumas operações:
protected static function boot()
{
    parent::boot();

    static::addGlobalScope('owner', function (Builder $builder) {
        $builder->where('user_id', 1);
    });
}

Mas estou com uma dúvida, na closure acima o valor 'owner' foi colocado no lugar de um argumento chamado scope, no meu caso owner é:
public function owner()
{
    return $this->belongsTo(User::class);
}

Minha dúvida é, o que de fato deve está presente neste campo definido para scope?
Comment: Qual versão do Laravel e poderia colocar as duas classes?
Answer: O Global Scope é recurso contido no Eloquent para configurar filtros e restrições para o Model em todas as consultas SQL que esse modelo faz. Um exemplo é a exclusão lógica (SoftDelete) que pode ser configurada para qualquer Model do Eloquent como descrito na documentação.
Quando se configura um Anonymous Global Scopes como exemplo contido na documentação, pode ser configurado uma classe ou um closure, e se for configurado com um closure o primeiro paramento é um texto (que define um nome qualquer) e o segundo a função anônima, exemplo:
<?php namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Cliente extends Authenticatable
{
    protected $table = 'clientes';
    protected $dates = ['created_at','updated_at'];
    protected $fillable = ['nome', 'sobrenome', 'email',
                           'password', 'ativo'];
    protected $hidden = ['password'];
    public $timestamps = true;

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('ativo_filtro', function (Builder $builder) {
            $builder->where('ativo',1);
        });
    }
}

No código é demonstrado que na SQL tem um filtro (Where) que só pode trazer os ativos = 1 ou seja:
$clientes = Cliente::all();

a SQL gerado é
"select * from `clientes` where `ativo` = ?"

é um recurso que pode ser explorada onde não queira digitar a todo momento um determinado filtro, mas, também existe a forma de inutilizar que é:
removendo um:
$cliente = Cliente::withoutGlobalScope('ativo_filtro')->get();

removendo vários:
$cliente = Cliente::withoutGlobalScopes(['ativo_filtro', '', ...])->get();

e removendo todos:
$cliente = Cliente::withoutGlobalScopes()->get();


Help with differential equation $y=2y'x + \frac {1}{y'}$

Question: Please do it :
$y=2y'x + \frac {1}{y'}$
I know that this have no solution, but i have no idea to prove this.
Answer: So
y'=p
$p\;dx=2p\;dx +2x\;dp- \frac{dp}{p^2}$
or
$\frac{dx}{dp}= -\frac 2p x + \frac {1}{p^3}$
$x=\frac{1}{p^2}C+\frac{\ln p}{p^2}$
$y=\frac 2p C+\frac 1p [2\ln p +1]$
now you must check if there are peculiar solutions
$2p=p$
There is only one solution p=0, but $p\neq0$ because y' is in denominator, so $y=2y'x$ + $\frac {1}{y'}$ have not solution


numpy.asarray( Image.open ( ...) ) does not work

Question: I believe that numpy.asarray is the recommended way to create numpy arrays for images.
numpy.asarray(Image.open("cat.jpg"))

I have two python installations on my machine. One is locally installed on my home directory. and the one installed in /usr.
Anyways, the local installation does not work. The numpy creates an array of that JPEG object which is not want I need.
array(<JpegImagePlugin.JpegImageFile image mode=RGB size=1000x781 at 0x2395878>, dtype=object)

The other python installation output is a numpy array which is what I need.
array([[[ 89, 125,  51],
        [ 89, 125,  51],
        [ 90, 126,  52],
        ...,
        [ 53,  55,  50],
        [ 53,  55,  50],
        [ 53,  55,  50]],

       [[ 89, 125,  51],
        [ 89, 125,  51],
        [ 90, 126,  52],
        ...,
        [ 54,  56,  51],
        [ 53,  55,  50],
        [ 53,  55,  50]],

       ...,

       [[132, 134, 147],
        [133, 135, 148],
        [133, 135, 148],
        ...,
        [149, 165, 190],
        [149, 165, 190],
        [149, 165, 190]]], dtype=uint8)

Anyone knows a fix?
Comment: I forget when PIL added support for `np.asarray` but it was a few years ago. It's possible your local python has an old version of PIL installed. I remember needing to `np.fromstring(...)` before the new method was introduced.
Comment: Its not the python version you're looking for its the version of PIL and/or numpy.
Comment: Actually the local version is more recent 2.7.6 vs 2.6.
Comment: numpy and PIL have the same versions.
Answer: For reading and writing images with NumPy I use either
from scipy.misc import imread, imsave
image = imread("filename.jpg")

or
from skimage.io import imread, imsave

Rather than going through PIL/Pillow directly.

http://scikit-image.org/docs/dev/api/skimage.io.html
http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imread.html
Answer: I had exactly the same issue: numpy.asarray didn't work on my local machine (that is, produced an array containing a single image object), while it worked on my server, although Python and PIL versions were the same in both places and Numpy version was newer on the local machine (the one on which numpy.asarray didn't work).
After performing some investigation, I finally discovered that this issue was because of PIL compiled without support for certain format: in my case, I was getting IOError: Decoder 'zip' not available when trying to print the __array_interface__ field of an image object returned by PIL on the local machine.
To install PIL with support for most common image formats, I just used the package from my system repository instead of installing PIL with pip and everything worked fine:
sudo pip uninstall PIL
sudo apt-get install python-pil

However, I also managed to make everything work fine using pip. I did as follows (taken from IOError: decoder zip not available).
First of all, I installed necessary libraries in my system:
sudo apt-get install libjpeg62-dev zlib1g-dev libfreetype6-dev

For some reason, pip didn't see these libraries, and they had to be linked to /usr/lib on my 64-bit machine:
sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib

Since PIL installation still failed at that moment with an error concerning missing header file, I had to create another symlink (see Trying to install PIL "pip install PIL" and got this error.):
sudo ln -s /usr/include/freetype2 /usr/include/freetype

Then, I managed to reinstall PIL with pip:
pip install -U --force-reinstall PIL

The output from that command confirms that a support for JPEG and PNG formats is now included:
*** TKINTER support not available
--- JPEG support available
--- ZLIB (PNG/ZIP) support available
--- FREETYPE2 support available
*** LITTLECMS support not available