Any idea why i'm always getting "Sat 17th" date (Calendar) - java?

Question:  public static void main(String[] args) {
   JsonWeatherTime time = new JsonWeatherTime();
   String date = time.formatDate(Long.valueOf(1454691600));  //Todays date
    System.out.println(date);

  }

 private String formatDate(long milliseconds){
    StringBuffer dateBuffer = new StringBuffer();
    Calendar     calendar = Calendar.getInstance();
    calendar.setTimeInMillis(milliseconds);
    switch(calendar.get(Calendar.DAY_OF_WEEK)){
    case Calendar.MONDAY: dateBuffer.append("MON, ");
    break;
    case Calendar.TUESDAY:dateBuffer.append("TUE, ");
    break;
    case Calendar.WEDNESDAY:dateBuffer.append("WED," );
    break;
    case Calendar.THURSDAY:dateBuffer.append("THUR, ");
    break;
    case Calendar.FRIDAY:dateBuffer.append("FRI, ");
    break;
    case Calendar.SATURDAY:dateBuffer.append("SAT, ");
    break;
    case Calendar.SUNDAY:dateBuffer.append("SUN, ");
    break;
    default:dateBuffer.append("N/A");
  }

 String day_of_week = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
    if(day_of_week.equals("1") | day_of_week.equals("21") | day_of_week.equals("31") ) day_of_week += "st";
    else if(day_of_week.equals("2") | day_of_week.equals("22") ) day_of_week += "nd";
    else if(day_of_week.equals("3") | day_of_week.equals("23")) day_of_week += "rd";
    else day_of_week += "th";
 //Log.d("JSONPARSE", "THE VALUE OF THE DATE ISSSSSS" + day_of_week);
  dateBuffer.append(day_of_week);
  return dateBuffer.toString();
 }

I'm parsing json weather data from the OpenWeatherMap api, and no matter the value i parse for the date (given in milliseconds through json), the calendar returns a date of Sat 17th. I'm not entirely familiar with working with dates, but the json returns a millsecond string in UNIX time, and if i pass in todays date (1454691600), the string should read (Fri, 6th), though it returns (Sat, 17th). Any idea what i'm doing wrong here?
Comment: So, your value is `1454691600` and you use `calendar.setTimeInMillis(milliseconds);` ... do you really think that "1454691600" are the _milliseconds_ counted since 01/01/1970? What if they are the _seconds_? Would your current problem then makes sense?
Comment: If that time were in milliseconds it would represent roughly 17 days, rather than 46 years
Comment: @Boris, thanks for the constructive comment...
Comment: @BoristheSpider Neither `SimpleDateFormat` nor date/time API will output date using `st`, `nd`, `rd`, and `th` suffixes, and that seems to be the desired output.
Answer: The value 1454691600 is in seconds, not milliseconds.
Date date = new Date(1454691600 * 1000L);
SimpleDateFormat dateFmt = new SimpleDateFormat("EEE, d");
System.out.println(dateFmt.format(date)); // prints: Fri, 5

System.out.println(date); // prints: Fri Feb 05 12:00:00 EST 2016

Comment: Wow, okay that was about "1000" times easier. Pun intended. Thanks man!
Answer: The JSON returns value in a seconds, not in a milliseconds.
public static void main(String[] args) {

    String date = formatDate(Long.valueOf(TimeUnit.SECONDS.toMillis(
            1454691600)));  //Todays date
    System.out.println(date); // FRI, 5th

}

This code works fine and prints expected date: FRI, 5th
Answer: The other Answers are correct, your number seems to be whole seconds rather than a count of milliseconds-from-epoch.
java.time
FYI, you are using old date-time classes bundled with the earliest versions of Java. They have proven to be troublesome and poorly designed. Java 8 and later supplants those old classes with the java.time framework.
Parse Number
An Instant is a moment on the timeline in UTC with a resolution of nanoseconds. In code below, notice the L to mark a numeric integer as a long (64-bit integer).
Instant instant = Instant.ofEpochSecond( 1454691600L );

Time Zone
Time zone is crucial in determining a date. If you do not specify the time zone, both the old classes (as seen in your Question) and java.time classes silently apply the JVM's current default time zone. Better to be explicit about the time zone you desire/expect.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Localized Name Of Day
To get the localized name of the day, use the DayOfWeek enum. We ask for Québec French here to make the point. You could specify Locale.ENGLISH or Locale.US, and so on. As with time zone, I strongly recommend always specifying your desired/expected Locale rather than rely implicitly on the JVM's current default Locale which can change at any moment even during runtime.
DayOfWeek dayOfWeek = DayOfWeek.from( zdt );
String nameOfDay = dayOfWeek.getDisplayName( TextStyle.SHORT , Locale.CANADA_FRENCH ); // Or Locale.ENGLISH or Locale.US, and so on.

Dump to console.
System.out.println ( "instant: " + instant + " | zoneId:  " + zoneId + " | zdt: " + zdt + " | dayOfWeek: " + dayOfWeek + " | nameOfDay: " + nameOfDay );

instant: 2016-02-05T17:00:00Z | zoneId:  America/Montreal | zdt: 2016-02-05T12:00-05:00[America/Montreal] | dayOfWeek: FRIDAY | nameOfDay: ven.

Ordinal Indicator
The java.time framework does not help you get the ordinal indicator such as "st" or "th" as far as I know. You will have to do the same kind of code as seen in your Question.


C++ boost async_accept exception "already open"

Question: I'm having a little problem that I cannot see a lot of people have come into with boost async_accept.
This is how I'm handling the async_accept and how I call it.
void Server::accept()
{
    try {
        Connection* connection = new Connection(io_service);
        connections.push_back(connection);
        acceptor->async_accept(connection->getSocket(), std::bind(&Server::onAccept, this, std::placeholders::_1, connection));
    }
    catch (const boost::system::system_error& e) {
        std::cout << "> [Error - Server::start]: " << e.what() << std::endl;
    }
}

void Server::onAccept(const boost::system::error_code& e, Connection* connection)
{
    if (e) {
        std::cout << "> [Error - Server::onAccept]: " << e.message() << std::endl;
        connection->disconnect();
        return;
    }

    connection->read();
    accept();
}

The method connection->getSocket() returns a reference to the boost::asio::ip::tcp::socket socket variable from the connection class.
The connection is accepted, but when onAccept is called, there is a "Already open" error which I cannot seem to find the solution to.
Answer: The problem is not in the code shown.
Google shows many people having the same issue, and one of the top 3 hits shows it being caused by the fact that the client connection class is being used, while this is a server.
Client connections initiate the connection, so if you copy/pasted that code, you would have an open connection, which is of course "Already open".
Check that you didn't open the socket in the Connection class. Alternatively, check that you're instantiating the correct type in new Connection (name and namespace).


For any three vectors $x,y,z\in\mathbb{R}^d$, we have $ \|y-z\|\cdot\|x\|\leq\|x-y\|\cdot\|z\|+\|z-x\|\cdot\|y\|$

Question: Does anyone know a proof of the following problem?
Problem: Show that for any three vectors ${\bf x}, {\bf y}, {\bf z}\in \mathbb{R}^d$ the following holds,
$$ \|{\bf y} - {\bf z}\|\cdot \|{\bf x}\| \leq \|{\bf x} - {\bf y}\|\cdot \|{\bf z}\| + \|{\bf z} - {\bf x}\|\cdot\|{\bf y}\|.$$
All of the norms are Euclidean 2-norm.
Answer: If any of $x,y,$ or $z$ is zero the result is trivial. So WOLOG assume that $x,y,$ and $z$ are all non-zero and let $a = x/\Vert x\Vert^2$, $b=y/\Vert y\Vert^2$, and $c = z/\Vert z\Vert^2$. We have $\left\Vert x-y\right\Vert=\frac{\left\Vert a-b\right\Vert}{\Vert a\Vert\Vert b\Vert}$, $\left\Vert z-x\right\Vert=\frac{\left\Vert c-a\right\Vert}{\Vert c\Vert\Vert a\Vert}$, and $\left\Vert y-z\right\Vert=\frac{\left\Vert b-c\right\Vert}{\Vert b\Vert\Vert c\Vert}$. Therefore, $$\left\Vert y-z\right\Vert\Vert x\Vert=\frac{\left\Vert b-c\right\Vert}{\Vert a\Vert\Vert b\Vert\Vert c\Vert}\\\leq\frac{\left\Vert a-b\right\Vert}{\Vert a\Vert\Vert b\Vert\Vert c\Vert}+\frac{\left\Vert c-a\right\Vert}{\Vert a\Vert\Vert b\Vert\Vert c\Vert}\\=\left\Vert x-y\right\Vert\Vert z\Vert + \left\Vert z-x\right\Vert\Vert y\Vert,$$ which completes the proof.
Comment: @user1551 The inequality is essentially [Ptolemy's inequality](http://en.wikipedia.org/wiki/Ptolemy%27s_theorem#Ptolemy.27s_inequality) with some little differences. One of the standard proofs for the Ptolemy's inequality is to use [inversion](http://en.wikipedia.org/wiki/Circle_inversion). What I wrote is basically expressing the given inequality in terms of the inverses with respect to the unit sphere.
Comment: I think that $\left\Vert x-y\right\Vert=\frac{\left\Vert a-b\right\Vert}{\Vert a\Vert\Vert b\Vert}$ is wrong.
Comment: @ChristianBlatter We have $x=a/\Vert a\Vert^2$ and $y=b/\Vert b\Vert^2$. Therefore, $\left\Vert x-y\right\Vert^2=\left\Vert a/\Vert a\Vert^2 - b/\Vert b\Vert^2\right\Vert^2=\frac{1}{\Vert a\Vert^2}-2\frac{a^T b}{\Vert a\Vert^2\Vert b\Vert^2}+\frac{1}{\Vert b\Vert^2}=\frac{\left\Vert a-b\right\Vert^2}{\Vert a\Vert^2\Vert b\Vert^2}$.
Comment: You are right. I had missed the ${}^2$ in the denominator. Sorry.
Comment: Excellent proof! This is my favourite proof of the day. +1. How did you come up with the $a=x/\|x\|^2$ trick?
Comment: @S.B. Thank you for the informative reply :-D


Idempotents in coordinate ring

Question: Let $k$ be an infinite field. Let $V$ be an algebraic set of $k^n$.
Let's suppose that $f(x)+I(V)\in k[x_1,\cdots,x_n]/I(V)$ $(x=(x_1,\cdots,x_n))$ is such that $f(x)^2+I(V)=f(x)+I(V)$. Then does $f(x)+I(V)$ have to be $0+I(V)$ or $1+I(V)$? And what if $k$ is algebraically closed?
Answer: No. Consider the simple case of $V\subset \mathbb{A}^1_k$ being two points, say given by the ideal $I(V)=(x^2-x)$. Then $k[x]/I(V)$ admits non-trivial idempotents, $x+I(V)$ and $1-x+I(V)$. Algebraically closed field does not resolve anything here...
In general a ring $R$ admits non-trivial idempotents if an only if $R\simeq R_1\times R_2$ is a product of two rings. In our example $k[x]/(x^2-x)\simeq k\times k$. Observe that in this case our algebraic set $V$ is disconnected. This is a general feature, whenever the coordinate ring of an algebraic set $V$ is disconnected, then the coordinate ring of $V$ admits non-trivial idempotents. Also conversely if an algebraic set is connected its coordinate ring does not admit non-trivial idempotents.
In case you are dealing with an irreducible algebraic set (affine variety), then this does not happen because any irreducible topological space is connected. or equivalently since $I(V)$ is prime, the coordinate ring $k[V]$ is an integral domain, hence cannot be isomorphic to a product ring $R_1\times R_2$ (product rings are never integral domains).

Idempotents in coordinate ring


PrimeFaces Mobile não funciona p:poll

Question: Estou implementando p:poll em uma página que usuário pode ver sua posição atualizada em uma fila de espera. Tentei executar em uma página mas não funcionou, a posição atualizada em fila de espera ficou em branco no campo usando API da Primefaces Mobile, veja a página que criei:

    <f:view renderKitId="PRIMEFACES_MOBILE">
        <h:head>
            <f:facet name="first">
                <meta content='text/html; charset=UTF-8' http-equiv="Content-Type"/>
                <title>Cliente</title>
                <h:outputScript library="primefaces/poll" name="poll.js"/>
            </f:facet>
        </h:head>
        <h:body>
            <pm:page>
                <pm:content>
                    <h:form>
                        <pm:field>

                        </pm:field>
                        <pm:field>

                        </pm:field>
                        <pm:field>

                        </pm:field>
                        <pm:field>

                        </pm:field>

                    </h:form>
                </pm:content>
            </pm:page>
        </h:body>
    </f:view>

ManagerBean:
@ManagedBean
@ViewScoped
public class FilaController {

    private Cliente cliente;
    private HttpSession session;
    private FacesContext context;
    private GerenciamentoDeFilaFacade fila;
    private String posicao;

    public FilaController() {
        context = FacesContext.getCurrentInstance();
        session = (HttpSession) context.getExternalContext().getSession(false);
        cliente = (Cliente) session.getAttribute(TipoUsuario.cliente.toString());

        if (cliente != null) {
            fila = new GerenciamentoDeFilaFacade();
        } else {
            System.out.println("Cliente está null");
        }
    }

    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

    public String getQuantidadeFila() {
        return fila.quantidadeTotal() + " Filas";
    }

    public String getPosicaoFila() {
        return fila.posicao(cliente) + "º posição";
    }

    public String getPosicao() {
        return posicao;
    }

    public void setPosicao(String posicao) {
        this.posicao = posicao;
    }

    public String desista() {
        if (fila.removerCliente(cliente)) {
            return "index.xhtml";
        } else {
            return "cliente.xhtml";
        }
    }

    public void atualizaPosicao() {
        this.posicao = fila.posicao(cliente) + "º posição";
    }
}

Classe GerenciamentoDeFilaFacade
public class GerenciamentoDeFilaFacade {

private GerenciamentoDeFila fila;
private Prioridade p = new Prioridade();

public GerenciamentoDeFilaFacade() {
    fila = GerenciamentoDeFila.getInstance();
}

public void inserir(Cliente cliente) {
    if (p.verifica(cliente)) {
        fila.inserirPioridade(cliente);
    } else {
        fila.inserir(cliente);
    }
}

public Cliente getCliente() {
    if (fila.verificaFilaPrioridadeDisponivel()) {
        return fila.getPrimeiroClientePioridade();
    }
    return fila.getPrimeiroCliente();
}

public Cliente chamarCliente() {
    if (fila.verificaFilaPrioridadeDisponivel()) {
        return fila.getChamarClientePrioridade();
    }
    return fila.getChamarCliente();
}

public int quantidadeTotal() {
    return fila.quantidade();
}

public int posicao(Cliente cliente) {
    if (p.verifica(cliente)) {
        return fila.posicaoPrioridade(cliente);
    }
    return fila.posicao(cliente);
}

public boolean removerCliente(Cliente cliente) {
    return fila.remove(cliente);
}

public Iterator<Cliente> Clientes() {
    return fila.getListaClientes();
}

}
Classe GerenciamentoDeFila
public class GerenciamentoDeFila {

private static GerenciamentoDeFila instance = null;
private static LinkedList<Cliente> fila = new LinkedList<Cliente>();
private static LinkedList<Cliente> filaPrioridade = new LinkedList<Cliente>();

public static GerenciamentoDeFila getInstance() {
    if (instance == null) {
        instance = new GerenciamentoDeFila();
    }
    return instance;
}

public void inserir(Cliente cliente) {
    fila.addLast(cliente);
}

public void inserirPioridade(Cliente cliente) {
    filaPrioridade.addLast(cliente);
}

public Cliente getPrimeiroCliente() {
    return fila.peekFirst();
}

public Cliente getPrimeiroClientePioridade() {
    return filaPrioridade.peekFirst();
}

public Cliente getChamarCliente() {
    return fila.pollFirst();
}

public Cliente getChamarClientePrioridade() {
    return filaPrioridade.pollFirst();
}

public boolean remove(Cliente cliente) {
    if (filaPrioridade.contains(cliente)) {
        return filaPrioridade.remove(cliente);
    }
    return fila.remove(cliente);
}

public int posicaoPrioridade(Cliente cliente) {
    return filaPrioridade.indexOf(cliente) + 1;
}

public int posicao(Cliente cliente) {
    int qtd = filaPrioridade.size();
    return ((qtd + fila.indexOf(cliente)) + 1);
}

public int quantidade() {
    System.out.println("Quantidade de fila - Cliente: " + fila.size() + " - Prioridade: " + filaPrioridade.size());
    return fila.size() + filaPrioridade.size();
}

public boolean verificaFilaPrioridadeDisponivel() {
    return !filaPrioridade.isEmpty();
}

public Iterator<Cliente> getListaClientes() {
    LinkedList<Cliente> lista = new LinkedList<Cliente>();
    lista.addAll(filaPrioridade);
    lista.addAll(fila);
    return lista.iterator();
}

}
Gostaria que vocês tragam alguma sugestão para resolver esse problema.
Obrigado!
Comment: Tem como postar o código desta classe:  GerenciamentoDeFilaFacade ? Qual é a versão do Primefaces?
Comment: Já coloquei mais dois classes, veja em cima.
A versão do PrimeFace é 5.0 e PrimeFace Mobile é 0.9.4
Comment: Com o PrimeFace 5 não precisa do Mobile 0.9.4, acho que a partir da versão 4 do Prime os projetos foram unidos. Só mais umas informações: qual é o servidor de aplicação e a versão dele? está usando Maven?
Comment: Estou usando o servidor é Tomcat 7 e usando o Maven.
Answer: No meu caso adicionando
<h:outputScript library="primefaces" name="primefaces.js" />

dentro de h:body resolveu o problema no PrimeFaces 5.1.20.

PrimeFaces Mobile não funciona p:poll


Tipo do campo CPF ou CNPJ no banco de dados VARCHAR ou INT?

Question: Qual tipo do campo CPF ou CNPJ no banco de dados VARCHAR ou INT?
Já vi alguns posts sugerindo usar INT para otimizar a performance no caso de JOINe filtros.
Se possuir 0 a esquerda é só completar de acordo com o tamanho do campo armazenado (CPF Ou CNPJ) para efetuar a validação.
Então qual seria a melhor abordagem?
Comment: Eu não vi nenhum valor na pergunta a princípio, mas o fato de haver uma consideração de que a resposta seja questão de opinião me fez perceber que a pergunta é útil sim (embora a resposta seja óbvia, parece que não é tão óbvia para todos).
Comment: Eu sempre utilizei `VARCHAR`, **mas apesar de não acreditar em nada que esta na internet**, já alguns comentários defendendo usar `INT`, apesar de não apresentar nenhuma fundamentação. E separando em: corpo ,filial, e controle para usar assim: `intCPFCNPJ = 000000000 and sintCPFCNPJFil = 0 and tintCPFCNPJCtrl = 90`. Achei um **gambiarra** terrível, mas achei interessante ver outras opiniões, apesar da resposta parecer obvia.
Comment: Eu acho que a pergunta pode ser respondida objetivamente, tanto que fiz. O fato de ter uma outra resposta que só emite opinião não é culpa da pergunta.
Comment: Melhor usar VARCHAR.
Comment: Eu me pergunto como a Receita Federal armazena , ela é a 'dona do circo' digamos assim. Se algum colega que trabalhe puder ingirmar ...  Acho a melhor solução caractere.
Answer: Otimização só deve ser feita se realmente for muito necessário. Eu duvido que esta otimização valha a pena em qualquer cenário.
A regra básica para seleção do tipo quando eles podem ser confundidos é para que vai usá-los. Números representam quantidades. CPF ou CNPJ são quantidades? Não, são identificadores que podem até mesmo mudar, que podem um dia ter letras (aconteceu com RG). A semântica correta para este dado é o varchar afinal ele é descritivo.

A questão do zero à esquerda por si só já é bom bom motivo para usar varchar. Pra que ficar fazendo gambiarras para resolver um problema causado pelo tipo errado. Sempre digo isso pra tudo em computação e até na vida, a pessoa causa um problema e depois causa novos tentando resolver algo que ela deveria ter feito certo do início (isso acontece mais do que quase todo mundo percebe, especialmente com experientes que não consegue mais enxergar seus erros tamanho a arrogância que desenvolve, mesmo discursando o contrário).
Você sempre deve optar por varchar em qualquer dado até que encontre um motivo para escolher outro tipo. Um ID geral, por exemplo, tem um bom motivo para ser um int, ele precisa ser incrementado, você faz contas com ele. O mesmo vale para salário, preço, quantidade. Mas não vale para CEP, fone, até mesmo número de um imóvel no endereço quando este campo é separado. Um vencimento tem motivo para ser de outro tipo, você precisa classificar a informação por ordem de data, e como texto isto não funcionaria corretamente. São só alguns exemplos.
Alguns até dirão que é necessário usar o varchar porque ele tem pontuação além de números. Mas este não é um bom argumento já que a pontuação nem deveria ser gravada, pelo menos não na maioria das situações. Isto deveria ser resolvido na apresentação apenas, a pontuação não faz parte do dado (geralmente).
Em alguns casos um tipo numérico nem pode ser usado já que a quantidade de dígitos usado para identificar algo é maior do que o tipo numérico comporta.
Alguns dirão que nem varchar deve ser usado. Como o tamanho é fixo, um simples char resolve o problema. Mas há controvérsias quanto a isso. Dependendo do sistema de DB um tipo realmente pode ser mais vantajoso que outro mas não o suficiente para justificar, na maioria dos casos, uma escolha será feita por causa da performance. A semântica deve ser a opção primária.
Infelizmente há muita informação errada na internet sobre o assunto (ou qualquer assunto :) ).

Coloquei no GitHub para referência futura.
Comment: @MarcioMazzucato depende muito do caso. Hoje eu faço sempre tabelas diferentes para pessoa física e jurídica, nem precisa dizer que as coluna são separadas. Eu modelo cadastros como eles realmente são, não crio uma divisão artificial e um união mais artificial ainda. Quando gosta de algo pode votar no post. http://pt.stackoverflow.com/q/54177/101 e http://pt.stackoverflow.com/q/14839/101
Comment: @danilo em 36 anos de dedicação e estudo estruturado. Obrigado.
Comment: @Maniero, rapaz, aonde tu aprendeu tudo isso? que resposta formidável!!!
Comment: Sempre defendi o uso de varchar. Semana passada tive que defender novamente. Hoje por coincidência me passaram um problema numa tela. Identifiquei que ocorre apenas com usuários com CPF iniciado por zero. Logicamente tinha cpf como BIGINT no meio.
Comment: Ótima resposta! Estou apenas com uma dúvida final, você aconselha a criação de uma coluna cpf e outra cnpj ou criar apenas uma coluna para armazenar tanto um quanto o outro?
Comment: @Maniero Ótima resposta, tirou toda e qualquer dúvida que esse assunto me gerava
Comment: Semanticamente `varchar` significa "campo de caracteres de tamanho variável". Como o CPF não tem tamanho variável, `char` é mais adequado do ponto de vista semântico. Além da já mencionada vantagem em relação ao desempenho.
Answer: Sempre defendi usar VARCHAR, pois eles são uma string que coincidentemente ocorre de serem uma sequência de dígitos. Diferentemente de um INT aonde a finalidade de ser um número é permitir que você possa efetuar operações matemáticas, algo que não tem sentido nenhum em um CPF ou CNPJ.
O mesmo caso ocorre com o RG, aonde cada estado tem um formato diferente, e usar como INT iria remover os zeros a esquerda, além de trazer problemas referentes ao dígito verificador.
Comment: Marcio Mazzucato, eu tenho usado a mesma coluna para armazenar CPF/CNPJ, usando entretanto um campo auxiliar "Tipo" (ex: CPF=1, CPNJ=2) para indicar o que tem na coluna principal (para facilitar algumas queries). Como eu salvo os dados com os zeros a esquerda (CPF tamanho 11, CNPJ tamanho 14) não preciso usar constraint com os 2 campos para garantir a unicidade.
Comment: Você aconselha a criação de uma coluna cpf e outra cnpj ou criar apenas uma coluna para armazenar tanto um quanto o outro?
Answer: Use VARCHAR você terá problemas caso o usuário utilize . (ponto) ou/e - para separar os dígitos. Caso você faça alguma verificação e retire esses ou outros caracteres, então pode-se usar INT. Mas recomendo usar VARCHAR. Use INT para registros que você sabe que só terá dígitos/números.
Comment: só uma ponderação... você só pode saber que o campo sempre terá dígitos/números se ele estiver no teu domínio, e se a natureza dele realmente é intríssica a números, não pode ser algo controlado por agente externo como é o caso da Receita Federal que controla a definição de cpf/cnpj
Answer: Conforme a resposta de Victor Stafusa, te ajudará a tomar a melhor decisão observar que tipos de operações serão realizadas no campo em questão. No caso do CPF e CNPJ, estes não sofrem operações aritméticas (normalmente) e são tratados como tipos de dado alfanumérico (char, varchar) desde de seus algoritmos de validação, que por definição os consideram cadeias de caracteres de tamanhos fixos. Um outro ponto a favor de serem utilizados tipos alfanuméricos como o varchar, é que fica facilitado a utilização de pesquisas usando o operador LIKE, ao contrário de campos de tipos numéricos. Campos de dados de "códigos identificadores" (como CPF e CNPJ) alfanuméricos também podem ser considerados mais a prova de futuro, pois há alguma possibilidade (talvez remota, mas há) de passar-se a utilizar letras nestes, já que cada letra aumenta em muito o número de combinações diferentes e, ao mesmo tempo, requer menos caracteres a memorizar.
Mas como tudo no mundo da computação, tudo tem seu preço e dependendo dos seus requisitos de performance e tamanho de banco de dados, pode ser muito mais performático armazenar CPFs e CNPJs como tipos numéricos, uma vez que ocupam consideravelmente menos bytes (especialmente em relação ao varchar com unicode), resultando em índices de tabela fisicamente menores, além de algoritmos de busca mais rápidos. De fato, já vi grande melhora de performance em bancos de dados Oracle ao terem CPFs armazenados como number.
Answer: Se observarmos o tamanho do INT(UNSIGNED) que vai de 0 a 4294967295, temos 10 posições suportadas.
Como o CPF tem 11 números sem formatação, teríamos 1 número a mais nessa cadeia, forçando o DB, no momento da inserção, a fazer um CPF com valor digamos inicial de "500.000.000-60" ou se for "4294967296" virar 4294967295.
A regra vale para o CNPJ também, no caso do CNPJ com 14 números sem formatação.  O ideal seria usar um BIGINT de 0 a 18446744073709551615. Para questões de velocidade em consultas, pode ser adicionado um índice nesse campo e outras regras que vai de cada DBA.
No caso dos 0 a esquerda no MySql por exemplo podemos definir o campo como ZEROFILL.
Sobre formatação não é necessário permitir que a aplicação chegue até o DB com um CPF ou CNPJ formatado com ".", "-" ou "/", essa regra cabe ser feita em uma view.
Comment: Possível de se usar inteiro até é, mas acho complicado dizer que "é o ideal". E outra, se é para armazenar no "improviso", poderia usar um INT sem problemas, afinal um CPF válido só tem 9 digitos significativos. Os dois de conferência são calculados (a não ser que você queira armazenar mesmo se os dígitos de conferência não baterem). O fato importante é ter em mente a natureza do dado, o que já está bem elaborado nos outros posts.
Answer: Cara te aconselho a usar uma string mesmo, pois vc pode ter problemas com 0 a esquerda pq eles podem ser desconsiderados.


How to import/add translated strings having inline styles?

Question: I've imported a .po file having Spanish translations. The import was successful but some translation strings were skipped because they contain disallowed HTML.
From UI, I found that some translations were not translated. So I tried them adding those via the translate admin interface (Administration » Configuration » Regional and language » Translate interface)
I could see the original text having inline style like following.

But when I tried to add a Spanish (Latin American) Translation and hit 'Save translations' getting the following error.

The submitted string contains disallowed HTML:Hola

I've enabled Translatable all HTML text formats under multilingual settings  (Administration » Configuration » Regional and language » Multilingual settings)

It's working when I remove inline style add translation   like the following. So I guess it's not supporting inline styles and classes.
 Hola

What could be the problem? I found a function in function locale_string_is_safe($string) under includes/locale.inc file. Do I need to do any tweaks with that?
Any suggestions would be much appreciated.
Answer: Here's an alternative without hacking the core. You simply could unset the validation for the translation interface form:
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  // That's the form ID of the translation interface.
  if ($form_id == 'i18n_string_locale_translate_edit_form') {

    // Let's check at least for a user's role first.
    global $user;
    if (in_array('administrator', $user->roles)) {

      // Simply unset the validation. Done.
      unset($form['#validate']);
    }
  }
}

Answer: Yes your guess is correct,locale_string_is_safe  "Check that a string is safe to be added or imported as a translation." if you want to ignore your job you should patch it for a while ,
change it to
function locale_string_is_safe($string) {
  return TRUE:
}

after your job  revert it.
Comment: Awesome! that works!! thanks zhilevan  you saved my day:)
Comment: Is there not any other solution since this is hacking core?thanks
Comment: @KrishnaMohan your welcome my friend :) . we are here to help each others ;)
Comment: @sokratis I dont spend more time on it maybe there is but I dont know it
Comment: @sokratis – Added no-hacking answer.


How to keep the single resource representation approach using OpenAPI spec

Question: Reading this post (see: 3 How to use a single definition when...) about describing a REST API using OpenAPI (Swagger) specification you can note how to keep a single resource representation for adding/updating and getting resource using readOnly property instead of having one representation for getting (GET a collection item) and other one for adding (POST to a collection). For example, in the following User single representation, the id is a read-only property which mean that it won't be sent in the representation when a user is created, it will be there when a user is retrieved.
"User":
{
    "type": "object",
    "properties": {
        "id": {
            "type": "integer",
            "format": "int64",
            "readOnly": true
        },
        "company_data": {
            "type": "object",
            "properties": {
                .
                .
                .
            },
            "readOnly": false
        }
    }
}

It is really clean and nice to keep the list of resource representation as short as possible so I want to keep the single resource representation approach but the problem I am facing to do that is: how to manage required when a property is mandatory for input only? Suppose I need to set company_data as required when the user is created (POST /users/) but non-required when an user is retrieved (GET /users/{user_id}). There are any way in OpenAPI specification to satisfy this need without lost the single resource representation?
Comment: My answer below. You might also want to look at RAPID-ML, which we designed to make canonical data models highly adaptable, thus easier to reuse and standardize across APIs: http://rapid-api.org/rapid-ml
Answer: From the Swagger-OpenAPI 2.0 spec, readonly is defined as follows:

Declares the property as "read only". This means that it MAY be sent
  as part of a response but MUST NOT be sent as part of the request.
  Properties marked as readOnly being true SHOULD NOT be in the required
  list of the defined schema. Default value is false.

Since the specification says that a read-only property should not be required, there are no defined semantics for what readonly + required should mean.
(It might have been reasonable to say that readonly + required means it's required in the response, but still excluded from the request. In fact there is an open issue to make this change, and it looks like it's under consideration for OpenAPI 3.0.)
Unfortunately there is no way for a single schema to make properties required in the request, but optional (or disallowed) in the response.
(Again, there's an open issue proposing a "write-only" modifier, possibly under consideration for the next release.)
For now, you would need to create different schemas for these different cases. As described here, you might be able to make these schemas a bit more DRY using allOf composition.


WebRTC for Android : VideoRendererGUI take a screenshot in the video call

Question: The demand is that saving a video frame in the video call. I have made a demo that take a screenshot through the GLSurfaceView's method "onDrawFrame". But when I use the webrtc, it have its own renderer "VideoRendererGUI" .And then when I want to override it, I find it can't be overrided. the main part code :
   vsv = (GLSurfaceView) findViewById(R.id.glviewchild_call);
    vsv.setPreserveEGLContextOnPause(true);
    vsv.setKeepScreenOn(true);

    VideoRendererGui.setView(vsv, new Runnable() {
        @Override
        public void run() {
            init();
        }
    });

And If you have another way to take a screenshot, you can also share with me.
Thanks a lot!
Answer: If you use a SurfaceViewRenderer to display the stream, you can use the solution in this answer to capture a frame on the call.
Basically, using surfaceViewRenderer.AddFrameListener with a class that implements EGLRenderer.FrameListener
Answer: I will assume that the SurfaceViewRenderer of the peer you want to take a screenshot of is called remotePeerSurfaceViewRenderer, also I will asume that the button that you will use to take a screenshot is called btnScreenshot
So all what you need to do is as "Webo80" said in the answer above use the FrameListener, the issue is the FrameListener implementation of the webrtc takes only the first frame available once the Listener is attached to the SurfaceViewRenderer, so my approach to do that is by attaching the webrtc implementation of the FrameListsner at the second I need to take a screenshot and remove it once it is taken:
btnScreenshot.setOnClickListener((view)-> {
    remotePeerSurfaceViewRenderer.addFrameListsner(new EglRenderer.FrameListener() {
            @Override
            public void onFrame(Bitmap bitmap) {
                runOnUiThread(() -> {
                    /*
                    do what ever you want with the bitmap for example
                    imgView.setImageBitmap(bitmap);
                    */
                    localVideoView.removeFrameListener(this);
                });
            }
        }, 1);
})

Important note:
1. Please don't forget to runOnUiThread as Iam doing
2. Please don't forget to remove the listener inside the button onClick() method

I have tried this solution and it is working more than fine, if you want to make your custom solution you have to completely implement the interface "EglRenderer.FrameListener"
Comment: This seems to work. Thanks. But I have a different requirement. I assumed that if I don't use removeFrameListener() the onFrame() would get called repeatedly. But that's not true I suppose. I want it to be called repeatedly so that I can analyze each frame. Any ideas?
Answer: I am sorry to say due to unavailability of canvas and other facilities in Android It's not possible to capture screenshot programatically using WebRTC. One can dodge this situation by animating the app's UI and capturing the screenshot manually , store it at configured location and exchange it with other party.
Comment: I hava found another solution! Firstly through webrtc ,I can get the I420frame in the method 'RenderFrame'. Then I convert the I420frame to YuvImage. Finally,I use the YuvImage's method 'compressToJpeg' to convert it to jpeg image.
Comment: Thanks Gaurav! Can I use the ffmpeg to solve this? Because now I have used the app's UI "GLSurfaceView" ,but it doesn't work.


Combinatorics: Lock puzzle , minimum combinations

Question: A safe has three locks of which every lock has 8 possibilities 1, 2 ...8. Safe gets opened if any 2 of 3 locks gets opened. So, a possible way to open safe is try 2 locks, for each possible pair of combinations giving us 64 combinations. Can it be done in lesser number of combinations? If so, what is the minimum number of combinations required?
Comment: I think you can't beat it, but I haven't fleshed out a format proof yet. Will post it as an answer if I get to it before someone else does.
Comment: With three locks that each have _two_ options, it's easy to directly show you cannot do better than that strategy just by directly counting every track.
Comment: Also, *formal, not format, haha
Answer: We can do it in $32$ tries as follows:
\begin{align}
\begin{matrix}
111 & 222 & 333 & 444 \\
123 & 142 & 134 & 243 \\
231 & 214 & 341 & 432 \\
312 & 421 & 413 & 324
\end{matrix}
&&
\begin{matrix}
555 & 666 & 777 & 888 \\
567 & 586 & 578 & 687 \\
675 & 658 & 785 & 876 \\
756 & 865 & 857 & 768
\end{matrix}
\end{align}
The idea is that the first block of $16$ rules out all combinations with at least two numbers from $\{1, 2, 3, 4\}$ and the second block of $16$ rules out all combinations with at least two numbers from $\{5, 6, 7, 8\}$. By Pigeonhole Principle, any combination must have two numbers in one of these two sets, so we have covered all possible combinations.

Proof of Optimality
Assume on the contrary that $31$ tries are sufficient.
Lemma: For any position and any number $n \in \{1, 2, \ldots , 8\}$, we must have tried $\geq 3$ combinations with $n$ in that position.
Proof: By symmetry, it suffices to show that we must have tried $\geq 3$ combinations starting with $1$.
Assume on the contrary that at most two of the combinations tried start with $1$, then each rules out $15$ combinations starting with $1$, so we still have $64-2(15)=34$ possible combinations starting with $1$. All other combinations tried do not start with $1$, hence only rule out one combination starting with $1$, so we need to try at least $34$ more combinations, a contradiction.
Therefore we must have tried $ \geq3$ combinations starting with $1$.

If for each $n=\{1, 2, \ldots , 8\}$, we have tried $\geq 4$ combinations starting with $n$, then we require at least $32$ tries, a contradiction. Therefore for some $n$, we have tried at most $3$ combinations starting with $n$, hence by the lemma we have tried exactly $3$ combinations starting with $n$.
Now WLOG assume that $n=1$, by symmetry. So we have something like
$$\begin{matrix} 1ab \\ 1cd \\ 1ef \end{matrix}$$
where $a, b, c, d, e, f$ need not be distinct.
Note that all combinations of the form $1xy$ where $x \not =a, c, e$ and $y \not =b, d, f$ have not been ruled out.
If $a, c, e$ are not pairwise distinct, then there are at least $6$ choices for $x$, and there are at least $5$ choices for $y$, so we have $30$ combinations starting with $1$ which have not been ruled out. All other combinations we try do not start with $1$, hence rule out at most one of these $30$ combinations. Thus we need $\geq 30$ more combinations, making a total of $33$, a contradiction.
Therefore $a, c, e$ are pairwise distinct. Then there are $5$ choices for $x$ and at least $5$ choices for $y$, so there are $25$ combinations of the form $1xy$ which have not been ruled out, so we require $\geq$ $25$ combinations of the form $nxy$ (where $n \not =1$) to rule these out. That gives $28$ combinations tried so far.
Now note that by the lemma, we need to try at least $3$ combinations with $a$ in the middle, and we currently only have one such combination $1ab$ (all the $nxy$ combinations have $x \not =a$). Thus we need to try two more combinations with $a$ in the middle. Similarly, we need to try two more combinations with $c$ in the middle, and two more with $e$ in the middle, giving a total of $34$ combinations tried, a contradiction.
We conclude that we require at least $32$ tries, and this is indeed minimal by our construction at the start of the post.
Answer: The first combination you try rules out $22$ possibilities from the total of $512$. Ideally, each combination you try will rule out another $22$, for a total of $$\left\lceil \frac{512}{22} \right\rceil = 24$$ combinations.
However, we can't actually find a set of $24$ special combinations so that the possibilities they rule out are distinct. Below is a rather messy attempt.

Without loss of generality, we can assume that the first combination we try is $111$. This rules out $111$, $\text{A}11$, $1\text{B}1$, and $11\text{C}$, for digits $\text{A} \neq 1$, $\text{B} \neq 1$, and $\text{C} \neq 1$.
If we try $222$, $333$, and so on up to $888$, each of those attempts rule out $22$ possibilities as well. After these, we've ruled out $22 \cdot 8 = 176$ possibilities. Which possibilities are left? Exactly those with no repeated digits.
If we try $123$, we have an overlap with $121$, $122$, $113$, $133$, $223$, and $323$ being doubly ruled out, but we still rule out $22-6=16$ additional possibilities. We can get another $16$ ruled out by each of $456$, $781$, $234$, $567$, $812$, $345$, and $678$.
Now we have a total of $512 - 22 \cdot 8 - 16 \cdot 8 = 208$ possibilities left to rule out. These are exactly the combinations $\text{A}\text{B}\text{C}$ in which $\text{B} - \text{A} \not\equiv 0, 1 \pmod{8}$ and $\text{C} - \text{B} \not\equiv 0, 1 \pmod{8}$.
If we try $135$, we have an overlap with $133$, $155$, $535$, $335$, $115$, $131$, $145$, $235$, and $125$ but we still rule out $22-9=13$ additional possibilities. Similarly, we try $246$, $357$, $468$, $571$, $682$, $713$, and $824$, each ruling out $13$.
Now we have $512 - 22 \cdot 8 - 16 \cdot 8 - 13 \cdot 8 = 104$ possibilities left, with $24$ attempted codes.
If we try $147$, we have an overlap with $144$, $177$, $117$, $447$, $141$, $747$, $145$, $167$, $127$, $137$, $247$, and $257$, but we still rule out $22-12=10$ additional possibilities. Similarly, we try $258$, $361$, $472$, $583$, $614$, $725$, and $836$, each ruling out $10$.
Now we have $512 - 22 \cdot 8 - 16 \cdot 8 - 13 \cdot 8 - 10 \cdot 8 = 24$ possibilities left, with $32$ attempted codes.
If we simply try each of the remaining $24$ codes, we have exhausted all possibilities (and so are guaranteed to open the lock) with $24 + 32 = 56$ tests, which is less than the proposed $64$.
$56$ is probably not the minimum number of tests necessary, but this shows that it can be done in less than $64$.

I apologize for the inelegance of this construction.
Comment: Still nice to be corrected though. +1
Answer: There are $1+7+7+7=22$ configurations that open the safe. There are $8^3=512$ configurations total. If you just randomly try a configuration, it has $\frac{22}{512}$ chance of working. If you repeat, choosing random independent configurations over and over, you have an example of the geometric distribution, and the mean is $\frac{512}{22}\approx23.3$. So at least in terms of expected value, this is better than exhaustively searching through the first two lock combinations, where the expected value for the number of trials needed is $\frac{7}{8}32.5+\frac{1}{8}\frac{7}{8}4.5+\frac{1}{8}\frac{1}{8}1\approx28.9$.
Comment: i think its wrong, we are talking about a deterministic solution here. sorry
Comment: I understand. This is "at least in terms of expected value". I think it's interesting but too much for a comment
Comment: I did the calculation for randomly choosing a combination to test _excluding_ combinations you have already tried, and the expected value goes down to $22.3$. And after $64$ tries, there would be over a 95% chance that you would have cracked it. I know it's not what you are looking for, but I still think it's neat.


Control Views Bulk Operation messages?

Question: For my purposes I don't need these types of messages:
2 rows processed in about 261 ms:
Performed Email Reviewers on user joren1.
Performed Email Reviewers on user joren5.

I don't want to hide messages in general. Is there a way to specifically target messages from this module, or specific messages at all?
Answer: You can uncheck "Display processing result" in the VBO settings (in the edit view UI).
VBO for D7 stopped generating that many messages in latest -devs (after beta1). It now only shows one message: "Performed $operation on $count items."
That is something that should be backported to D6, there's an open issue for it.
In general, you can't affect those, the module is just calling drupal_set_message (usually in _views_bulk_operations_execute_finished()).
Answer: As general solution that works independently from the module that writes the messages you want to see, you can override theme_status_messages(), and filter out the messages you don't want appearing.
You need to implement hook_theme_registry_alter() in a module, using code similar to the following one:
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['status_messages'])) {
    $theme_registry['status_messages']['function'] = 'theme_mymodule_status_messages';
  }
}

theme_mymodule_status_messages() is the function that the module implements to filter out the messages that would appear to the user, and that modules add through drupal_set_message().
In the case of the Views Bulk Operations, it is enough to update the module to the latest version, but if you need to control the messages output from modules, you can implement the functions I described here.
Comment: I marked Bojan's as the answer because it addresses my specific problem most easily, but this code is going to come in handy in-future, thanks.
Comment: Hmmm can you elaborate a bit on this? What parameters does the function take? How can I determine the correct key from the theme_registry? The module that produces the messages I wish to filter isn't in the list.
Comment: The code you should write for `theme_mymodule_status_messages()` is similar to the code used by [theme_status_messages()](http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_status_messages/7); the difference is that you first check that the content of the `$message` variable (or `$messages[0]`) is the message you want to filter out; if it is the message you want to filter out, then you don't output it.
Comment: Question? when i do block multiple user at a time through views bulk operation module in views  .... i get this success message (Performed Block current user on 2 items.).. but i want to sucess message like this (user1 and user2 sucessfully blocked), please suggest me. how can i do this

Control Views Bulk Operation messages?


dynmap through mod_proxy on a external webserver

Question: My setup consist of two servers, one for hosting websites and one for doing the heavy lifting (for example Minecraft). I am using Spigot to power some plugins and one of the plugins is dynmap (which is a interactive map for showing the world and the players online). More information regarding the dynmap is here: https://github.com/webbukkit/dynmap
Anyway, I want to use a ReverseProxy on my web server and Proxy the dynmap content so I can close some ports on the router. Currently I have just made a Port forward on port 8123 to my Minecraft server.
On the web server I am currently running Apache 2.4 and I have installed mod_proxy and mod_proxy_html. I have also defined this in the vhost file for both HTTP and HTTPS:
ProxyRequests off
ProxyPass "/map" "http://192.168.2.31:8123/"
ProxyPassReverse "/map" "http://192.168.2.31:8123/"

This should be rather self explanatory. But when I access the page [WEBSITE]/map I am greeted with a white blank page. I am getting this though:
<!DOCTYPE html>

    <title>Minecraft Dynamic Map</title>

    <meta charset="utf-8" />
    <meta name="keywords" content="minecraft, map, dynamic" />
    <meta name="description" content="Minecraft Dynamic Map" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />

    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

    <link rel="icon" href="images/dynmap.ico" type="image/ico" />

    <link rel="stylesheet" type="text/css" href="css/leaflet.css?_=2.3-2074" />

    <link rel="stylesheet" type="text/css" href="css/standalone.css?_=2.3-2074" media="screen" />
    <link rel="stylesheet" type="text/css" href="css/dynmap_style.css?_=2.3-2074" media="screen" />

 For full functionality of this site it is necessary to enable JavaScript.
 Here are the
 instructions how to enable JavaScript in your web browser.

I have also defined the web server as "trusted proxy" in the dynmap config.
So my guess is that JavaScript or pictures is blocked somehow? mod_security is not installed.
EDIT
The links appears as 404, I should propably add sublinks in the proxy

EDIT 2
Alright, so I added those lines into the vhost config, and now I am getting far less errors, that's something.
        ProxyRequests off
    ProxyPass "/map"                "http://192.168.2.31:8123/"
    ProxyPass "/js"                 "http://192.168.2.31:8123/js/"
    ProxyPass "/js/minecraft"       "http://192.168.2.31:8123/js/minecraft/"
    ProxyPass "/js/map"             "http://192.168.2.31:8123/js/map/"
    ProxyPass "/css"                "http://192.168.2.31:8123/css/"
    ProxyPass "/standalone"         "http://192.168.2.31:8123/standalone/"

    ProxyPassReverse "/map"         "http://192.168.2.31:8123/"
    ProxyPassReverse "/js"          "http://192.168.2.31:8123/js/"
    ProxyPassReverse "/js/minecraft""http://192.168.2.31:8123/js/minecraft/"
    ProxyPassReverse "/js/map"      "http://192.168.2.31:8123/js/map/"
    ProxyPassReverse "/css"         "http://192.168.2.31:8123/css/"
    ProxyPassReverse "/standalone"  "http://192.168.2.31:8123/standalone/"

I am still trying to figure out why the servers does'nt send me the .js files that are located under / (see picture)

EDIT 3
Alright, this is rather strange. But if I remove the last backslash like this, I am not getting a 404 on the -js file in the catalogue /standalone.
 ProxyPass "/standalone"  "http://192.168.2.31:8123/standalone"
 ProxyPassReverse "/standalone"  "http://192.168.2.31:8123/standalone"

EDIT 4
Alright, some progress at least. Editing those lines like I did on previous edit did give me a lot of more 404, but this time it was from the tiles and images. So that is good.
 ProxyPass "/up/configuration"   "http://192.168.2.31:8123/up/configuration"
 ProxyPassReverse "/up/configuration"   "http://192.168.2.31:8123/up/configuration"

Answer: You should really check the URI mapping rules for proxy requests.
And overall prefer <Location> to handle proxied content.
Also note the ProxyPassReverse directive in Apache, as well as dynmap configuration for its web resource locations. By default, it is using relative paths, so that all you should've done is

<Location "/map/">
  ProxyPass http://192.168.2.31:8123/
</Location>

Just note that in such configuration your map will be dependent on the server being online.
Comment: So I tried to add thoose lines but it seems like I am getting a 404 **(like the first picture).**
Comment: I'd really like to debug it with you. Can you please contact me on IRC?
Comment: I have solved it in a rather strange way, do not like the solution but it works. Will post as an answer.
Comment: But I am curious to know what we can find out toghether,
Answer: Alright, after several hours of trial and error. And alot of different eyes that took a look I finally came up with a config that looked like this:
    ProxyRequests off
    ProxyPass "/map"                "http://192.168.2.31:8123/"
    ProxyPass "/js"                 "http://192.168.2.31:8123/js/"
    ProxyPass "/js/minecraft"       "http://192.168.2.31:8123/js/minecraft/"
    ProxyPass "/js/map"             "http://192.168.2.31:8123/js/map/"
    ProxyPass "/css"                "http://192.168.2.31:8123/css/"
    ProxyPass "/standalone"         "http://192.168.2.31:8123/standalone"
    ProxyPass "/up/configuration"   "http://192.168.2.31:8123/up/configuration"
    ProxyPass "/version.js"         "http://192.168.2.31:8123/version.js"
    ProxyPass "/images"             "http://192.168.2.31:8123/images/"
    ProxyPass "/tiles/world/t"      "http://192.168.2.31:8123/tiles/world/t"
    ProxyPass "/tiles/world/t_day"  "http://192.168.2.31:8123/tiles/world/t_day"
    ProxyPass "/tiles/world_nether/nt"      "http://192.168.2.31:8123/tiles/world_nether/nt"
    ProxyPass "/tiles/world_nether/flat"      "http://192.168.2.31:8123/tiles/world_nether/flat"
    ProxyPass "/tiles/world_the_end/st"      "http://192.168.2.31:8123/tiles/world_the_end/st"
    ProxyPass "/up/world/world"     "http://192.168.2.31:8123/up/world/world"
    ProxyPass "/up/world/world_nether"     "http://192.168.2.31:8123/up/world/world_nether"
    ProxyPass "/up/world/world_the_end"     "http://192.168.2.31:8123/up/world/world_the_end"
    ProxyPass "/mapimages"          "http://192.168.2.31:8123/mapimages/"
    ProxyPass "/tiles/_markers_"    "http://192.168.2.31:8123/tiles/_markers_"
    ProxyPass "/tiles/faces/16x16"  "http://192.168.2.31:8123/tiles/faces/16x16"
    ProxyPass "/tiles/faces/32x32"  "http://192.168.2.31:8123/tiles/faces/32x32"

    ProxyPassReverse "/map"         "http://192.168.2.31:8123/"
    ProxyPassReverse "/js"          "http://192.168.2.31:8123/js/"
    ProxyPassReverse "/js/minecraft""http://192.168.2.31:8123/js/minecraft/"
    ProxyPassReverse "/js/map"      "http://192.168.2.31:8123/js/map/"
    ProxyPassReverse "/css"         "http://192.168.2.31:8123/css/"
    ProxyPassReverse "/standalone"  "http://192.168.2.31:8123/standalone"
    ProxyPassReverse "/up/configuration"            "http://192.168.2.31:8123/up/configuration"
    ProxyPassReverse "/version.js"  "http://192.168.2.31:8123/version.js"
    ProxyPassReverse "/images"             "http://192.168.2.31:8123/images/"
    ProxyPassReverse "/tiles/world/t"             "http://192.168.2.31:8123/tiles/world/t"
    ProxyPassReverse "/tiles/world/t_day"             "http://192.168.2.31:8123/tiles/world/t_day"
    ProxyPassReverse "/tiles/world_nether/nt"      "http://192.168.2.31:8123/tiles/world_nether/nt"
    ProxyPassReverse "/tiles/world_the_end/st"      "http://192.168.2.31:8123/tiles/world_the_end/st"
    ProxyPassReverse "/up/world/world"   "http://192.168.2.31:8123/up/world/world"
    ProxyPassReverse "/up/world/world_nether"     "http://192.168.2.31:8123/up/world/world_nether"
    ProxyPassReverse "/up/world/world_the_end"     "http://192.168.2.31:8123/up/world/world_the_end"
    ProxyPassReverse "/mapimages"          "http://192.168.2.31:8123/mapimages/"
    ProxyPassReverse "/tiles/_markers_"    "http://192.168.2.31:8123/tiles/_markers_"
    ProxyPassReverse "/tiles/faces/16x16"  "http://192.168.2.31:8123/tiles/faces/16x16"
    ProxyPassReverse "/tiles/faces/32x32"  "http://192.168.2.31:8123/tiles/faces/32x32"

This works (in my case), but I know that I have to redefine all rules if there is a change in the catalogue structure.
Everything works as I should with this config.
Just change the world names if your is diffenrent.
I would also recommend any reader to try "AnrDaemons" suggestion


How to adjust sample weights in Adasboost

Question: I am following this video tutorial to understand Adaboost
I am confused about the sample weights updating. It first calculates the amount of say of each stump by this formula,

where total error is sum of the weights associated with incorrectly classified samples.
Based on this formula, amount of say ranges from negative infinity to positive infinity. Then it updates the sample weight according to this rule.

Incorrectly classified samples

Correctly classified samples

I am confused about why this updating works. I understand when amount of say is greater than 0, the formula makes sense to me. But when amount of say is below 0, then we would actually decrease the weights for incorrectly classified samples, and increase the weights for correctly classified samples. Anything I miss here? How to udpate sample weights each round?
Answer: In Adaboost you always decrease the importance of correctly classified samples, and increase the importance of the incorrectly classified ones. The exponential function has values >1 for positive exponent and between 0 and 1 for a negative one.

So assuming "amount of say" is a positive factor, incorrectly classified samples will have their weights multiplied with factor >1, while correctly classified ones will be reduced, with a factor from 0 to 1.
Comment: But the formula does not work when amount of say is a negative factor. When amount of say is negative, based on the formula here, sample weights for incorrectly classified samples actually decrease, but for correctly classified samples increase.
Comment: Or shall we use another set of formula when amount of say is negative?


Measurable rectangles inside a non-null set

Question: Consider $[0,1]^2$ with Lebesgue measure $\mu$.  Let $D\subseteq [0,1]^2$ be measurable with $0<\mu(D)<1$.  Can you find $A,B\subseteq[0,1]$ measurable with $\mu(A)\mu(B)>0$ and yet $\mu(D\cap (A\times B))=0$?  (That is, I want to find a non-null rectangle which is essentially inside the complement of $D$).
Some thoughts:

By regularity, we may suppose that $D$ is open, and that $A$ and $B$ are closed
If $D$ is not dense, then the answer is easily "yes".  So we may suppose that $D$ is open and dense.
You can then write $D$ as a countable union of open rectangles with rational coordinates.  Treating each one at a time, we can delete null sets from A or B.  Repeating countably many times shows that if $A$ and $B$ exist, then actually, we can choose them with $D \cap (A\times B) = \emptyset$.

I somewhat suspect that this is false, but I cannot find a counter-example (I can't get the usual trick of, say, covering the rationals by small open balls to work).
Answer: The existence of a counterexample is implied by Theorem 2.1 of Kendall and Montana's paper "Small sets and Markov transition densities".  Below is an excerpt from pages 180-182, including the beginning of the section for context.
This question is answered with a different approach in Halmos's Problems for mathematicians, young and old.  Problem, Hint, and Solution 14.E are given below the Kendall and Montana excerpt.

And here's Halmos:
Comment: Brilliant!  And if I could +1 twice for including scans of the article, I would.  That is indeed more complicated than I expected...
Comment: Btw, did you just happen to know this paper?  Or did you manage to search for it?  If the latter, any hints on how you found it??
Comment: @Matthew: I did not know about it in advance.  I don't remember the exact Google search, but it included `"measurable rectangle"`, and probably `null`.  This also led me to Halmos.
Comment: I cannot follow Halmos's proof. First, I do not understand the significance of the second-to-last paragraph, where he shows that $D \cap (E-F)$ includes a non-empty open set; this fact seems to not be used anywhere. Next, in the last paragraph, he claims for *each* real number $y$ that $(\delta^{-1}(D) \cap (E \times F))^y = (D+y) \cap E$, which is only true in case of $y \in F$; this latter condition is used implicitly in the last line of the three-line equation. This restriction on $y$ completely kills the calculation of $\lambda(\delta^{-1}(D) \cap (E\times F))$ - or am I missing something?
Answer: I don't see the need to work so hard. Let $S$ be the unit square $[0, 1]^2$, $D = \{(x, y) \in S : x + y \notin \mathbb{Q}\}$. Then both $D$ and $S \backslash D$ are positive rectangle free (for $D$, use Steinhaus theorem). Now divide $S$ into four equal squares and choose $E \subset S$ which is the union of $D$ relativized to 1st and 3rd square and $S \backslash D$ relativized to 2nd and 4th square. Then, $E$ has area $1/2$ and both $E$ and $S \backslash E$ are positive rectangle free.


Prove that $\forall \ n \in \mathbb{N}, \ n^2 + 3n + 2$ is not prime

Question: Can anyone explain step by step how to use direct proof for solve this type of sum. Seriously I am confused with direct proof.
Comment: Have you tried factorizing the expression?
Comment: Actually i don't know how to approach this type of a sum.
Comment: That is quadratic equation, even if you can't guess the solution, you should be able to calculate the roots.
Answer: Try factoring $n^2 + 3n + 2$. You get $(n+1)(n+2)$. Observe that since we deal with only positive numbers, none of $n+1$ or $n+2$ is equal to 1. Prime numbers are those numbers which do not have any factors other than $1$ and itself. But $n^2 + 3n + 2$ has two factors namely $n+1$ and $n+2$. So it is not a prime.
Since you asked for a direct proof I will suggest another proof. Consider that for all odd and even integers that number $n^2 + 3n + 2$ is even. The function is strictly increasing and the lowest value for $n=1$ turns out to be $6$. We know that all even numbers greater than $6$ are composite.
Comment: I know find factors for the expression. but I don't understand how to apply direct proof theories for this proof. :(
Comment: @Rohit Edited the answer. Hope you understand that.
Comment: ok i can understand the proof. but the questions says prove this using direct proof. so what is the direct proof means? how should I apply it to solve this sum?
Comment: @Rohit I have extended the answer to prove this directly without any algebraic manipulation.
Comment: can you please explain how to solve this using algebraic manipulations.
Comment: @Rohit The first answer uses algebraic manipulation. The second one is a direct proof.
Answer: hint: $n^2+3n+2=(n+1)(n+2)$.is it clear?
Comment: yeah.. surely. know factorizing.
Answer: If $n$ is even, $n^2$ is even and $3n$ is even, thus$n^2+3n+2$ is even and hence not prime.
If $n$ is odd, $n^2$ is odd and  $3n$ is odd, thus $n^2+3n+2$ is again divisible by 2.


Proving that s = 1 maximises the expression

Question:
Consider two discrete random variables, $X$ and $Y$, with a joint distribution $P_{X,Y}$. Prove that $s=1$ maximizes the following inequality:
\begin{align}
&\sum_{x, y} P_X(x) P_{Y \mid X}(y \mid x) \log \left(\frac{P_{Y \mid X}(y \mid x)^s}{\sum_{\bar{x}} P_X(\bar{x}) P_{Y \mid X}(y \mid \bar{x})^s}\right)\\
\leq{}& \sum_{x, y} P_X(x) P_{Y \mid X}(y \mid x) \log \left(\frac{P_{Y \mid X}(y \mid x)}{\sum_{\bar{x}} P_X(\bar{x}) P_{Y \mid X}(y \mid \bar{x})}\right)\\
={}& I(X; Y).
\end{align}
Here, $\bar{x}$ has the same marginal distribution as $x$.

A simple approach is to prove the concavity of the expression in $s$ using Holder's inequality and then demonstrate that the derivative with respect to $s$ is zero when $s=1$. However, this doesn't seem to be an elegant solution, and my intuition suggests that there might be a concise proof, perhaps involving an inequality, that establishes this result in 3-4 lines.
Answer: Noting that $\sum_{x'} P_X(x')P_{Y|X}(y|x') = P_Y(y),$ we can define $$f(s) := \mathrm{LHS} - \mathrm{RHS}=  \sum P_{XY}(x,y) \log \frac{P_{Y}(y) P_{Y|X}(y|x)^{s-1}}{\sum_{x'} P_X(x')P_{Y|X}(y|x')^s},$$ where the "$\mathrm{LHS},\mathrm{RHS}$" refer to the inequality in the question. Clearly, $f(1) = 0$, and we want to show that $f(s) \le 0$. Now, hitting this with Jensen's inequality for the concave function $\log,$ we have $$ f(s) \le \log \sum_{x,y} \frac{P_X(x)P_Y(y) P_{Y|X}(y|x)^s}{\sum_{x'} P_X(x') P_{Y|X}(y|x')^s},$$ where I've used Bayes law to write $P_{XY} = P_X \cdot P_{Y|X},$ and folded the latter into the power. But note that for a fixed $y$, $$ \sum_x \frac{P_X(x)P_{Y|X}(y|x)^s}{\sum_{x'} P_X(x') P_{Y|X}(y|x')^s} = 1,$$ so the total sum inside the logarithm is $\sum_y P_Y(y) = 1,$ and we're done. In fact, since $\log$ is strictly concave, the same shows that unless $s$ is such that $P_Y(y)P_{Y|X}(y|x)^{s-1} = \sum_{x'} P_Y(x')P_{Y|X}(y|x')^s$ for every $x,y$ (in other words, unless $s = 1$, or $Y$ is independent of $X$), $f(s)$ is strictly smaller than $0$.


Editar diretamente via FTP com Sublime Text

Question: Quero trabalhar via FTP com o Sublime Text 2. Não quero apenas conectar via FTP e transferir arquivos, mas sim, editar o arquivo, e quando salvá-lo, ele envia diretamente para o servidor, por FTP. Assim, como é feito no Komodo. Isso é possível?
Answer: Essa funcionalidade não está disponível no core do Sublime Text, mas é possível com plugins. Uma pesquisa no Google encontrou dois entre os primeiros resultados:

SublimeText2-FTPSync
Gratuito, mas sem suporte a SFTP
Sublime SFTP
Pago (USD 20), com suporte a SFTP
Comment: @FelipeStoker Eu na verdade nunca usei esses plugins. Mas se você não precisa de SFTP (que é como o FTP, mas por SSH), a primeira opção deve servir.
Comment: Desculpe a pergunta leiga. Mas, é necessário SFTP? O FTPSync exige a instalação do SFTP?
Answer: Cara, eu costumo usar o FileZilla como Client para FTP, e tenho configurado o Sublime como editor padrão para ele...e quando faço edição a partir dos arquivos do servidor, salvando o FileZilla já pergunta se quero enviar ao servidor novamente com as alterações.

Depois de salvar:
Comment: Isso funciona para editar um arquivo individual, mas se quiser trabalhar com um projeto, não serve (por exemplo, não dá para abrir um arquivo com CTRL+T).
Comment: Obrigado amigo. Mas, eu gostaria de editar direto no servidor, pelo que vi não é tão simples quanto parece, bem que poderia ser igual ao Komodo, apenas instalar um plugin e ponto final.
Comment: Esse esquema é bom, mas somente para edições pontuais. Mas acho válida a resposta como uma alternativa para casos específicos.
Answer: Se você ainda procura por isso, tanto no SFTP quanto no FTPSync, pode-se fazer alterando a linha " 'upload_on_save': false " para " 'upload_on_save': true" no arquivo de configurações do próprio plugin, onde você fornece o host, user e pass. Desta forma ao salvar o arquivo o plugin faz o upload automaticamente. Vlw Flw
Answer: Já tentei fazer isso também, na qual vida de programador, isso mesmo desafios todos os dias, um programa leve que faz isso é o cute ftp.
Comment: Essa resposta está um tanto incompleta quanto estranha (como se fosse traduzida para português por um tradutor online).


SpringBoot app running on AWS-EC2 unable to connect to MySQL AWS-RDS database

Question: I am having problems running an app I have developed in an EC2 instance. When I execute the .jar (java -jar app.jar), the SpringBoot app starts but it fails when trying to connect to my MySQL RDS database. The thing is when I run the app locally on my machine, It has no issues with the DB connection.
I have opened the port where the app is running (8090) and MySql port as well (3306) for inbound and outbound traffic:

This is the error I get:

2016-09-23 17:46:38.132  INFO 10161 --- [main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 8090
2016-09-23 17:46:38.604  INFO 10161 --- [main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-09-23 17:46:38.605  INFO 10161 --- [main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.54
2016-09-23 17:46:38.724  INFO 10161 --- [ost startStop 1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-09-23 17:46:38.725  INFO 10161 --- [ost startStop 1] o.s.web.context.ContextLoader: Root WebApplicationContext: initialization completed in 5028 ms
2016-09-23 17:48:48.476 ERROR 10161 --- [ost startStop 1] o.a.tomcat.jdbc.pool.ConnectionPool: Unable to create initial connections of pool.

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

Any ideas how can i solve this problem?
Thank you very much  for your help
Regards
Andres
Answer: From your description and log file, it's likely that network configuration is the cause here.
You might want to draw the network topology of your instances (region/availability zone, VPC, subnet, network acl, security group). This will be very helpful when you do more complex development work.
There are good references: VPC Introduction and Security in your VPC and Scenarios for Accessing a DB Instance in a VPC
I suggest the following actions for your troubleshooting:

Check security group (SG) configuration of your EC2 instance and RDS instance.
You can check this by going to EC2 Dashboard/RDS Dashboard -> Click on an instance and look at "Security Group" description, or you can click on the Setting icon (Show/Hide columns) and tick "Security Groups".
In RDS's SG configuration: make sure you have enable access from EC2 instance's SG to port 3306. You can do this by putting EC2 instance's SG ID into Source field of the config, as a "Custom IP" value. See the 1st scenario in the above reference for more detail.
Use mysql command line to test the connection between EC2 instance and RDS.

Hope it helps.
Comment: Thank you very much for you response @LiemPham. You were right. the problem was that RDS security group did no have an Inbound Rule for EC2 security group. Both RDS and EC2 were in the same VPC and subnet but they could not talk to each other. The three link related to VPC were very useful to understand how EC2 and RDS communicates in AWS.
Answer: You need to perform following steps :
1) Go to EC2 instance and find security group you want access in RDS

2) Now go to your RDS security group and select inbound rules
  Select ALL TCP and add your sg-xxx(security group)

https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.Scenarios.html


Element by element formulae for 3x3 matrix inversion

Question: Given a 3 x 3 matrix:
$$
       A= \begin{bmatrix}
        a & b & c \\
        d & e & f \\
        g & h & i \\
        \end{bmatrix}
$$
Can $A^{-1}$ be shown as as a 3x3 matrix with each element in terms of $a,b,c,d,e,f,g,h$ and $i$. Showing  basic operators (only $+ - / *$)?
Comment: see [http://en.wikipedia.org/wiki/Inverse_matrix#Inversion_of_3.C3.973_matrices]
Answer: $$A^{-1}=\frac{1}{\det(A)} adj(A)$$
$$\det(A)=aei+dhc+bfg-ceg-bdi-afh$$
$$adj(A)= \begin{bmatrix}
        ei-fh & ch-bi & bf-ce \\
        fg-di & ai-cg & dc-af \\
        dh-ge & bg-ah  & ae-bd \\
        \end{bmatrix}$$
_
Comment: +1 Nice one @N.S.


Computing profile confidence intervals for a regression line

Question: Simulate some data
n       <- 50
beta0   <- 2
beta1   <- 0.32
x       <- runif(n=n, min=0, max=5)
mu      <- exp(beta0 + beta1 * x)
y       <- rpois(n=n, lambda=mu)
data    <- data.frame(x=x, y=y)
plot(data$x, data$y)

Apply a Poisson regression
glm.pois <- glm(formula= y ~ x, data=data, family=poisson(link="log"))
summary(glm.pois)

Compute profile 95% CI
(pCI <- confint(glm.pois))
nice.xs <- sort(data$x)
pred.pCI   <- apply(t(pCI), 1, FUN=function(x){exp( x[1]+x[2]*nice.xs)})

Compute 95% CI using the SE
new.dat <- data.frame(phat = predict(glm.pois, type="response"),
                      x  = data$x)
new.dat <- new.dat[with(new.dat, order(x)), ]
ilink <- poisson()$linkinv

## Add fit and se.fit on the link scale
new.dat <- bind_cols(new.dat,
     setNames(as_tibble(predict(glm.pois, new.dat,
                           se.fit = TRUE)[1:2]),
              c('fit_link','se_link')))
new.dat <- mutate(new.dat,
                  fit  = ilink(fit_link),
                  right_upr = ilink(fit_link + (2 * se_link)),
                  right_lwr = ilink(fit_link - (2 * se_link)))

Plot
ggplot(data=new.dat, aes(x=x, y= phat)) +
    geom_point() +
    geom_ribbon(aes(x=x, ymin =right_lwr, ymax = right_upr),
                fill = "darkgreen", alpha=0.3) +
    geom_ribbon(aes(x=nice.xs, ymin = pred.pCI[,1], ymax = pred.pCI[,2]),
                fill = "darkorange", alpha=0.3) +
    theme_classic(base_size=15)

My question is why are the profile 95% CI (orange ribbon) so large? I imagine I am computing them wrong but I don't know where my mistake is.
Answer: There is a very strong correlation between the intercept and slope:
cov2cor(vcov(glm.pois))
            (Intercept)          x
(Intercept)   1.0000000 -0.9147526
x            -0.9147526  1.0000000

Your profile CIs, which are computing (logistic(intercept_lwr + slope_lwr*x) and logistic(intercept_upr + slope_upr*x), are ignoring this correlation.
It's not easy to compute profile confidence intervals on derived values (i.e., on quantities other than the parameters themselves).
Comment: Great, thank you. I imagined this was the case but couldn't find it explicitly stated anywahere (maybe I was looking in the wrong places).


Find $x_{1}$ such that $x_n$ is convergent $x_{n+1}=(n+1)x_n -1,$ $\forall n \in N^{*}, n\ge 1$

Question: Let $x_n$ be a sequence of real numbers such that $x_{n+1}=(n+1)x_n -1,$ $\forall n \in N^{*}, n\ge 1$ .Find $x_1$ such that  $x_n$ converges.
$\text {My attempt: }$
The only way that i tried to use was to write $$y_n=nx_n,\text{ and obtain that }y_{n+1}-y_n=(n^2+n+1)\frac{y_n}{n}-n-1, \text {So, it s similar to }
 y_{n+1}+\alpha_n y_n=\beta_n$$
So, we can find the general solution of the homogeneous associated recurrence
$$ y_{j+1}+\alpha_j y_j=0.
\forall  j \in N^{*} \text { We get that }
y_{n+1}=(-1)^n \prod_{j=1}^{n}\alpha_j y_1 $$
$\text {That is where i could not continue anymore }$
Comment: @Medo, what are you talking about??
Comment: The value of $x_1$ does not predict any thing about convergence of a sequence. In fact, neither do the first finite number of terms. So, why is this sequence special ?
Comment: @Empy2: $e-2$, to be more precise.
Comment: Please show your attempt.
Comment: $x_2=2x_1 +1$, $x_4=24x_1-17$ so for arbitrary $n$ we have something like this $x_n=n!x_1-S(n)$ where $S$ depends on $n$ and goes to infinity "slower than" $n!$
Comment: So slightly more than 17/24 then.
Comment: @TonyK, how to get that constant? I ve posted what i tried
Answer: We have
$$x_n=n!\,x_1-u_n$$
for the sequence $(u_n)=(0,1,4,17,86,\ldots)$ defined by $u_1=0$ and $u_{n+1}=(n+1)u_n+1$.
Now define the sequence $(v_n)$ by $v_n=u_n/n!$ Then we can rearrange $u_{n+1}=(n+1)u_n+1$ to get $v_{n+1}=v_n+1/(n+1)!$ So $(v_n)$ looks like:
$$\left(0,\;\;\frac{1}{2!},\;\;\frac{1}{2!}+\frac{1}{3!},\;\;\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!},\;\;\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\frac{1}{5!},\;\ldots\right)$$
which tends to $e-2$.
Also, we have $x_n=n!x_1-u_n=n!(x_1-v_n)$.
What this tells us is that $(x_n)$ certainly doesn't converge unless $x_1=e-2$. But this doesn't necessarily mean that ($x_n)$ converges, because there is a factor of $n!$ that might throw things off. You have to show that it converges by estimating the error term $n!(v_n-(e-2))$, which you should try to show tends to $0$ (it's not too hard).


"Where is the Mouse Right Now?"

Question: I'm trying to write a program that will constantly display x- and y- coordinates of the mouse cursor as I move it around(Automate the boring stuff in python page 417).
I have tried adjusting indentation of the Try statements,but I was still
receiving indentation error message.
import pyautogui

print('press Ctrl-C to quit.')

try:

    while True:

except KeyboardInterrupt:

     print('\nDone.')

        x,y=pyautogui.position()

        positionStr='X: ' + str(x).rjust(4) + 'Y: ' + str(y).rjust(4)

        print(positionStr,end='')

        print('\b'*len(positionStr),end='',flush=True)

I expected an output of two lines like below:
press Ctrl-C to quit.
X:290 Y:424
But the output I got was :
 File "<ipython-input-2-b3f3ee266ed5>", line 6

    except KeyboardInterrupt:
                             ^
IndentationError: expected an indented block

Comment: See above. Your line of `while True:` must be followed by the body of the loop.
Answer: The code should be:
import pyautogui

print('press Ctrl-C to quit.')

try:
    while True:
        x,y=pyautogui.position()

        positionStr='X: ' + str(x).rjust(4) + 'Y: ' + str(y).rjust(4)

        print(positionStr,end='')

        print('\b'*len(positionStr),end='',flush=True)

except KeyboardInterrupt:
    pass

You had the loop body in the exception handling block.
Well at least it works now to make the output more useful. What is needed is to only print if the position changed from the last time it was polled and to put in a time.sleep(0.1) in the loop.
import pyautogui
import time

print('press Ctrl-C to quit.')

last_position = None

try:
   while True:
       x,y=position=pyautogui.position()

       if position != last_position:

           positionStr='X: ' + str(x).rjust(4) + 'Y: ' + str(y).rjust(4)
           print(positionStr,end='')
           print('\b'*len(positionStr),end='',flush=True)

       last_position = position
       time.sleep(0.1)

except KeyboardInterrupt:
   pass

This reduces the speed of the loop and it will only print if the position has changed.
Comment: Hi Dan D. I already applied your strategy before,but like I said I expect the program to output only two lines,so that as you move the cursor around the coordinates will be changing.But with the technique of placing except Keyboard at the end of the program,the output is unending x- and y- coordinates.
Comment: Do you mean that you also want the new output from the program to overwrite the prior output? That can be done but perhaps the additions I propose will reduce the output enough.

"Where is the Mouse Right Now?"


Protecting a webpage with an authentication form

Question: I have created an employee webpage with a lot of company info, links, etc., but I want to protect the page because it contains some confidential company information. I am running IIS7 on Windows Server 2008 R2, and I already have the site setup as a normal, non-protected site. I want all active directory users to have access to the site. This is not an intranet site, it is exposed to the internet. I tried setting it up using Windows Authentication, but I had problems with multiple login prompts, etc. I just want a simple form for users to enter their credentials and have access to the site, and I need it to query the AD for login. I've searched the web for a guide on this, but I can't seem to find one that fits my situation. This is not a Web App. It is just a simple html site.
Does anyone have any suggestions or a link to a guide on this?
Thanks so much!
-LB
Answer: If the server isn't directly exposed to the internet, but is exposed via a reverse proxy like IAG, UAG, TMG, then the simplest way to set this up is to enable forms based authentication there.
If it's directly exposed to the Internet, a) urgh, are you sure you want this?, b) look into using IIS Forms-Based Authentication - it's installed with ASP.Net and can be configured with a variety of authentication providers, but won't run against non-ASP.Net content by default - you'll need to toggle the ManagedHandler precondition for the FormsAuthenticationModule in order for it to work.
Don't forget SSL to protect the credentials when being sent via the web form.
Comment: +1 for "urgh, are you sure you want to do this?"
Comment: Just curious, but why do you ask if I would want to do this? Is there a better alternative?
Comment: So the "sure you want to do this" refers to the "this server is on the Internet" part; it might already be reverse-proxied or otherwise protected, but the question doesn't provide any details on this, and creates the impression that a social engineering/phishing goldmine has been established on a relatively unprotected server. It is absolutely the right approach to want to protect that information, and I commend you for having reached that conclusion, but having a server directly exposed to the Internet with a questionable security configuration is often how breaches start.
Comment: Ah, no no no. The entire server is not directly exposed to the Internet, I just have port 80 opened in the firewall. Is there more I should be doing?


Intuition behind why continuous random variables cannot take a particular value?

Question: It was iterated over and over again in our probability class that continuous random variables CANNOT have a probability mass function, instead they NEED TO have a density function. I am trying to find some intuition behind this. Any help would be greatly appreciated.
Additionally the following facts were mentioned:

The probability distribution function of some continuous random variable may take a value larger than 1. Why/How?

In the case of a continuous random variable, $P(X=x) \ne p_{x}(x)$. Why?
Comment: It's also worth mentioning that there are random variables that are neither continuous nor discrete. Such a variable takes certain individual values with nonzero probabilities and takes other values in a way described by a probability density function. https://math.stackexchange.com/questions/3967681/can-random-variables-be-something-else-other-then-discrete-or-continuous
Comment: If you know a bit of physics, the analogy of probability density with mass density is really clear.  The mass of some volume is the integral of the mass density over the volume.  For a volume much less than one unit, even if the density is very large the mass of that volume can still be small.  Similarly, the probability of an event is the integral of the probability density over the region of the domain where that event happens.  So the integral over the whole domain is 1, but the density at some point may be arbitrarily large.
Comment: A really simple way to intuitively understand the probability of a single point being zero is that if you select a single mathematically exact point on a wall and THEN throw a dart at the wall, the probability of it hitting that point is zero.  Yet if you throw a dart at a wall and THEN measure the exact point it hit, obviously it did hit an exact point.  Sometimes we expect something different for more complex problems, but it often comes down to this.
Comment: I like to think of examples of mass functions and densities to get a feel for them. A mass function could tell you the probability of $N$ people visiting a store in a day. A density could tell the probability of the height of a person randomly drawn from the population lying between 5ft-6ft.
Answer: If there is some $c\in \mathbb{R}$ such that $\Pr [X=c]>0$ then the distribution function of $X$ at $c$ is discontinuous. To see this we will show the contrapositive statement: if $F_X$ will be continuous at $c$ then we will show that $\Pr [X=c]=0$.
First, as by assumption $F_X$ is continuous at $c$, then
$$
\lim_{x\to c}F_X(x)=F_X(c)\tag1
$$
Also we have that
$$
\Pr [X=c]= \Pr [X\leqslant c]-\Pr [X<c]\tag2
$$
But as a probability is a measure then
$$
\begin{align*}
\Pr [X<c]&=\Pr [X^{-1}((-\infty ,c))]\\
&=\Pr \left[\bigcup_{n\in \mathbb N }X^{-1}((-\infty ,c-1/n])\right]\\
&=\lim_{n\to\infty}\Pr [X^{-1}((-\infty ,c-1/n])]\\
&=\lim_{n\to\infty}F_X(c-1/n)\tag3
\end{align*}
$$
Thus from (1) and (3) we find that if $F_X$ is continuous at $c$ then $\Pr [X<c]=\Pr [X\leqslant c]$, and consequently from (2) we have that $\Pr [X=c]=0$.∎
Answer: We know from the probability axioms that the total probability over a sample space is $1$. For a continuous random variable, this corresponds to the area to the left of a point under the curve. So, the probability $P(X=x)$ is the area of an infinitely small strip with some height, and so the area is $0$.
The way to formalise this is to consider the probability $P(X-\epsilon<x<X+\epsilon)$.
As for your first question, can you elaborate further with a specific example?
Answer: I'll elaborate on the idea of "almost never" in probability - this refers to an event that occurs with probability 0, but is not impossible. Suppose we want to pick a random number from the uniform distribution on [0, 1]. There are an infinite number of choices, so the odds that we will pick exactly 0.5 (or any other numer) is zero. The fact remains, however, that 0.5 is in the range we're selecting from, so it is actually possible to pick it. A continuous random value does take on a particular value, despite the fact that the likelihood of picking any particular value is actually zero. If you throw a dart at the number line in the [0, 1] range, you have zero likelihood of hitting any particular value with infinite precision, but the dart still must land somewhere.
Answer:
The probability distribution function of some continuous random variable may take a value larger than 1. Why/How?

For the same reason that you can drive somewhere one mile away while going at speeds faster than 1 mph.
The same general idea applies to the rest of the questions.
Answer: Maybe this will help clarify things:
Suppose you tried to use a mass function for a continuous r.v.  This is a function that assigns nonzero probability to some basic, atomic outcomes.  There is an uncountably infinite number of outcomes that have values, though, given a continuous distribution.
How could you write a summation to define the expectation?  There are not enough numbers in the infinite series of integers that would index a summation.
OK, but suppose, magically (doesn't really make sense, but let's try it out for the sake of a reductio) you could write the expectation as a sum.  Since there is an infinite number of values, each with equal probability (otherwise the distribution will not be continuous), all values have zero probability, in which case the total probability is zero, or else the probabilities are nonzero, in which case the total probability is infinite.  But the sum must be equal to 1.
With a density function, you can "sum" using an integral, though. Each possible value of the r.v. has zero probability, but regions of values have nonzero probability.  That's why the expectation of a continuous r.v. can be written as an integral over a density function.


foreign key is null Springboot jpa

Question: customer

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor

@Entity
@Table(name = "customer")
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "customer_id")
    private Long customerId;

    @NonNull
    @Column(name = "name")
    private String name;

    @NonNull
    @Column(name = "address")
    private String address;

    @NonNull
    @Column(name = "house_no")
    private String houseNo;

    @Column(name = "active")
    private boolean active = true;

    @NonNull
    @Column(name = "customer_type")
    private String customerType;

    @NonNull
    @Column(name = "pack")
    private String pack;

    @JsonIgnore
    @OneToOne(mappedBy = "customer",cascade = CascadeType.ALL)
    private Stb stb;

    @JsonIgnore
     @OneToOne(mappedBy = "customer",cascade = CascadeType.ALL )
    private Payment payment;

    @JsonIgnore
    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    private List<History> history;

}

History
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor

@Entity
@Table(name = "history")
public class History {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "history_id")
    private Long historyId;

    @Column(name = "amount_paid")
    private Long AmountPaid;

    @LastModifiedDate
    @Column(name = "payment_date")
    private String paymentDate;

    @Column(name = "due")
    private Long due;

    @JsonIgnore
    @ManyToOne(optional = false,fetch=FetchType.LAZY)
    @JoinColumn(name = "customer_f_id",referencedColumnName = "customer_id")
    private Customer customer;

payment
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "payment")
public class Payment {
    public Long normalPrice =220L;
    public Long sportsPrice = 250L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "payment_id")
    private Long paymentId;

    @Nonnull
    @Column(name = "amount_paid")
    private Long paid;

    @Nullable
    @LastModifiedDate
    @Column(name = "payment_date")
    private String paymentDate;

    @Nullable
    @Column(name = "due")
    private Long due;

    @JsonIgnore
    @OneToOne(fetch=FetchType.EAGER,optional=false)
    @JoinColumn(name = "customer_f_id",referencedColumnName = "customer_id")
    private Customer customer;

stb

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "stbox")
public class Stb {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "stb_id")
    private Long StbId;

    @NonNull
    @Column(name = "stbox_number")
    private String StboxNumber;

    @NonNull
    @Column(name = "stbox_id")
    private String StboxId;

    @NonNull
    @Column(name = "stbox_cust_number")
    private String StboxCustNumber;

    @NonNull
    @Column(name = "stbox_type")
    private String StboxType;

    @JsonIgnore
    @OneToOne(optional = false,fetch=FetchType.LAZY)
    @JoinColumn(name = "customer_f_id",referencedColumnName = "customer_id")
    private Customer customer;

im new to springboot , i just assigned foreign key in many ways i watched many tutorials and blogs and tried it out but it all failed , the foreign key is always set to null, anybody help , thanks in advance :) .
im trying to create a foreign key in stb , payment ,history but i refered it correctly but it ssets to null
Answer: Are you setting both sides of the joins?
public class Customer {
  public void setStb(Stb stb) {
    this.stb = stb;
    stb.customer = this;
  }
}

or outside maybe?
public void setCustomerStb(Customer customer, Stb stb) {
  customer.setStb(stb);
  stb.setCustomer(customer);
}

The same also applies to the other joins.

foreign key is null Springboot jpa


What am I missing (Fundamental Normality Test)?

Question: Consider $\Omega=\{z\in\mathbb{C}:|z|<1\}$ and let $\mathcal{F}=\{f(z)=z+n:n\in\mathbb{N}\}$. We have that $\mathcal{F}$ is a family of holomorphic functions defined over $\Omega$ whose range omits infinite points of $\mathbb{C}$; hence by the Fundamental Normality Test we can say that $\mathcal{F}$ is a normal family, but this family is not uniformly bounded under compact sets of $\Omega$.
I am sure it has to be something obviuos but I have been thinking for a while and I do not find any clue of why my reasoning is wrong.
What am I missing here? Any help would be appreciated.
Comment: What version of the fundamental normality test as you using?
Answer: This family is certainly not normal with respect to $(\Omega,\mathbb{C})$, as it is not locally uniformly bounded. Indeed, take any compact subset $K$ of $\Omega$ that contains the origin, and suppose the family $\{f_n\}$ were uniformly bounded by some $M>0$. Consider the image of $0$ under the family. If we choose $N$ so that $N>M,$ then $|f_N(0)|=N>M.$
Read your version of the fundamental normality test again carefully and make sure that it applies exactly. Does it apply to $(\Omega,\mathbb{C})$ or to $(\Omega,{\hat{\mathbb{C}}})?$ Is the question about normality with respect to $(\Omega,\mathbb{C})$ or to $(\Omega,{\hat{\mathbb{C}}})?$
Recall that normality can be defined on the Riemann sphere, in which case the above work is not sufficient. In this scenario, we either need that a subsequence converges uniformly on each compact subset as a sequence into $\mathbb{C}$ (we can rule this out) or that it converges to $\infty$ uniformly on compact subsets.
This part is true. Fix any compact $K\subset\Omega.$ Note that if $z\in K,$ then $$|f_n(z)|=|n+z|\geq n-|z|\geq n-1\rightarrow\infty$$ uniformly in $n$ as $n\rightarrow\infty$. This is because the FNT that you've seen was likely applied to $\hat{\mathbb{C}}.$
Comment: My original statement to prove was: Let $\Omega\subset\mathbb{C}$ be a domain with $0\in\Omega$. Let $\mathcal{F}\subset\mathcal{H}(\Omega)$ with sup$\{|f(0)|:f\in\mathcal{F}\}<\infty$ and all the functions in $\mathcal{F}$ omit a ball. Prove that $\mathcal{F}$ is normal. Searching for some result that could help me I read about the Fundamental Normality Test in here: https://www.encyclopediaofmath.org/index.php/Normal_family, which a priori solved my problem but then the example I wrote originally in the post seemed to contradict this Fundamental Normality Test.
Comment: Still don't understand exactly what I am missing, but the truth is that I have only worked with normality referring to $\mathbb{C}$ and not $\hat{\mathbb{C}}$. Anyway, thanks for your help.
Comment: I am only able to take a brief glance of the page you linked at the moment, but I don't see the FNT in there. You might want to reference Schiff's Normal Families book, but the version that they have is just like the one you'll find on wikipedia. You might like this link for your problem in your first comment: https://math.stackexchange.com/questions/5016/normal-families
Comment: @G.Acd In Schiff, their version of normality is defined on $\hat{\mathbb{C}}$, and so their version of FNT is applied to $(\Omega,\hat{\mathbb{C}}).$ I suspect that the version of the theorem you've seen does, as well. The family that you listed is normal here.
Comment: I've edited my post accordingly.


Removing some elements from a list which satisfy some condition

Question: I have a list with some file names(locations), what I am trying to do is I want to remove every elements from the list locations.
Condition: do not print the file name if it starts with the any of the strings in the excludes list.
locations = ['/data/mybackup/data/fil1',
            '/data/mybackup/data/fil2',
            '/data/mybackup/data/fil3',
            '/data/mybackup/song/fil1',
            '/data/mybackup/song/fil2',
            '/data/mybackup/song/fil3',
            '/data/archive/song/fil1',
            '/data/archive/song/fil2',
            '/data/archive/song/fil3',
            '/data/archive/data/fil1',
            '/local/archive/data/fil2',
            '/local/archive/data/fil3',
            '/ebboks/wordpress/fil1',
            '/ebooks/wordpress/fil2',
            '/ebooks/wordpress/fil3']

excludes = [  '/data/archive/', '/data' , '/ebooks/'   ]

for location in locations:
  for exclude in excludes:
    if not location.startswith(exclude):
      print(location)
    break

RESULT:
/data/mybackup/data/fil1
/data/mybackup/data/fil2
/data/mybackup/data/fil3
/data/mybackup/song/fil1
/data/mybackup/song/fil2
/data/mybackup/song/fil3
/local/archive/data/fil2
/local/archive/data/fil3
/ebboks/wordpress/fil1
/ebooks/wordpress/fil2
/ebooks/wordpress/fil3

My result still have the file names starting with '/data'
What is wrong with my code?
Comment: `str.startswith` takes a tuple... If you make `excludes` a tuple instead of a list, you can do `if not location.startswith(excludes)` in one go and not have to worry about ordering/overlaps or the subloop
Comment: I think this is really just a logical error, not so much a python question. The inner loop over `excludes` will always only test against `excludes[0]` and `break`.
Answer:
Condition: do not print the file name if it starts with the any of the strings in
  the excludes list.

With all() function:
for location in locations:
    if all(not location.startswith(e) for e in excludes):
        print(location)

The output:
/local/archive/data/fil2
/local/archive/data/fil3
/ebboks/wordpress/fil1

Answer: str.startswith accepts a tuple of arguments to check against so you avoid an additional loop to check and concerns about ordering comparisons, so you can use:
exc = tuple(excludes)
# Or start with: excludes = ('/data/archive/', '/data' , '/ebooks/') instead
for location in locations:
    if not location.startswith(exc):
        print(location)

Which gives you:
/local/archive/data/fil2
/local/archive/data/fil3
/ebboks/wordpress/fil1

Comment: Thanks for your effort to solve this problem. Your solution really worked well.
Answer: For location is , let's say, "/data/mybackup/data/fil1" and exclude is "/data/archive", the location variable doesn't start with "/data/archive".
As you have a "/data" value in your excludes list, you don't need to put another path that starts with "/data". So if you define excludes = ["/data", "/ebooks"] there will be no problem.
Answer: Because you are checking against /data/archive/ first; it is letting all entries which are not starting with /data/archive/ essentially skipping the check for /data.
You can do this:
>>> excludes = tuple(excludes)
>>> filter(lambda x: not x.startswith(excludes), locations)
['/local/archive/data/fil2', '/local/archive/data/fil3', '/ebboks/wordpress/fil1']

Answer: You have to check all excludes before printing the location.
Try changing this:
for location in locations:
  for exclude in excludes:
    if not location.startswith(exclude):
      print(location)
    break

To:
def valid(location):
  for exclude in excludes:
    if location.startswith(exclude):
      return False
  return True

for location in locations:
  if valid(location):
    print(location)

Answer: try list comprehensions:
>>> [location for location in locations \
if not location.startswith(tuple(excludes))]

output:
['/local/archive/data/fil2', '/local/archive/data/fil3', '/ebboks/wordpress/fil1']

or filter with lambdas if you prefer functional programming in answer of @mshsayem


Grant a role access to certain content

Question: Is there a way to only grant a role access to certain content?
So that every user given that role can access what they need without others being able to, while still being limited from accessing content that only other roles can access?
Also is there a way to automatically grant new roles to users as a result of performing certain actions?
Just like how some forums work where you can only start new threads when you've written 10 replies? Only this will be people being able to access a new level of the site when they have say uploaded a file or corresponded with a certain person and that person has given a thumbs up?
The latter I suppose could come in form of you being granted a role when a certain level is reached that enables you to give other users roles up to a certain limit?
Cheers,
Thor
Comment: I get that you can allow them to create, edit or delete content categories (News, basic page, basic node etc). But can you stop them from viewing the content?
Answer: There are a variety of content access modules, so you might want to look around to find one that best suits your specific needs but a good start is often https://drupal.org/project/content_access
As for automatic role delegation, there are a variety of ways you can do so, too. Rules is a great place to start https://drupal.org/project/rules but depending on what your requirements are, you might need to write a custom module. There are also a variety of rules-related modules that expand on it's offerings that might help you out. Rules is very capable for many things but sadly, if you have very specific needs it might be a little more complex than point-and-click.
Comment: Aight thanks a bunch! I would thumbs up if I could :-)

Grant a role access to certain content