Qual a diferença entre aspa simples ' e aspa dupla " no SQL?

Question: Contexto
Quando faço um SQL e desejo por um alias especifico devo por entre aspas duplas ".
SELECT A.ds_nome_pessoa AS "Pessoa.nome" ...

Quando quero fazer um where in de um campo varchar os valores devem estar em aspa simples '.
WHERE A.ds_nome_pessoa IN (
    'Jose',
    'Maria',
    'Joao'
)

Pergunta
Qual a diferença entre aspa simples ' e aspa dupla " no SQL?
Adendo
Se eu fizer um SELECT de SELECT - SUBQUERY - de campos que tem alias em ", o meu SELECT mais externo também deve ter ".
SELECT "Pessoa.nome" FROM
(
SELECT A.ds_nome_pessoa AS "Pessoa.nome" ...
)

Comment: Veja se pode te dá uma ajuda. Mais de qualquer forma grande pergunta.http://stackoverflow.com/questions/1992314/what-is-the-difference-between-single-and-double-quotes-in-sql.
Comment: Pelo menos no postgres um nome de identificar com letras maiusculas precisa de aspas duplas ... :P nesse caso é só dar o alias em caixa baixa.
Comment: Falando do **PHP**, se usa aspas duplas quando no meio da expressão há uma variável, `$var`. Quando não tem usa aspas simples. Se você fizer: `$var = 5; echo '$var';`, não vai mostrar `5` e sim `$var`. Se fizer `echo "$var";` mostrará o valor da variável.
Answer: Em SQL padrão só apóstrofes (aspas simples) são reconhecidos como delimitador de literais strings ou algum outro tipo de dado (acredito que para outros tipos seja específico e não padrão). Fornecedores específicos admitem o uso das aspas duplas para a mesma função, mas isso pode variar, alguns exigem configuração. Exemplos que admitem o uso são MySQL, SQL Server e Oracle.
Alguns bancos de dados usam uma delas ou ambas para criar um alias de coluna, aí não precisa usar o AS. Mas é específico e não padrão. Melhor usar o padrão que é não ambíguo. O padrão determina que o alias seja com aspas duplas, ou sem elas. Todos os principais bancos aceitam o padrão, mesmo que precise configurar isso.
Todos os bancos SQL mainstream usam as aspas (duplas) para delimitar o nome de um identificador (nome de tabela, coluna, alias, etc.), alguns permitem configurar como vai usar. Alguns usam o backtick (crase) para fazer isso. Outros usam os colchetes [] (SQL Server). O delimitador pode ser necessário quando há espaço no identificador ou usa uma palavra reservada. Pode variar de acordo com o fornecedor.
Configuração do MySQL:
SET GLOBAL SQL_MODE=ANSI_QUOTES

Configuração do SQL Server:
SET QUOTED_IDENTIFIER ON

Coloquei no GitHub para referência futura.
Há casos, como o PostgreSQL, em que o uso das aspas duplas faz com que o nome do identificador considere a sensibilidade de caixa, o que não é normal do SQL. É bom ter certeza do que está fazendo e se é isso que deseja. O uso das aspas duplas são necessárias, junto com &U para escrever caracteres Unicode, mas é melhor evitar o seu uso.
Lembre-se que o uso de delimitadores quase nunca são necessários para identificadores. Se a pessoa quiser eles nunca são necessários. Pra mim os delimitadores só deveriam ser usados em literais. E se precisar usar no identificador mesmo, que seja uma exceção extrema.
Tem que consultar a documentação específica de cada fornecedor ou fazer perguntas específicas aqui.
Não encontrei nada em documentação que faça os elementos literais string do operador IN serem escritos de uma forma ou outra, eu conto com a documentação e ela diz que o ANSI deve usar aspas simples.
Opção
Um outro motivo para usar aspas simples no SQL é que é normal a consulta ser montada dentro de outra linguagem por strings que provavelmente estará delimitada pelas duplas, então é melhor evitar confusão. Se a linguagem usada costuma delimitar strings com a simples, então é melhor usar a dupla no SQL.
Escolha uma forma de uso e fique com ela, não fique trocando sem motivos. Só o faça se tiver um bom motivo para fazer exceção. Faça se houver motivos que atrapalhem o SQL do fornecedor que estiver usando ou a linguagem hospedeira da montagem da consulta.
Note que o padrão do SQL são as aspas simples. E o padrão de todas as linguagens mainstream que eu conheço são as aspas duplas, ainda que possa, e alguns prefiram, usar as simples nessas linguagens. Eu particularmente adoto esse padrão porque ele funciona bem em mais de 99% dos casos. O padrão contrário funciona bem em bem menos casos, dependendo do banco de dados, algo até próximo de 99%, mas há casos que praticamente não funciona. Vai que um dia precise adaptar o código para outro banco...
A conclusão é que é melhor só usar aspas duplas onde realmente é absolutamente obrigado. Se eu encontrasse alguma situação onde fosse obrigado - acho que nunca encontrei - eu tentaria achar uma solução diferente. Não sei se todos concordam.


C# console app chess table

Question: I'm trying to create a chess table and output it on the screen also I want to be able to add x's in the table. For example if I want to show that the current position of a figure is on A,2 a x appears there.. I currently have only the table displayed and it's not even contained in array :
    private static readonly string[] letters = { "A", "B", "C", "D", "E", "F", "G", "H" };
    private const int size = 8;
    private static void Main()
    {
        const string top = " -----------------";
        const string line = "| | | | | | | | |";
        for (int i = 0; i < size; i++)
        {
            Console.WriteLine(" {0}", top);
            Console.WriteLine("{0} {1}", size - i, line);
        }
        Console.WriteLine(" {0}", top);
        Console.Write("   ");
        for (int i = 0; i < size; i++)
        {
            Console.Write("{0} ",letters[i]);
        }
        Console.ReadKey();
    }

However I have absolutely no access or control over the table it's just drawn. I want to be able to put the "x" in between the free space here : |x| how can I put this table in some sort of jagged array/2d array or a nested list ?
Answer: Look at my answer here: Tic-tac-toe code help improve
I think this is exactly what you are looking for.
In your case it might be sufficient to use an array of bool, because you only want to store two states (empty or X).
private static readonly string[] letters = { "A", "B", "C", "D", "E", "F", "G", "H" };
    private const int size = 8;

    private static bool[,] chessboard;

    private static void Main()
    {
        const string top = " -----------------";

        //init chessboard
        chessboard = new bool[size, size];

        //place a figure on field 4/6 for demonstration
        chessboard[4, 6] = true;

        for (int y = 0; y < size; y++)
        {
            Console.WriteLine(" {0}", top);
            Console.Write("{0} ", size - y);
            for (int x = 0; x < size; x++)
            {
                Console.Write("|{0}", chessboard[x, y] ? 'X' : ' ');
            }
            Console.WriteLine("|");
        }

        Console.Write("   ");
        for (int i = 0; i < size; i++)
        {
            Console.Write("{0} ", letters[i]);
        }
        Console.ReadKey();
    }

Comment: The reason this is a bad idea for a real game is, that you have far more states then you need. While this doesnt sound bad at all at first, it gets problematic if you have a complicated game logic. Your have to ensure your algorithms can operate on a defined gamestate. With the possibility to add a figure that doesnt exist in the game you create error prone code. But as i said, for your case it is probably fine.
Comment: This doesn't help's me at all can you provide a sample code ?
Comment: I think using char/string is a lot better than bool like shown in the FreshWaterTaffy's answer and simply put the value of the char in there not checking and than putting
Comment: Better really depends on the usecase. I had real games in mind where the data structure is most likely an array of enum or even object. But for your textbased console application i agree. Its also easier to add another symbol. If you know for sure that you will only use X and empty, i would still go with bool though ;)
Comment: The code should always be as flexible as possible for example adding third symbol will break your logic using boolean variable however it will work fine with char/string array..
Answer: create a 2D array of chars : char[x][y] boxes where x is the width of the board and y is the height.
Initialize every char to a white space.
Set desired spot to desired char : boxes[2][2] = 'x'
Make a loop:
for(int y = 0; y < boxes.length; y++)
{
    //print line
    Console.Write("|")
    for(int x = 0; x < boxes[0].length; x++)
    {
        //Show char at that spot
        Console.Write("{0}|", boxes[y][x]);
    }
    //procede to next line
    Console.WriteLine();
}

C# console app chess table


Como comparar variáveis usando JavaScript?

Question: Utilizo muito comparação de variáveis. Exemplo:
 if (item[l].item[0] == 'tipoRescisao') {
                log.info('Tipo Rescisão: ' + item[l].item[1])
                if (
                    (item[l].item[1] == (1))
                        || (item[l].item[1] == 01)
                        || (item[l].item[1] == 08)
                        || (item[l].item[1] == 10)
                        || (item[l].item[1] == 12)
                        || (item[l].item[1] == 13)
                    ) {
                    prazo = dataDesligamento + 24;
                }
            }

Existe uma outra forma de realizar essas comparações de forma mais sucinta?
Comment: O que especificamente quer saber, se dá para comparar a variável com múltiplos valores?
Comment: isso mesmo, quero saber se uma variável está em determinada faixa de valores.
Comment: Tem dois q é o mesmo valor, tem algum motivo para isso?
Comment: Não, pode ignorar
Answer: Acredito que a forma mais fácil seria pesquisando em um array dos valores a serem comparados. Se ele achar no array é porque a variável vale pelo menos um desses valores. Tem gente que até tem alguma função para abstrair isso.
if ([1, 8, 10, 12, 13].indexOf(item[l].item[1]) > -1) {
    prazo = 20;
}

var prazo = 0;
var x = 8;
if ([1, 8, 10, 12, 13].indexOf(x) > -1) prazo = 20;
console.log(prazo);
var prazo = 0;
var x = 7;
if ([1, 8, 10, 12, 13].indexOf(x) > -1) prazo = 20;
console.log(prazo);

Coloquei no GitHub para referência futura.
Comment: hehe pensamos igual, mas eu demorei 2min  a mais :D
Answer: Você pode fazer esse tipo de verificação mais simples usando indexOf.
primeiramente crie um array como todas as possibilidades que deseja.
['1', '01', '08', '10', '12', '13']

Após basta verificar se o valor que busca esta dentro deste array através no indexOf
['1', '01', '08', '10', '12', '13'].indexOf(item[l].item[1])

Se o resultado encontrado for -1 então o valor não existe no array de pesquisa.
Assim seu if ficaria :

// Função simples
function inArray(value, array){
  return array.indexOf(value) != -1;
}

console.log(inArray('01', ['01', '10']));

// Aplicada ao prototype de string
String.prototype.inArray = function(array){
  return inArray(this.toString(), array);
}

console.log('01'.inArray(['01', '10']));
Comment: Consegue me ajudar na criação de uma função, já que utilizo muito essas comparações?
Comment: @durtto seja agora, se facilita um pouco.
Comment: +1 Se o resultado encontrado for -1 então o valor não existe no array de pesquisa
Answer: Terá que verificar qual o tipo do valor item[l].item[1].
Type string:
se for "01", terá que fazer desta forma
if(valor item[l].item[1] === "01")...

Type Int:
se for 1, terá que fazer desta forma
if(valor item[l].item[1] === 1)...

Comment: Sua resposta não me ajuda, não responde a pergunta.


Prestashop 1.7 Overriding default presta module source files

Question: Is it possible to override module source files? for example:
modules/ps_facetedsearch/src/Ps_FacetedsearchFiltersConverter.php
There is no problem to override module file but all the src files are being loaded from original path.
Answer: Have you try to create file into override/modules/ps_facetedsearch/src/Ps_FacetedsearchFiltersConverter.php and delete class_index.php into var/cache ?


Logic Question (predicate logic)

Question: Consider the formula
F =∀x∃y∃z (¬(x=y)∧¬P(x,y)∧¬(x=z)∧P(x,z))
Let n ≥ 3 be a natural number. Find a universe U with n elements (i.e., |U | = n) and
a predicate P : $U^{2}$ → {0,1} such that F is true. The Universe and the predicate P have to be defined in terms of n, but how would a universe and a predicate look like that satisfy the above formula?
Comment: Hint: think about modular arithmetic (though I'm sure there are other solutions).
Comment: My first thought is to see how you could make this work for n=3 .... and then maybe n=4 if that doesn;t suggest some general pattern yet ... but I bet that just by looking at n=3 you already get a good idea for a pattern, and so then generalize it, and prove that it indeed always works for any n >= 3
Answer: I would consider first with the set of integers from $0$ to $n-1$. Then to get a $P$, we can start by using the subtraction, modulo $n$. We then just need to assign to the result of the subtraction the $0$ or $1$ values. There are many ways to do that. Here are two examples:

$$P=\begin{cases}1,(x-y)\mod n=1\\0,(x-y) \mod n\ne 1\end{cases}$$
$$P=\begin{cases}1,(x-y)\mod n=2k, k\in\mathbb N\\0,(x-y) \mod n=2k+ 1, k\in\mathbb N\end{cases}$$

In these examples, the subtraction modulo $n$ takes all values from $0$ to $n-1$. In your case $n\ge 3$ means that you have at least $0,1,2$ as possible values. You get $0$ in the subtraction when $x=y$. But you get at least two different values for any $x$, one for $(x-y)\mod n=1$, one for $2$. So you just need to assign them different truth values in defining the predicate $P$.

Logic Question (predicate logic)


When i click the menu in drop down, How can i be able to pass value and hit second api?

Question: export default App;

How do i pass value to second api

import React, { useState } from "react";
import axios from "axios";

let App = () => {
  let [value, setValue] = useState('');
  let [locations, setLocations] = useState([]);

  let handleSubmit = async () => {
    if (value === "") return;

    let response = await axios.get(`https://api2-4ofagodxfq-uc.a.run.app/locality?stateName=KARNATAKA&districtName=BANGALORE&pinCode=${value}`);
    if (response.status === 200) setLocations(response.data);
  }
  let handleChange = async () => {
    if (value === "") return;

    let response1 = await axios.get(`https://api2-4ofagodxfq-uc.a.run.app/branch?stateName=KARNATAKA&districtName=BANGALORE&pinCode=560001&officeName=${value}`);
    if (response1.status === 200) setLocations(response1.data);
  }

  return

    STATE:<select value="KARNATAKA">
      <option value="KARNATAKA">KARNATAKA</option>
    </select>

    CITY:<select value="BANGALORE">
      <option value="BANGALORE">BANGALORE</option>
    </select>

    PINCODE:<input type="text" onChange={e => setValue(e.target.value)} onKeyPress={(handleSubmit)} />

    <select onChange={e => setValue(e.target.value1)} >
      {locations.map((location, index) => {
        return <option key={index}>{location}</option>
      })}
    </select>
    <input type="submit" onClick={(handleChange)}></input>
    {locations.map((location, index) => {
      return
{location}

    })}

}

export default App;

That too in the same page
Answer: you need to wrap all form fields in <form /> call handleSubmit() on submit
something like  this
<form submit={() => handleSubmit()}>
STATE:<select value="KARNATAKA">
      <option value="KARNATAKA">KARNATAKA</option>
    </select>

    CITY:<select value="BANGALORE">
      <option value="BANGALORE">BANGALORE</option>
    </select>

    PINCODE:<input type="text" onChange={e => setValue(e.target.value)} onKeyPress={(handleSubmit)} />

    <select onChange={e => setValue(e.target.value1)} >
      {locations.map((location, index) => {
        return <option key={index}>{location}</option>
      })}
    </select>
    <input type="submit" onClick={(handleChange)}></input>
    {locations.map((location, index) => {
      return
{location}

    })}
</>

Comment: But it will not hit second api
Comment: it should, did you try it? do u have it in codesandbox ?
Comment: yes I tried. It will hit the first api and repeats the result in


Is every key the same thing?

Question: Have you noticed that sometimes you can recognize a song just by listening to about 3-4 notes?
We can transpose those 3-4 notes to a different key, and I bet you would still recognize it. Even if I played them with a different instrument you would still recognize it!
Just so long as those notes are played in the right rhythm, it is recognizable.
Isn't this because there are 7 notes in a key The 1st, 2nd, 3rd, 4th, 5th, 6th 7th (8th), and those 7 notes are proportional to some different key... if you get what I'm trying to say.
Wouldn't this mean that every key is the same thing? That every song ever made is just a different arrangement of the 1st, 2nd, 3rd, 4th, 5th, 6th 7th (8th) (excluding jazz)
That is amazing, and it means that music has more to do with rhythm than notes.
Every key is the just the first, second, third, ect, in a higher/lower proportional tone? So this means all keys are "the same"?
Comment: I think there are 12 notes in a key, and the arrangement of them changes color of sound. Rhythm is very important and often overlooked, because it is the other half of playing. For song recognition that is just because we humans tend to pick up on melody quite quick. The melody of a tune sticks and understanding melody in song creation is quite powerful.
Comment: The Well-Tempered Clavier by some minor baroque composer might well be worth researching (and listening to).
Comment: The rhythm does not need to be identical, variations on a theme probably all have different rhythms but you can still recognise the melody it was built on
Comment: @NeilMeyer - funnily enough, it's something I do to show students how important the rhythmic pattern of a song is. I play all the right notes, in the right order, but change the note values,and chances are they *don't* recognise what the tune is - because, simply, it's *not* the same tune as original...
Comment: Also check out the Parsons code classification of melodies according to their contour. Starting with the first note, each successive note of the melody is either a Repeat of the previous note, or goes Up or Down.  http://www.musipedia.org/pc.0.html?&L=0
Answer: Welcome to the world of 12 EDO, where all the notes have been subtly moved by just a little, to make any tune sound just as good in any key. A couple of hundred years ago, an instrument could be tuned to sound good in one key. But try to play a piece in a different key, and it would sound slightly out of tune.
That's when it was realised that by moving the pitches very slightly, the same tune would sound pretty good when transposed to any of the 12 keys. It's called equal temperament.
Comment: That's so fascinating. Where can I find out more about this?
Comment: @emero - this is a good start (it's a big subject): https://en.wikipedia.org/wiki/Musical_temperament
Answer: You are essentially correct, in that a song or melody played in a certain key can be transposed to any other any other key - that is, can be played starting on any note and still be recognizable - but here's the nub. When we talk about the key of a piece - for example, A major - we are talking about a collection of 7 notes (In this case, A,B,C#,D,E,F#,G#, or Do, re, mi, fa, sol, la, ti). If you start in a different key - say, C Major - you would have a scale made of different tones (C,D,E,F,G,A,B); HOWEVER, they still occupy the same place in the key (Do, re, mi, etc.), and so it's easy (when you know your scales!) to transpose keys on the fly.
But in the western musical tradition, tempered instruments have 12 distinct tones! A major scale, like many common used scales, is merely a collection of tones. Most scales - for example, the major and minor scales - use 7 distinct notes just like the major scale. And while you might start a scale on the same note - in this case, A - the specific pattern of notes you pick determines the key. A major, as we have seen, is comprised of a whole step, another whole step, a half step, three whole steps, and a half step (the last half step is between G#, or ti,  and A at the top, or Do):
A | A# | B | C | C# | D | D# | E | F | F# | G | G# | A
Do..........re..........mi....fa...........sol.........la.............ti....do
Alternatively, a minor scale has the pattern, whole, half, whole, whole, half, whole, whole:
A | A# | B | C | C# | D | D# | E | F | F# | G | G# | A
Do.........re....me..........fa..........sol....le...........te............do
Either of these scales can be transposed to different keys, and although the specific collection will change, the pattern of steps, and therefore the solfege (do, re, mi etc.) will not change. These patterns are called modes; the most common are major and minor. Although a scale or melody may start on the same note, it is not necessarily in the same key. Thus, the key is determined by two factors: the starting note (1st and 8th, or Do), which we call the tonic, and the mode, which have different names.
So what are the different modes? First think of a C major scale - no sharps or flats, all the white keys on a piano - C,D,E,F,G,A,B,(C). If we play the notes in this order starting on C it sounds like C major - we call this the Ionian, or major, mode. But what if we played the same collection of notes, but starting on a different note - like A for example? We get the Aeolian, or minor, scale. Starting on different notes will yield more exotic scales. (https://en.wikibooks.org/wiki/Music_Theory/Modes)
If you're interested in understand more about the nature of the scales, and music theory in general, i recommend studying the Circle of Fifths (for reading keys/music) as well as learning solfege, which helps immensely with audiating, the process of accurately expressing what you hear in your head. Once you can hear it, you can sing it, and if you can sing it, you can play it, and if you can play it, you can retire to a cottage in Florida at the age of sixty three for some quality time with the local beach bunnies.
Comment: You mean **tonic sol-fa** to be moveable doh. **Solfege** is fixed doh - always **C** and used certainly in France and other continental countries.
Comment: And actually, trying to audiate in solfege is damned difficult compared with tonic sol-fa. I play with French musicians and they find it really easy, though.
Comment: I was indeed referring to movable do; in the U.S. (and by extension American English) this is generally what is meant by solfege, although I admit I should be a bit more careful making assumptions about my audience!From the wiki page: There are two current schools of applying solfège: 1) fixed do, where the syllables are always tied to specific pitches (e.g. "do" is always "C-natural") and 2) movable do, where the syllables are assigned to scale degrees ("do" is always the first degree of the major scale).
Comment: It's an interesting read about the two - similarities/differences/history. In my 'Oxford Companion to Music': two paragraphs are dedicated to 'solfege', while seven pages explain 'tonic sol-fa'. It would be interesting to try to explain one to someone who is used to the other! I've tried and bewilderment is the usual result.    Also - have a read of your second para., one sentence is odd.
Answer: It's not the notes which are used that matter. Rather, it's the intervals between the notes that help distinguish and identify a melody.
So instead of thinking of a melody as a series of notes; think of it as a series of intervals. This way it doesn't matter which note you start on. If the intervals are identical then the melody will be recognizable regardless of the key you're playing in.

Is every key the same thing?


Reproducing SQL Exception and correct handling in layer architecture

Question: Lets say I have this:
String sql = "DELETE FROM "+ TABLE_NAME +"  WHERE id=?";

try {
    int ra = jdbcTemplate.update(connection -> {
                PreparedStatement stmt = connection.prepareStatement(sql);
                stmt.setLong(1, id);
                stmt.executeUpdate();
                return stmt;
            });

    if (ra == 0)
        throw new SQLException(SQL_ERROR);
} catch (SQLException e){
    LOGGER.error(SQL_ERROR);
    throw new DataAccessLayerException("Entity could not be deleted due to SQL Exception");
}

I am deleting a entity from table with key(id). Now I want to be able to report INTERNAL_SERVER_ERROR to client without causing a RuntimeException.
However, I can't reproduce SQLException. If I for example delete a letter in my sql statement I only get a Syntax error that is thrown as Runtime error and it seems like I am not catching it.
Help me understand what is exactly meant here with SQLException and how do I reproduce it and report this to client without causing RuntimeException?
Answer: Your code is wrong. You're calling update(PreparedStatementCreator psc), and as the name suggests, your code should create a fully "prepared" statement object, but it should not "execute" that statement, so remove the executeUpdate() call.
The update() call throws a DataAccessException, not a SQLException, so the only source of SQLException inside that try block is your if statement, so you might as well just throw that DataAccessLayerException exception directly. I would recommend throwing a EmptyResultDataAccessException instead, though.
Since Spring specifically converts the checked SQLException into unchecked DataAccessException runtime exception, you will always get runtime exceptions when using Spring JDBC, and that is a good thing, because you now won't need to add checked exceptions to all the methods in your code.
An unhandled exception is handled by Spring MVC. By default, Spring MVC will redirect to an error page. If you don't want that, see e.g. question Spring Boot Remove Whitelabel Error Page.


Erro de lógica ao remover itens repetidos de uma lista

Question: Estou fazendo um exercício onde devo criar uma função que remove itens repetidos de uma lista e retorna essa lista ordenada.
Meu código remove apenas alguns itens repetidos, mas deixa outros. Eu sei que existem outras soluções sem o uso do del, mas estou curioso sobre o que estou errando aqui, também aceito dicas que não envolvam a solução pro exercício.
Segue o código:
def remove_repetidos(lista):

    for itens in lista:
        if lista.count(itens) == 1:
            continue
        lista.remove(itens)

    return sorted(lista)

Caso eu coloque [7,3,33,12,3,3,3,7,12,100] como parâmetro ela devolve [3, 3, 3, 7, 12, 33, 100].
Answer: O problema é que o seu código modifica a lista dentro do for in. Você pode ver isso colocando um print dentro do loop.
>>> lista = [7,3,33,12,3,3,3,7,12,100]
>>> for itens in lista:
...     print(itens)
...     if lista.count(itens) == 1:
...         continue
...     lista.remove(itens)
...
7
33
12
3
7
12
100

Em teoria deveríamos ver todos os itens no console, mas não é o que acontece.
Ao invés de usar a mesma lista, você pode criar uma nova:
>>> lista = [7,3,33,12,3,3,3,7,12,100]
>>> nova_lista = []
>>> for item in lista:
...     if not item in nova_lista:
...         nova_lista.append(item)
...
>>> nova_lista
[7, 3, 33, 12, 100]

Ou simplesmente usar o set do Python:
>>> sorted(set([7,3,33,12,3,3,3,7,12,100]))
[3, 7, 12, 33, 100]


node.js asynchronous passing variable between functions

Question: i am taking my first steps with node.js and i came across this issue with passing variable in asynchronous way. I have this piece of code im using to create Facebook user:
req.tmpPassport = {};
var fb = new fbgraph.Facebook(accessToken, 'v2.2');
function initUser() {
    fb.me(function (err, me) {
        req.tmpPassport.me = me;
        console.log(req.tmpPassport.me) // works
    });
}

console.log(req.tmpPassport.me) // not working -> undefined var

i tried to figure out why the second log isn't working and i ended up reading about synchronous and asynchronous functions, so in attempt to implement what i read i tried coming up with a solution using callbacks, but no success.
my last attempt was this:
req.tmpPassport = {};
var fb = new fbgraph.Facebook(accessToken, 'v2.2');
function initUser() {
    fb.me(function (err, me) {
        req.tmpPassport.me = me;
    });
    fb.my.events(function (err, events) {
        //console.log(events);
        req.tmpPassport.events = events;

    });
    fb.my.friends(function (err, result) {
        req.tmpPassport.results = result;
    });
}
function passUser(){
    console.log(req.tmpPassport);
    return req.tmpPassport;
}
cp.exec(initUser, passUser);

but its not working...
what i am actually trying to achieve its to render this object with my express router var which looks like this:
   router.get('/welcome', securePages, function(req, res, next){
        res.render('welcome', {title:'Welcome to aDating', user:req.tmpPassport});
    })

but i cant figure out how to pass this object only after created...any help please?
Answer: A method of chaining function calls when certain async tasks are done is one way to deal with this.
Looking at the first snippet of code, it would be rewritten as follows:
req.tmpPassport = {};
var fb = new fbgraph.Facebook(accessToken, 'v2.2');
function initUser() {
    fb.me(function (err, me) {
        console.log(req.tmpPassport.me) // works
        req.tmpPassport.me = me;

        // triggers execution of the next step
        post_populating_passport();
    });
}

function post_populating_passport() {
    // this function is only executed after the callback from the async call
    console.log(req.tmpPassport.me);
}

Answer: Node.js is an asynchronous programming language, a fundamental concept in its core. You either need to use function callbacks (not a good practice) or available npms utilities for async flow.


Derivation of the Compound Interest Formula Without Using Calculus

Question: I am a student but I am only in Algebra 2. I am doing a project on compound interest and I am trying to prove how we arrive at the formula $y=Pe^{rt}$ but I am stuck at the step where you get from $y=P(1+r/n)^{nt}$ to $y=P((1+1/n)^{n/r})^{rt}$. I would really appreciate some help with my algebra. Thanks!
Comment: Could you format this with [mathjax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)?
Comment: I don't know how to use that, sorry. But it looks like someone else formatted it.
Comment: Are you sure it's $P((1+1/n)^{n/r})^{rt}$ and not  $P((1+r/n)^{n/r})^{rt}$ or $P((1+\frac{1}{\frac{n}{r}})^{n/r})^{rt}$ ?
Answer: Generally, $y=P(1+r/n)^{nt}$ does not imply $y=P((1+1/n)^{n/r})^{rt}$ (Try $P=1, n=2,  r=2, t=2$. It fails, since $P(1+r/n)^{nt}=1(1+\frac{2}{2})^{2 \cdot 2}=16 \neq P((1+1/n)^{n/r})^{rt}=1((1+\frac{1}{2})^{2/2})^{2\cdot 2}=\frac{81}{16})$.
It looks like something may have been mistyped here.
However, it is true that $$y=P(1+r/n)^{nt}=P((1+r/n)^{n/r})^{rt}.$$
There is a rule for exponentiation that states $(a^b)^c=a^{bc}$. Assuming that $r$ is nonzero, we can write $$y=P(1+r/n)^{nt}=P(1+r/n)^{\frac{n}{r}\cdot (rt)}=P((1+r/n)^{\frac{n}{r}})^{\cdot rt}.$$
Comment: Thank you so much, this is what I needed.
Comment: And yes, I did mistype it. Sorry.
Comment: @GabeJ Yikes, I mistyped too! See the edited post for a correct version (I don't know what I was thinking when I typed this up before...)


SQLSTATE[42S22]: Column not found: 1054 Unknown column 'session_id' in 'field list'

Question: How can I solve this kind of error, after transferring my Magento files and SQL to new hosting:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'session_id' in 'field list'

Please see this link for the error: http://prntscr.com/3yj69u
Answer: Ambhen, This is issue log_visitor table check the table structure.
Goto this check this table have  session_id columns in table
If it is exting then you need to create log_visitor table again
CREATE TABLE IF NOT EXISTS `log_visitor` (
  `visitor_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Visitor ID',
  `session_id` varchar(64) NOT NULL COMMENT 'Session ID',
  `first_visit_at` timestamp NULL DEFAULT NULL COMMENT 'First Visit Time',
  `last_visit_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Last Visit Time',
  `last_url_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT 'Last URL ID',
  `store_id` smallint(5) unsigned NOT NULL COMMENT 'Store ID',
  PRIMARY KEY (`visitor_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='Log Visitors Table' AUTO_INCREMENT=1 ;

for second issue:
CREATE TABLE IF NOT EXISTS `report_viewed_product_index` (
  `index_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Index Id',
  `visitor_id` int(10) unsigned DEFAULT NULL COMMENT 'Visitor Id',
  `customer_id` int(10) unsigned DEFAULT NULL COMMENT 'Customer Id',
  `product_id` int(10) unsigned NOT NULL COMMENT 'Product Id',
  `store_id` smallint(5) unsigned DEFAULT NULL COMMENT 'Store Id',
  `added_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Added At',
  PRIMARY KEY (`index_id`),
  UNIQUE KEY `UNQ_REPORT_VIEWED_PRODUCT_INDEX_VISITOR_ID_PRODUCT_ID` (`visitor_id`,`product_id`),
  UNIQUE KEY `UNQ_REPORT_VIEWED_PRODUCT_INDEX_CUSTOMER_ID_PRODUCT_ID` (`customer_id`,`product_id`),
  KEY `IDX_REPORT_VIEWED_PRODUCT_INDEX_STORE_ID` (`store_id`),
  KEY `IDX_REPORT_VIEWED_PRODUCT_INDEX_ADDED_AT` (`added_at`),
  KEY `IDX_REPORT_VIEWED_PRODUCT_INDEX_PRODUCT_ID` (`product_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='Reports Viewed Product Index Table' AUTO_INCREMENT=1;

I hope ther are lot issue in database  ..... you  need fresh install database
Comment: Hi Amit,

I got this error

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'rmmagsde_database.report_viewed_product_index' doesn't exist

This is the screenshot1: http://prntscr.com/3ykmg2

And when I got login I see this error also.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'rmmagsde_database.sales_flat_order' doesn't exist

This is the screenshot2: http://prntscr.com/3ykmug
Comment: Hi @Amit,

After creating the second issue i got another problem:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'rmmagsde_database.report_compared_product_index' doesn't exist

whole screenshot: http://prntscr.com/3ykq8i
Comment: Please help! Anybody?
Comment: Hi @Amit,

It fixed the error! Thank you for your help!

Best Regards,
Ambhen
Comment: @Amit please check here : http://stackoverflow.com/questions/34606694/sqlstate42s22-column-not-found-1054-unknown-column-main-table-age-in-fiel
Comment: Hey,too busy for 3-4 day. i cannot reply u .sorry for that


Need help getting images to stack inside a div

Question: I'm trying to get a series of images to stack one on top of each other inside a div and I need some help. The div is set up in CSS to be 450px wide and the top picture is always that width. The images that follow will vary in size and need to flush right with 36px of padding on the right side.
Currently my code looks like this:

Unfortunately the bottom two photos want to sit next to each other. Even if I put a break after the second picture, they remain in the same place.
I tried setting the div to display: block, but there was no change.
Comment: When you say "stack one on top of the other", do you mean literally overlaying each other, or each following the last in a column?
Comment: Could you provide a picture of how you want them to stack?
Answer: If you want them to stack, use inline-block
http://jsfiddle.net/jax29/
css
#photos{
width:450px;
}

#photos img{
display:inline-block;
}

#photos img:nth-child(n+2){
margin-right:36px;
float:right;
}

html

Comment: I'll upvote for the artwork alone... ok, I guess also because it works, but that is secondary.
Answer: I may be misunderstanding what you want, but if you want the images stacked vertically and never horizontally, you could set text-align: right; on the parent div rather than using float: right to align the images.
If you want to use float: right; try adding clear: both; on each image. That way, they won't want to jump up next to the previous image. using float tells subsequent elements to display next to the floated element.
Comment: Thanks Nick, that solves most of the issues. The `float: right;` seems to have been the culprit. There will be instances where I do want two images that will fit on a single row to do so flushed to the top of the largest image. I'm trying to do that now but the smaller image is flushing to the bottom of the larger one. Any idea why?
Comment: Can you tell me how you are getting the two images to display next to each other? It could have to do with your method.
Comment: here is a [link](http://jsfiddle.net/CpN2X/) to an example of how one might achieve what I think you are talking about.
Answer: This should fit your requirements.

#photos {
    width: 450px;
    text-align: right;
}


Chi-square, effect size and unbalanced groups

Question: For context: I should note in advance I am a relative beginner with this.
Data context
I have data on some 600 000 persons which includes a column of whether these persons took parental leave or not (coded simply as 1 - took parental leave, 0, took no parental leave). I also have a column coding each person as male or female. I want to know whether persons coded as female are more likely to take parental leave than persons coded as male.
So I made a 2x2 table (female/male; no parental leave/parental leave) and applied the chi-square test which is significant (as expected). The residuals + prop table show that indeed women are overrepresented in taking 'parental leave'. So far so good.
Problem statement
However, the effect size is relatively small (Cramer's V about 0,15). For a number of reasons this seems counterintituive - the difference between men and women in the 'parental leave = 1' group seems quite large. I googled/read a bit about effect size & unbalanced groups. In this case there is a large dataset, with a relatively small proportion of the 600 000 persons taking parental leave. Could this affect the effect size, if yes, is there any measure other than Cramer's V that should be used in this regard?
Note: I am not specifically looking for a large effect size, just wondering whether I am applying the right measure.
Own research I have read the post: Chi-square Test with High Sample Size and Unbalanced Data but it didn't quite answer my question (the issue seems similar though).
Comment: Everything in this question is based on your perception that "the difference between men and women ... seems quite large."  Please tell us what that difference is and why it seems large to you.
Comment: Apologies for not responding sooner - I didn't see that I got comments. I think the difference is quite large as, relative the proportion of men/women in the overall population, women are about twice as likely to take up parental leave. I suppose I am wondering how the odds ratio stacks up to the effect size...
Comment: It sounds like you are describing the most useful effect size for your situation: "relative
 to the proportion of men/women in the overall population, women are about twice as likely to take up parental leave".  If I understand what you are saying, this is the odds ratio.  As an example of a 2 x 2 table with Cramer V = 0.15, and OR = 2, the following is code in R : `Matrix = matrix(c(550, 1100, 250, 1000), nrow=2, byrow=TRUE); library(vcd); assocstats(Matrix); oddsratio(Matrix, log=FALSE)`
Comment: Thanks for the response; I will just stick with the odds ratio then!
Comment: As an alternative, odds ratio is easy to calculate for a 2 x 2 table and is easy to understand.  But Cramer's *V* (or *phi* for the 2 x 2 case) is appropriate as well.  Or as mentioned in an answer in the post you cited, simply looking at the proportions of observation in each cell in rows or columns.
Answer: Answer from comment thread:
It sounds like you are describing the most useful effect size for your situation:

relative to the proportion of men/women in the overall population,
women are about twice as likely to take up parental leave.

If I understand what you are saying, this is the odds ratio.
For future readers, as an example of a 2 x 2 table with Cramer V = 0.15, and OR = 2, the following is code in R:
<code>Matrix = matrix(c(550, 1100, 250, 1000), nrow=2, byrow=TRUE)

library(vcd)

assocstats(Matrix)

oddsratio(Matrix, log=FALSE)

   ###                     X^2 df   P(> X^2)
   ### Likelihood Ratio 64.712  1 8.8818e-16
   ### Pearson          63.294  1 1.7764e-15
   ###
   ### Phi-Coefficient   : 0.148
   ### Contingency Coeff.: 0.146
   ### Cramer's V        : 0.148
   ###
   ### odds ratio
   ###
   ### 2

OR = (550 / 1100) / (250 / 1000)

names(OR) = "Odds ratio"

OR

   ### Odds ratio
   ###          2
</code>


Prove a randomly created message has probability less than $2^{-1023}$ of sharing a factor with n

Question: Prove a randomly created message has probability less than $2^{-1023}$ of sharing a factor with n, where $n=pq$ is a product of 2 primes with 1024 binary digits. We can assume the likelihood of a message falling into each residue class is equally likely.
I first have started by proving that that the probability of an integer being relatively prime to n is $\frac{(p-1)(q-1)}{pq}$. Then, I can use this to prove that the probability of an integer not being relatively prime to n is $1-\frac{(p-1)(q-1)}{pq}=\frac1p+\frac1q-\frac1{pq}$. However, I'm not exactly sure where to go from here. If I can find p and q, or at least bounds for p and q, I belive I can figure out the inequality, but the fact that n has so many digits is where I'm stuck.
Answer: If $p$ has $1024$ binary digits, it is greater than $2^{1023}$ and the same for $q$.  That gets a probability less than $2^{-1022}$.  I don't know where to get the last factor $2$.
Comment: Yeah I'm getting that the probability is less than $2^{-1022}-2^{-2046}$, so not necessarily strictly less than $2^{-1023}$


box plot in R: Do the outliers count when the quantiles are being determined?

Question: I have a 1 dimensional dataset and I use the boxplot function to make a box plot. Then I can see that I have some outliers.
Do the outliers count when the quantiles are being determined?
Is there a right/wrong way or are both ways correct as long as we are clear about which method has been used? If so, how does R do it?
Comment: It's partly a question of English usage, but boxplot programs don't determine outliers. At most, they plot separately points that should be thought about and might be (univariate) outliers.
Comment: For a large sample from a exponential distribution about $4.8\%$ of the sample might appear beyond the upper whisker.  If you were to exclude these, you could get substantially wrong quantiles
Answer: R -- like many, but not all programs -- mostly uses Tukey's definition* of how to draw a boxplot.
The entire original sample is used to calculate the hinges (where the box-ends are drawn).
Hinges are very similar to the quartiles (you could say they're a particular way to calculate the upper and lower quartiles that differs slightly from the more usual definitions of quartiles -- though there are a number of different definitions of sample quartiles as well; indeed R offers nine distinct quartile calculations, not counting hinges themselves).
The upper hinge is at the median of the upper half of the data (the upper half includes the median of the original sample if it was a data point) and the lower hinge is at the median of the lower half (which also includes the median of the original sample if it was at a data point):
$\qquad$
So for example with 6 observations the hinges are the second largest and the 5th largest observation (3 points in each half). With 9 observations the hinges are the 3rd and the 8th largest (5 points in each half, the median coming in both halves). With 11 observations the lower hinge is halfway between the 3rd and 4th largest observation and the upper hinge is halfway between the 8th and 9th largest observation (6 points in each half). The illustration shows the case with 13 observations.
Note that quartiles (/hinges) are not at all sensitive to the values of the outliers, only to the fact that they are outside the quartiles. You can move them all close to the box ends (so that there are no outliers) without changing the quartiles/hinges, or as far away as you like (so they're all far away), again without changing the values of the quartiles. So there'd really be no need to do anything when there's an "outlier".

* Or rather, one of them; Tukey gave several definitions, though for present purposes we need only worry about how the calculation of the hinges works; I say mostly because the version with "outliers" would be what Tukey called a schematic plot but they don't do the one with two distinct kinds of "outlier" marks.
Comment: Is the definition for *hinges* in this context the same as Tukey's description of using *fourth-spread*?  When reading *Understanding Robust and Exploratory Data Analysis* he states, "Some readers may be familiar with the *interquartile range*, which is very close to the fourth-spread because quartiles are nearly the same as fourths."  I did not see in that book where he ever explained the difference between the two.
Comment: @Tavrock  *fourths* have the same definition as *hinges*. Both terms are inventions of Tukey's. So "hinge-spread" is the same as "fourth spread".


Reverse vector items but not the first one? C++

Question: I have a vector
std::vector<std::string> letters; // {{A, B, C,}, {A}, {B, C, D, E}}

I want to reverse the order but NOT the first letter for each vector. How do I do this?
So it would be
{{A, C, B}, {A}, {B, E, D, C}}

I tried to do:
std::reverse(letters.begin(), letters.end());
for (int i=0;i<letters.size();i++)
  cout << letters[i];

but it crashes on me
Comment: add a test condition on the number_of_elements before entering the For-loop....
Comment: 1. your loop does not "reverse letters", it prints strings starting from the second one, 2. `cout << it` is not valid without dereferencing `it`,
Comment: Why would it crash on a vector with on element? v.begin()+1==v.end() in this case. It should probably crash on an empty vector.
Answer: You could do it like the example below:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

int main() {
  std::vector<std::string> letters {"ABC", "A", "BCDE", ""};
  std::for_each(letters.begin(), letters.end(), [](std::string &str) { if(!str.empty()) std::reverse(str.begin() + 1, str.end()); });
  for(auto i : letters) std::cout << i << std::endl;
}

LIVE DEMO
What are you doing wrong in your code:
std::reverse(letters.begin(), letters.end()); applies to your initial vector (i.e., it reverses the order of the strings in letters, it doesn't reverse the strings of the vector).
Comment: @40two That's wrong.  `std::string` may appear null terminated in a few specific contexts, but that trailing null is not part of the string.  An empty string is still empty, `s.begin() == s.end()` on it, and `s.begin() + 1` is still undefined behavior on it.
Comment: Nice solution, however I think you need to check if the string is empty before calling `std::reverse`.
Comment: @SebastianK after C++11 `std::string` is null terminated. Thus, never empty. ;)
Comment: So this is valid in C++11, but not in C++98? Interesting :)
Comment: @SebastianK Yes, but solution posted uses lambdas. So applies for C++11.
Comment: When compiling this with `-D_GLIBCXX_DEBUG`, I get an error: `/usr/include/c++/4.8/bits/stl_algo.h:1447:error: function requires a valid iterator range [__first, __last).`. `str.end()` points at the null-terminator, not after it, so when the string is empty, `str.begin() == str.end()` and the range [`str.begin() + 1`, `str.end()`) is indeed invalid.
Comment: @JamesKanze Thnx, `@MagnusHoff` already point that out :) and corrected the code. Apparently I wasn't aware of that and stupidly I assumed that null character is part of the string ;). P.S that's the main benefit from SO actually exchange of knowledge.
Answer: To reverse the vector in-place, you can use std::reverse:
std::reverse(letters.begin() + 1, letters.end());

To reverse them on output, leaving the vector intact, you could iterate over the vector in a reverse direction using vector::rbegin() and vector::rend()


Converting StringDate to a queryable representation. Group and project sum of today,yesterday, week, month

Question: I was about to try to figure out how to complete the given question.
It might consists of 2 parts, first one being - my collection dates are stored in plain string with a mysql format (YYYY-mm-dd HH:mm:ss), the second how to project the (today, yesterday, 7 day, month - summaries).
I have been experimenting around and this is what I came up with.
Pipe 1.
$match - nothing fancy there just a simple field = value.
Pipe 2.
$addField - trying to process the string date as a ISO date I believe? I am not sure
{
  expired: {
    $dateFromString: {
            dateString: '$expired',
            timezone: 'America/New_York'
    }
  }
}

Pipe 3.
$match - Quoted out wanted to select only a specific range so not more than 30 days - doesn't work
 expired: {
                $gt: ISODate(new Date(new Date(ISODate().getTime() - 1000*60*60*24*30)))
            }

Pipe 4.
$group - Here I group and sum everything per day. So an output is

_id: 2021-09-27, theVal : 100

{
  _id: {
    $dateToString: {
      date: { $toDate: "$expired" },
      format: "%Y-%m-%d" }
  },
  theVal : {$sum:{$first:"$values.quantity"}} // as $values is an array [0].quantity,[1].quantity,[2].quantity - I am just interested in the first element.
}

Pipe 5.
$project - getting rid of the _id field - making it date name field, keeping theVal.
{
  "date": "$_id",
  "theVal": 1,
  "_id": 0
}

theVal is a sum of integers within a day.
Questions

Between Pipe 1 and 2 ( temporary 3 ) I should be able to match dates
within the last 30 days to reduce the processing?

How to get a desired output like this:
 {
     today : 100,
     yesterday : 10,
     7days : 220,
     month: 1000,
 }

Really appreciate any help here.
Answer: Tried to "replicate" what you intend to do as you didn't provided sample test data.
You may want to do the followings in an aggregation pipeline:

$match : filter out the ids you want - same as your pipe 1
$dateFromString: use "format": "%Y-%m-%d %H:%M:%S", "timezone": "America/New_York"
$match : filter out records that are within 30 days with $expr and $$NOW
$group : group by date without time; achieved by converting to dateString with date part only
$addFields : project flags that determine if the record are within today, ``yesterday, 7days, month`
$group : As you didn't provided what is the meaning of today, ``yesterday, 7days, month, I made an assumption that they are the cumulative sum in the ranges. Simply and conditional $sum` will do the summation with the help of flags in step 5

Here is a Mongo playground for your reference.


Normality of a sample mean

Question: I am trying to show that my sample mean is approximately normalized. But, when I perform a shapiro wilk normality test, I obtain a p-value of 0.0002589. So, my sample mean doesn't tend to follow a normalized distribution.
It make a non sense for me because I made two plots which prove my sample mean is normalized.

Someone could explain to me why I obtain a p value which doesn't fit with the two graphics please ?
Comment: I asked a question long time on repeated measures long time ago that included uing Sahpiro-Wilk test, and @Glen_b responded in comments on this test. Have a look at this: [question](https://stats.stackexchange.com/questions/181563/analyzing-repeated-measures-experiment-with-multiple-treatment-groups-and-multip)
Comment: Please explain how you produced these plots: what exactly do they purport to show?  When you do, would you mind also explaining why you think the sample mean ought to be Normal?  What is the basis for that?
Comment: Aslo, are you familiar with how to interpret q-q plots? What do you think about this plot that posted?
Answer: I'm not sure I'm going to answer your specific problem exactly, but most often the issue with normality testing is the following.
The Shapiro-Wilk test does not test if your distribution is approximatively normal, but if the distribution is exactly normal.
It says no when the data contains enough information to say that the distribution is not normal. When there is enough information (a lot of data), it will always say "no" unless the distribution is exactly normal, which only happens in rare cases where an underlying "physical" process ensures the distribution is exactly normal. Thus, when you have enough data, you almost always have a very small p-value: normality rejected.
I think the answers on that thread explain the problem quite well: Is normality testing 'essentially useless'?

Normality of a sample mean


How to link to live chat TawkTo module pop up window with Drupal 7?

Question: I have Tawkto module installed, and I want to create link on my main menu for:
"Live Chat"
The link is:
   Click to Chat

Now this works fine on static HTML pages, but when I paste it in field for main menu, it doesn't work.
I've tried:
 /javascript:void(Tawk_API.toggle())

And:
 javascript:void(Tawk_API.toggle())

How can I do this?
The site with Livechat is:
www.vuxi.com
Comment: You can try implementing [theme_menu_link](https://api.drupal.org/api/drupal/includes!menu.inc/function/theme_menu_link/7.x) hook in your theme's template.php file and replace the link for your menu. You can implement hook using `[THEME_NAME]_menu_link` function name.
Answer: You can easily achieve this by using Void Menu module.

Download & Install Void Menu module.
Go to http://www.yoursite.com/admin/config/user-interface/void_menu
Set javascript:void(Tawk_API.toggle()) as value for HTML value for <void2>
Then go to main menu configuration and set menu Path as <void2>
Comment: Yep, that works perfectly ;)


$G$ is cyclic $iff$ there is an element of order $|G|$.

Question: I'm trying to prove that if there is an element of order $|G|=n$ there the group is cyclic. But I have some problem. Let $a\in G\backslash \{1\}$. And consider $\left<a\right>$ which is cyclic. Let $b\in G$. Then, $b^n=1=a^n\in \left<a\right>$. Does the fact that $b^n\in \left<a\right>$ implies that $b\in G$, and if yes, why ?
Comment: Where did the $p$ come from? And you picked a $b\in G$ so clearly you have $b\in G$.
Answer: By definition $G$ is cyclic iff $G=\langle a\rangle$ and so order of $a$ should be $|G|$. And if the order of $a$ is $|G|=n$ then $a$ generate $n$ distinct elements, and so $a$ generate whole of $G$.


Pegar o valor de um select dinâmico

Question: Gostaria de saber como pego o valor de um <select> dinâmico, ou seja quando eu modificar o valor ele me apresentar este valor, imagino algo como abaixo, alguém poderia me ajudar?
varItens = document.getElementById('caminhos');

for( i = 0;i < varItens.length;i++)
{
  varItens.options[i].selected = true;
   alert( varItens.options[i].id );
}

Porém não funciona, pois sei que isto era caso fosse estático.
Comment: Você deseja pegar o valor selecionado pelo usuário ou todos os valores do select? No seu exemplo você está tentando selecionar todos e tentando exibir o `ID` da `option`, que provavelmente será sempre `null`.
Comment: seria de cada option quando o mesmo fosse selecionado
Comment: Para fazer isso a resposta do @Danilo está correta, desde que você possa usar jquery, como está nas tags da pergunta.
Answer: Vê se isso te ajuda:

$("#caminhos").on('change', function(e){
  alert($(this).val())
  return false;
});

<select id="caminhos">
  <option value="Elemento 1">Elemento 1</option>
  <option value="Elemento 2">Elemento 2</option>
  <option value="Elemento 3">Elemento 3</option>
  <option value="Elemento 4">Elemento 4</option>
  <option value="Elemento 5">Elemento 5</option>
</select>
Comment: obrigado pela resposta, acabei recordando que por ser dinâmico era só eu passar o caminho da div e depois do option ex: $('minhaDiv').on('change','#caminhos',function()
{
});
Comment: Entao essa resposta te serviu? Muito bom :D
Comment: serviu sim, agradeço
Comment: @Danilo acho que devias juntar à resposta a delegação: `$('minhaDiv').on('change','#caminhos',function(){` que era o problema original da pergunta.
Answer: Vi que já aceitaste uma resposta com jQuery. Aqui fica uma com JavaScript nativo:
var items = document.getElementById('caminhos');
items.addEventListener('change', function(){
    alert(this.value); // o valor que procuras é: this.value
});

Se o elemento ainda não estava presente precisas delegar, isso é fácil:
var items = document.getElementById('minhaDiv'); // elemento presente desde inicio
items.addEventListener('change', function(e){
    if (e.target.id == 'caminhos') alert(e.target.value); // o valor que procuras é: e.target.value
});

Neste caso não vale a pena usar jQuery.
Answer: Eu faço da seguinte maneira cada vez que seu select for escolhido ou seja selecionado você pela o valor por uma função que é chamada no onchange ou seja quando mudar esse valor fica armazenado em uma variável.
Comment: Pode nos mostrar a sua maneira com códigos?

Pegar o valor de um select dinâmico


unit of work in a java 'main' application

Question: I am doing this in each and every DAL method:
 public static Product GetProductByPartNumber(String partNumber)
    {
         Session session = HibernateUtil.getSessionFactory().getCurrentSession();

         session.beginTransaction();

         Product product = (Product)session.createCriteria(Product.class)
                                    .add(Restrictions.eq("partNumber", partNumber))
                                    .uniqueResult();
         session.getTransaction().commit();

         return product;
    }

This is causing problems, giving me 'session is closed' errors because of lazy loading etc.
How can I have getCurrentSession to not get a new session?
public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration().configure();

            //configuration.addClass(hsspider.Model.AMCategory.class);

            return configuration.buildSessionFactory();
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

        <property name="current_session_context_class">thread</property>

I am guessing that is the problem, that the call to getCurrentSession is not getting the current session right?
Or does calling transaction.commit(); kill the session?
Should I just use flush?
Comment: transaction.commit() does not close the session .. It sounds like you may be closing the session yourself somewhere else in the Thread.  Which version of Hibernate are you using?  I know that in older versions you had to explicitly reconnect a session after you close the transaction, but you don't have to do that with the current version.
Comment: Bryan; the default session context *does* close the session when the transaction is committed. This is done because the ThreadLocalSessionContext cannot rely on any other hook for cleanup.
Comment: Why would you not just continue this conversation where it started?
http://stackoverflow.com/questions/2029301/many-to-many-mapping-not-working-one-side-is-set-to-inverse/2029414#2029414
Comment: @delfuego that other thread seems to be a different question, so this one deserves another post.
Answer: Did you look at the Transaction javadoc that I'm quoting below?

Allows the application to define units of work, while maintaining abstraction from the underlying transaction implementation (eg. JTA, JDBC).
A transaction is associated with a Session and is usually instantiated by a call to Session.beginTransaction(). A single session might span multiple transactions since the notion of a session (a conversation between the application and the datastore) is of coarser granularity than the notion of a transaction. However, it is intended that there be at most one uncommitted Transaction associated with a particular Session at any time.

And, about Transaction#commit():

Flush the associated Session and end the unit of work (unless we are in FlushMode.NEVER. This method will commit the underlying transaction if and only if the underlying transaction was initiated by this object.

This should answer your question: commit() doesn't kill the session (that can span multiple transaction as we saw).
Another good idea would be to put a breakpoint and to look at the internal details (you may need to tell your IDE where to find Hibernate sources for this).
I also suggest to check Pluggable Session management in Hibernate 3.1 and the more recent Sessions and transactions (especially Transaction demarcation with plain JDBC).
Answer: It could be that you use the ThreadLocalSessionContex. The interesting part of that javadoc is:

it was decided to have this default
  impl actually generate a session upon
  first request and then clean it up
  after the Transaction associated with
  that session is committed/rolled-back

The best way to deal with this is to move your transaction boundaries to incorporate the entire process; that is, not only getting the Product but also doing whatever you want with it.
You can change the behavior of ThreadLocalSessionContext by subclassing it and re-implementing isAutoCloseEnabled() and other methods. You'd have to find a way to signal closing of the session though.
Comment: This is not exactly my understanding of http://relation.to/Bloggers/PluggableSessionManagementInHibernate31 and https://www.hibernate.org/42.html.


Solving for Displacement given Velocity and Acceleration?

Question: I have given a problem to solve for the displacement of an object given the acceleration $-10\;\mathrm{m/s^2}$ and the initial velocity $627\;\mathrm{m/s}$ of how far an object shoots up, though I am not given the time, so I can't use the equation
$$S=vt+\frac{at^2}2$$
Is there a way to solve this? Thanks!
Edit Thanks to whoever edited my question for the formatting
Comment: How about finding the time when the velocity gets zero with $v(t)=v_0+a t$ (which would be mathematically equivalent to finding the maximum of $s(t)$) ? If you get this time then you can use it in the equation you wrote down in your post to get the distance.
Comment: Are you allowed calculus?
Comment: @JoeJohnson126 Yes.
Answer: You can use Torricelli's equation: $$v_f^2 = v_0^2+2a\Delta S$$ where $v_f, v_0$ are, respectively, the final and initial velocity of the object, $a$ its acceleration and $\Delta S$ its displacement, and solve for $\Delta S$.
You know that at the point of maximum height, the object's velocity is 0 $m/s$. Substituting the other terms, and solving for $\Delta S$, we have $$\Delta S = \frac{-v_0^2}{2a} = \frac{-627^2}{-20} = 19 656.45 m$$
Comment: How did you get the final velocity in that equation?
Comment: You want to find the object's maximum height, but this is the moment right before it starts to fall. Falling means its velocity is negative. Which means that at the point of maximum height its velocity is zero, and therefore $v_f = 0$.
Answer: If acceleration is $-10$, and velocity is an antiderivative of acceleration, then
$$
v(t) = \int -10 \, dt = -10t + C.
$$
If you put in $t = 0$ you will see that $C$ is your initial velocity.  Then you have that displacement is an antiderivative of velocity.


ALIMENTAR TABELAS (SQL SERVER )

Question: Opa Bom dia.
Tenho um banco sql, neste banco existe uma tabela para Pessoas, é uma segunda tabela para cadastro de credenciais,  em uma terceira tabela e feito a associação da credencial com a pessoa, ou seja existe uma Tabela chamado CRED_PESSOAS, onde através do código da pessoa é numero da credencial é feita a associação da credencial para pessoa.
Tenho um cliente que pediu para alimentar essas informações de credencial através de scripts, já alimentei as duas tabelas (PESSOAS E CREDENCIAIS) minha duvida é como criar uma condição, onde eu pegue por exemplo a credencial X para pessoa Y, credencial y para pessoa x e assim em diante.

Desde já agradeço.
Gustavo Braga
Comment: Gustavo, bem vindo ao stackoverflow em português, seria legal fazer um [Tour](http://pt.stackoverflow.com/tour), e editar sua pergunta com algumas informações como;  Qual banco de dados? e qual a estrutura das tabelas?
Comment: OPA, Obrigado pela dica vou me atentar mais sim, so que não não conheço muito do SQL é muito menos desta base acabei de receber esta demanda aqui no escritório, coisa de comercial que vende o que não pode entregar kkk
Comment: Bom, você esta fazendo o insert desses dados, acredito que saiba qual banco onde essas informações estão sendo armazenadas, e qual os campos das tabelas.
Comment: Então ainda não entendi o que precisa saber exatamente, o Banco é SQL SERVER, as tabelas que estou alimentando são aquelas que citei, na tabela credencial eu alimentei uma coluna chamada CRED_NUMERO, como o numero das credenciais, Na Tabela PESSOAS fiz num tipo de insert pois as pessoas já estavam cadastradas, dela so preciso pegar a PES_NUMERO para associar com com a credencial na tabela CRED_PESSOAS
Comment: OK, quando um dado já esta inserido ( ... Na Tabela PESSOAS fiz num tipo de insert pois as pessoas já estavam cadastradas, ...) o que você faz é um update para atualizar o campo, você precisa pega o PES_NUMERO, mas como vai usar isso e qual informação você tem para regasta esse número?
Comment: Editei o post com duas imagens, que deve transparecer melhor o que preciso.
Comment: De onde está vindo os dados de uma planilha, do banco de dados ou aplicação.  Mostre como fez os outros insert e o que é preciso fazer,  eu ainda não sei o que você quer.
Answer: Você precisa de um relacionamento restritivo entre as tabelas, conforme exemplo abaixo:
<code>    SELECT pessoa.*, credencial.*
      FROM pessoa
INNER JOIN pessoa_credencial ON pessoa_credencial.id_pessoa = pessoa.id
INNER JOIN credencial ON credencial.id = pessoa_credencial.id_credencial
</code>
Lembrando que o relacionamento desta forma, caso seu banco de dados possua mais de uma credencial para a mesma pessoa ou mais de uma pessoa para uma credencial) poderá retornar mais de uma linha.
Obs.: O select que montei é um exemplo, não necessariamente representa a estrutura das suas tabelas, mas indica a forma correta de fazer o relacionamento entre as 3 tabelas que você possui.

ALIMENTAR TABELAS (SQL SERVER )


Is it possible to authencticating/login for WPA2-Enterprise using web portal?

Question: I just wondering is it possible using WPA2-Enterprise with authentication using web just like captive portal? If possible I think it would be really cool though the setup will take time.
Answer: No, this is not possible.
WPA2 Enterprise requires successful authentication before any data can be transmitted to/from the client. This obviously precludes serving a web form to the user before they're authenticated to the network.
Comment: thank you very much for your explanation EEAA, now it really clear to me how WPA2 Enterprise work :).


Andy Timmons Dimarzio AT1 pickup sound

Question: Well, the story goes like this : I have a custom made Tom Anderson guitar which has a fender style body (alder wood). The guitar comes with VAx pickups which sound great but the pickup near the bridge is way too bright for my taste. So... I replaced the entire circuit (Removed it as is so I could install it easily back) with Andy Timmons pickup set (Neck = Middle = Dimarzio-Crusier, Bridge = Dimarzio AT1 custom) installed on a different pickguard.
Now the bridge sounds much more like I want it to sound BUT I do not feel that "fat" tone and warmth this pickup is told to have.
I used the following diagram for the wiring.
My signal-chain : Guitar --> TS808HW --> Carl Martin Compressor --> Engl Screamer AMP
Again, the sound has less bright hisses and the harmonics are great but still I am wondering what makes that punchy/crunchy tone when he plays.
Comment: don't underestimate the importance of microphones in capturing the audio for recording. I don't know the artist, but I did a video search and I was struck by how much he manipulates the pickup selector switch, sometimes 2-3 times in a run (!)
Answer: The tone quest is very ellusive. I too went down trying to get Andy Timmons sound several years ago. It is damn near impossible to get the exact sound without the exact equipment.
PU's matter but the amp and effects are just as important. Each variable in the equation interacts with all the others to create compound effects that are impossible to determine. Even the same model gear won't necessarily sound the same.
I will only list some of the variables but not go into detail. All I can say is, if you want a great sound, go play your guitar and be amazing at it... you will then find people that can get you the sound you want. It's almost impossible to be a sound engineer, electrical engineer, musician, and guitar player and be good at them all. (just not enough time or money)

Pickups*
Pickup height*
Guitar Electronics*
Guitar type(wood, scale length, etc... This are important but not that much. They effect the timbre of the sound to a small degree but are maybe the last 2% of the sound... assuming you have a similar guitar to Andy).
Amp* (boost in front of the amp can help in some cases, Includes speakers)
Compressor*
Delays and Reverbs(required effects but any will do. Some are better than others but maybe 2% of the sound).
EQ*
Touch(about 2%. Obviously we are talking about tone here and not ability. Two separate issues but touch does factor into the sound to some degree. e.g., If you play too soft you won't get the bitey sound)
Volume*

All the * are very important in getting the sound. You could also have Andy's exactly equipment but if you have the settings wrong you won't have his sound.
Andy obviously developed an ear for the type of tone he likes and can probably dial a good sound on most gear rather quick(he knows what he likes and how to get it).
EQ is probably one of the biggest things that can make or break your sound. Andy's tone tends to be pretty compressed and very middy with nominal presence. Use a 31 band dual EQ and put it on the input and FX loop of your amp and you'll be amazed at all the different tonal variations you can get. This might be enough to get you what you want if you can dial it in.
Comment: Regarding effects I do use the Carl Martin and TS808HW and in the neck position I get almost the exact same tone (like in "electric gypsy" track). its punchy, fat and feels sooo damn right:). About the bridge I agree this depends on equipment+setup and you can never know how he tweaks (circuit-wise) his pedal effects like he did with the BB Preamp which he oftenly uses. Thank for the detailed answer !
Answer: Preamplifier circuits make a huge difference between whether a tone is "fat" or "chunky".
In a typical distortion block, made up of several stages, there is tone filtering before, in between and after.
Some guitar preamplifiers (or preamplifier stages of amps) have multiple voicings that you can switch. Others have multiple gains to control where in the distortion block most of the distortion happens, which affects the tone.
You can also add "pre EQ" before the amplifier. The first pre-EQ is your guitar's tone control. The next is any box you have before the amplifier, like an overdrive pedal (which you already have).
Speaking of which, your placement of the compressor after the OD pedal doesn't make a lot of sense, unless you're using the OD just as a boost (to ovecome the compressor not having a low enough threshold: hard to believe). Usually, a compressor goes first, then limiting/clipping devices and distortions. If the signal level is already limited by a soft-clipping OD, then a compressor won't do much with it. (Does Andy Timmons also put a compressor after overdrive, is that why? Even so, that doesn't mean you should do it.) What if the TS808 is driving the compressor too hard, causing some distortion from the compressor, which then affects the tone. That compressor is not meant to distort; it is intended to be a sonically pure compression effect.
You might get more flexibility out of the chain if you put the compressor first, then the overdrive pedal. Also, try driving the amp just with the compressor alone, and with the OD alone, various settings of each.
Comment: Hi @Kaz. I started it off with the compressor first. During my experiments of capturing the tone I switched the order and believe it or not it sounds different and more creamy in the soft-gain channel and the compressor makes the screamer much more punchy. The most beautiful things come from the unexpected right ?
Answer: Your question is almost impossible to answer. In the setup you use, there are already so many variables: the guitar, tubescreamer, amp, compressor. Add to this the type of strings and their thickness, the material and thickness of your pick. How hard do you hit your strings, what is the angle of your pick etc. etc. etc.
One thing I've learned is that the single most important item when it comes to creating tone is: YOU.
Comment: BTW are you familiar with Andy Timmon's music ? his gear etc ? I was not just asking out of the blue this question. anyway just got another answer more the point : "Funny you bring this up. I spoke with Andy last thursday about his gear and essentially, his AT1 is like a JB but with softer highs (his own words) and he plays his amps LOUD. really, really LOUD. That's how he gets that punchy, crunchy sound. and... a lot of talent."
Comment: That is just my point: every part in the chain matters, so it's virtually impossible to say "I would like exactly so-and-so sound, what kind of -fill-in-some-apparatus-or-gear- do I have to use?". Every variable is important. However, why I ended with the player being most important: he/she is the start of the chain. Try this out: record a few minutes of you playing, then give the guitar to a friend and let him/her record a few minutes. I will bet it will sound very different...
Comment: I do not agree with your answer completely. I agree there are many components influencing the final signal coming out from the amp but still pickups play a big role in this process and the body of the guitar.
Comment: When you play lets say a power chord if the pickup is warm and crunchy the pickup is warm and crunchy, and the chord will sound warm and crunchy (unless you use some really nasty pedals on the way which in my case its quite what Andy used in one of his recordings). So an amateur player will be play the chord less accurately but still you will feel that tone coming out from the guitar.

Andy Timmons Dimarzio AT1 pickup sound


Show all results of a table and how many are in which district

Question: I have a table with records of cars. I want to query that table so that all (found) records are retrieved AND a table with the district-name plus how many cars are in the districts is shown besides the results.
Like a normal craigslist result page or similiar sites, where the results are shown, and on the left side is a table which shows where (in which disctrict, etc.) the results are and how many in each district are, etc.
At the moment I achieve that with two queries, but I asked me if that couldn't be done with just one query?
My table looks simplified like that:
    name | color | year | district
    ------------------------------
    ford | blue  | 1998 | 1010
    opel | red   | 2001 | 1030
    vw   | green | 1999 | 1010
    ...  | ...   | ...  | ...

So the result should look like:
districts       results
---------       ----------
1010 (2)        ford, 1998
1030 (1)        opel, 2001
....            vw, 1999
                ...

Hope you know what I mean.
Comment: What's the structure of the table that holds the districts?
Comment: What do you want the result set to look like?
Comment: To have two result sets, you need 2 queries.
Comment: Is one query what you want? It may be more efficient to do two.
Comment: that was not the answer i wanted to hear but if it's not possible, than it's not possible :) at the moment i'm retrieving my expected result with two queries, but i asked myself if that could not be done with a special "join-group-having" trick, because i query the same table two times... but thanks for your answer :)
Answer: You can't generate two views from a single query. If you want to view all records, that's one query. If you want to view records grouped by district, that's a separate query.
Comment: that was not the answer i wanted to hear but if it's not possible, than it's not possible :) at the moment i'm retrieving my expected result with two queries, but i asked myself if that could not be done with a special "join-group-having" trick, because i query the same table two times... but thanks for your answer :)
Answer: You can't have two result sets generated from one query.
To get the district name with the total number of cars do this:
SELECT d.name, COUNT(c.id) as total
FROM districts AS d
LEFT JOIN cars AS c ON c.district = d.id
GROUP BY d.id;

Comment: that was not the answer i wanted to hear but if it's not possible, than it's not possible :) at the moment i'm retrieving my expected result with two queries, but i asked myself if that could not be done with a special "join-group-having" trick, because i query the same table two times... but thanks for your answer :)
Answer: My guess is that you have to use GROUP BY for this.
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
SELECT c.name,
       c.color,
       c.year,
       c.district,
       COUNT(c.id) counted,
FROM   cars c
GROUP BY district, name

Comment: thanks. but you're right and wrong. right for group by (for the districts), but wrong because if i make a group by i can't display _all_ of my cars (just grouped by the district) :)


reason to "Permission Denial: receiving Intent "

Question: I successfully made these c2dm implementations work on my app.
I have a problem when the c2dm messages are not received suddenly by the device.
This time it gives me permission denial which I am confused about:

Permission Denial: receiving Intent {
  act=com.google.android.c2dm.intent.REGISTRATION cat=[myapp.android]
  (has extras) } to myapp.android requires
  myapp.android.permission.C2D_MESSAGE due to sender
  com.google.android.location (uid 10037)

It happened to me the second time now, I can't just tell my users that they need to perform factory reset when they didn't receive any command.
Has anyone here encounter similar issue? Any help or insights and causes would be much appreciated.
manifest.xml as requested

   <receiver
        android:name="myapp.EmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="myapp" />
        </intent-filter>
    </receiver>

...

<uses-permission android:name="myapp.android.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.INTERNET" />

Answer: For me, it worked after I defined it as follows:
<permission android:name="mypkg.permission.C2D_MESSAGE" android:protectionLevel="signature"/>
<uses-permission android:name="mypkg.permission.C2D_MESSAGE"/>

where mypkg = is my app's package
Answer: You also need to define the permission in your manifest like so, because it is not a system one, but one specific to your app:
<permission android:name="myapp.android.gms.permission.C2D_MESSAGE" />

In case you already have, it is probably a bug in a specific device or an older version of related Google libraries, etc. Not much you can do in that case.
Comment: Hello, Elenkov.

I don't define it, try it.
If I don't define it, I suddenly can't receive notification?
In addition, I don't use gsm network...

Thank you for your help
Comment: Does it work when you define it properly? Not sure how the GSM network is related... Does the problem present itself on specific devices and/or Android versions?
Comment: Try now. When it define, program work normally. This problem has occurred only once, the Android version and device isn't known only one.
Comment: wow it worked for mine. As stated from the comment, it's probably a bug in a few specific devices. !
Answer: I've run into the same problem, even when I had the permission defined in my manifest.
It seems to have something to do with protectionLevel="signature" and the definition of the permission becoming corrupted when the app is reinstalled with production vs debug keys.
What fixed it for me was temporarily setting protectionLevel="normal", then reinstalling the app, then changing back to "signature" and reinstalling again.


How to load a Processor into Apache NiFi while it is running?

Question: I it possible to load a new Processor into Apache NiFi while it is running
Furthermore, is it possible to update an already loaded Processor in a running Apache NiFi instance?
I am coming from an Erlang background, where the BeamVM can actually facilitate hot module replacements all together with state updates. Its a complicated topic, but possible.
It would be great to at least be able to load new code into a running NiFi instance, without having to stop the cluster when applying new Processors.

A possible workaround I have found (although not preferred) is to use a scripting Processor that can set/update code at runtime via its properties.
Answer: Historically it has required a full restart of NiFi to load new NARs, but on the apache master branch there is a new feature to watch a directory and auto-load new NARs, so you can expect this to be available in a future release, possibly 1.9.0 if the community decides on that.
https://issues.apache.org/jira/browse/NIFI-5673
We don't plan to re-load existing NARs as it can be problematic to unload classes in the JVM, and also with versioned NARs I would argue that when you deploy a NAR you should be deploying a new version, and not trying to overwrite a version of an already deployed NAR.
Hope that helps.
Comment: Thanks for the answer. This is great news. Do you know if unloading them is also supported by any chance?
Comment: There are currently no plans to support unloading that I am aware of, is there a reason why you would want/need to do that?
Answer: During development/prototyping one often needs to redeploy a broken or partially-complete processor, and it's irritating, to say the least, to have to bump the version number for every typo or microfeature.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


math.floor(N) vs N // 1

Question: I am wondering if anyone can give me any insight into how the following may be the same / different in Python3:
N // 1

and
from math import floor
floor(N)

I tried the following, which seems to indicate that they are equivalent:
import math
import random

for _ in range(0, 99999):
    f = random.random()
    n = random.randint(-9999, 9999)
    N = f * n
    n_div = N // 1; n_mth = math.floor(N)
    if n_div != n_mth:
        print("N // 1: {} | math.floor(N): {}".format(n_div, n_mth))
else: # yes, I realize this will always run
    print("Seem the same to me")

Thanks for comments below. Updated test to the following, which clearly shows float // N returns a float, while math.floor(N) returns an int in python3. As I understand it, this behavior is different in python2, where math.ceil and math.floor return floats.
Also note how unusual/silly it would be to use math.ceil or math.floor on an int instead of a float: either function operating on an int simply returns that int.
import math
import random

for _ in range(0, 99):
    N = random.uniform(-9999, 9999)
    n_div = N // 1; n_mth = math.floor(N)
    if n_div != n_mth:
        print("N: {} ... N // 1: {} | math.floor(N): {}".format(N, n_div, n_mth))
    elif type(n_div) != type(n_mth):
        print("N: {} ... N // 1: {} ({}) | math.floor(N): {} ({})".format(N, n_div, type(n_div), n_mth, type(n_mth)))
else:
    print("Seem the same to me")

Comment: @NotAnAmbiTurner Yes, that's exactly what I said.
Comment: It's all the same.
Comment: `//` returns a `float` and `floor` returns an `int`?
Comment: @tobias_k in Python 3, `math.float()` and `math.ceil()` return `ints`
Answer: You will spot a difference when using floats:
>>> 1000.5//1
1000.0
>>> floor(1000.5)
1000

floor returns an integer. For most cases 1000 and 1000.0 are equivalent, but not always.
Answer:
math.floor(N) returns an int, and N // 1 returns a float.
>>> type(math.floor(-4.4))
<class 'int'>
>>> type((-4.4) // 1)
<class 'float'>

Because of this floor(nan) will raise ValueError while nan // 1 returns NaN (similar for ±inf.)
>>> math.floor(math.nan)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot convert float NaN to integer
>>> math.nan // 1
nan

I don't think there are other differences when N is a float, since x//y is defined as ⌊x/y⌋.
Comment: I think this answer is practically correct, because you can expect to use a these functions only on floats.
Answer: math.floor first tries to use the __floor__ magic method, if it does not exist it instead uses __float__ and then floors that, so it will work when the object supports __floor__ or can be cast to a float.
x//1 uses the __floordiv__ magic method and if that is not defined or returns NotImelemeted it  then tries __rfloordiv__ on the integer 1 which will almost certainly be NotImplemented, so this would require __floordiv__ to be implemented on the object in question.
from math import floor

class MyInt(int):
    def __floor__(self):
        print("using __floor__")
        return int.__floor__(self)
    def __floordiv__(self,other):
        print("using __floordiv__")
        return int.__floordiv__(self,other)

>>> x = MyInt(5)
>>> floor(x)
using __floor__
5
>>> x//1
using __floordiv__
5

Normally the two values will always be equal but may implement the two differently, usually the only noticable difference is the type of the return value although there can be more substantial changes depending on what kind of object you are using:
>>> x = numpy.array([1.5, 2.3, 5])
>>> x//1
array([ 1.,  2.,  5.])
>>> floor(x)
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    floor(x)
TypeError: only length-1 arrays can be converted to Python scalars

math.floor(N) vs N // 1


DTO - Interface x Class

Question: Tenho usado Interface para criar DTO (Data Transfer Objects), objetos "burros" que só servem para padronizar a comunicação de objetos entre o front e o back. A minha questão é a seguinte: Realmente usar Interface é a melhor prática? Ou seria melhor usar classes? Qual a opinião de vocês a respeito disso?
Ex:
interface UserDTO {

    name?: string;
    mailAddress?: string;
    phone?: string;
}

 params: UserDTO;

_save(user): void {

   this.params = {};

   this.params.name = user.name;
   this.params.mailAddress = user.mailAddress;
   this.params.phone = user.phone;

   [...]
}

Acabo tendo que definir as propriedades como nullable para poder inicializar a interface com objeto vazio, para que não ocorra null reference exception. É exatamente isso que está me incomodando. Caso utilizasse classe resolveria isso instanciando um objeto User. Espero ter sido claro.
Comment: Obrigado. Estava fazendo isso agora.
Answer: A interface pode ser uma forma de tipar uma estrutura JSON. A vantagem de usar interface direto é tratar o objeto como um JSON puro. Visto que assim permite você criar o objeto direto nesta notação.
EX:
this.params = {
     name: "Nome",
     mailAddress: "email@example.com",
     phone: "55555555"
}

Como você quer criar um JSON com campos que podem não existir, seria mais prático realmente usar Classe. Porém você teria que converter esta para JSON antes de salvar:
class UserDTO {

    name: string;
    mailAddress: string;
    phone: string;
}

params: {} = {};

_save(user: UserDTO): void {

    this.params = JSON.stringify(user);

    [...]
}

Answer: Acredito que são duas questões separadas. Por partes.
Evitar a exceção na criação diretamente a partir da interface
Para evitar exceção de null na inicialização vazia da interface, basta que você inicialize o objeto diretamente, assim:
this.params = {
     name: user.name,
     mailAddress: user.mailAddress,
     phone: user.phone
}

Isso permite criar o objeto diretamente, e ao mesmo tempo impede a criação de um objeto com alguma propriedade null, onde isso não seja permitido pela interface.
É isso que você provavelmente quer, para evitar entrada de nulls no seu processamento.
Criar um objeto "vazio", padrão, para mutação posterior
Para criar um objeto vazio, que seja ao mesmo tempo válido, você daí sim precisa usar classes, para que possa informar inicializadores padrão em cada propriedade ou um construtor que preencha as variáveis com valores padrão ou alguma computação.
Nesse caso, para manter o "jeitão" geral de usar interfaces no DTO, pode-se criar uma classe DtoDefault que implementa um Dto em particular. Assim, a interface permanece "pura", só informando como os dados são, e quaisquer defaults são encontrados numa classe separada.

DTO - Interface x Class


General Expansion formula for $(x_{1}y_{1}+x_{2}y_{2}+\cdots+x_{k-1}y_{k-1})^{2}$

Question: I am looking for a more formal way to represent the expansion of
$$
(x_{1}y_{1}+x_{2}y_{2}+\cdots+x_{k-1}y_{k-1})^{2},\quad (x_{i},y_{i})\in\mathbb{R}^{+}\times\mathbb{R}^{+}
$$
There is a nice exercise in Spivak's book on the relation
$$
(x_{1}y_{1}+x_{2}y_{2})^{2}=(x_{1}^{2}+x_{2}^{2})(y_{1}^{2}+y_{2}^{2})-(x_{1}y_{2}-x_{2}y_{1})^{2}
$$
I was wondering if we can use this to establish a general formula for $k$ variables $x_{i}$ and $y_{i}$. Any suggestion is definitely welcomed.
Comment: there are some related things that are only possible when the dimension is a power of $2.$   If you can specify something in dimension $3,$  I guess $(x_1 y_1+x_2y_2+x_3y_3)^2$  compared with $(x_1^2 + x_2^2 + x_3^2)(y_1^2 +y_2^2+y_3^2).....$  let me check
Comment: @SPARSE Lookup [Lagrange's identity](https://en.wikipedia.org/wiki/Lagrange%27s_identity).
Comment: what is a more formal way in your definition ? Do you want this to be sum of squares?
Comment: @dezdichado That is one way for instance. Maybe we can represent it as a binomial expansion? I am not much familiar with these notations and would love to get some help with these
Comment: Hint: induction.
Comment: I mean this is essentially a SOS proof of Cauchy-Schwarz in the discrete settings:
$$\left(\sum x_iy_i\right)^2 = \sum_i x_i^2\sum_j y_j^2 - \sum\limits_{i<j}(x_iy_j - x_jy_i)^2$$
Answer: $X = (x_1,x_2,...,x_n)$,$Y = (y_1, y_2,...,y_n)$ column vector.
Let tr(A) represent the trace of matrix $A$, it has following properties:
(1)tr(AB) = tr(BA),
(2)tr(A+B) = tr(A) + tr(B),
(3) $tr(A^T) = tr(A)$,
(4) if A is $1\times 1$ matrix then tr(A) = A.
$\sum^n_{i=1} x^2_i \sum^n_{j=1} y^2_j - (\sum^n_{i = 1} x_i y_i)^2=  X^TXY^TY - X^TYX^TY = tr(X^TXY^TY - X^TYX^TY) = tr(X^TXY^TY) - tr(X^TYX^TY) = \frac{1}{2}(tr(YX^TXY^T) + tr(XY^TYX^T) - tr(YX^TYX^T) - tr(XY^TXY^T)) = \frac{1}{2}
(tr(YX^TXY^T + XY^TYX^T - YX^TYX^T - XY^TXY^T)) = \frac{1}{2}tr((XY^T - YX^T)^T(XY^T - YX^T)) = \sum_{i<j} (x_iy_j - y_ix_j)^2$


What is tremolo picking?

Question: Are you just picking the same note a bunch of times or are you picking a lot in general and kind of hammering on to hit the notes? What does it have to do with an actual tremolo (whammy bar)?
Answer: Tremolo picking means picking a note fast and repeatedly to give the impression of a single, sustained note with a "trembling" feel to it.  You hear this a lot in mandolin playing: since the mandolin has such poor sustain, players use tremelo picking to play melodic lines that require longer-sustaining notes.
It's not just playing really fast.  A famous example is Eddie Van Halen's "Eruption".  He's playing notes really fast throughout the whole song, but the tremolo-picking part is only from 0:30 to 0:37.
As a technique of altering the sound of a sustaining note, tremolo differs from vibrato in that tremolo modulates the volume of the note (rapidly sounding slightly louder, then slightly softer), while vibrato modulates the pitch of the note (rapidly sounding slightly shaper, then slightly flatter).  Interestingly, Fender got these two backwards: the "tremolo bar" on Strats actually produces vibrato---at least, that was what it was intended to do; Leo never envisioned it as a "whammy" bar---while the "vibrato" effect on Fender amps actually simulates tremolo.
Comment: Interesting tidbit on Leo. I'd never noticed that before.
Comment: For a very good example of tremolo picking:http://www.youtube.com/watch?v=qJmI6fAPUSk&feature=related
Answer: Its pretty much just fast picking; where instead of playing/picking each note in a riff once; you pick each note three/four/five times; at speed.
I think the term 'tremolo picking' comes from the effect produced from doing this.
Here's an example
<code>$6.5  $6.5  $6.5  $5.7  $5.7  $5.7  $6.8  $6.8  $6.8  $5.5  $5.5  $5.5  $6.7  $6.7  $6.7  $6.5  $6.5  $6.5
</code>
Pretty basic, but that's the idea, any difficulty comes from the speed.

What is tremolo picking?


Greatest integer less than or equal to the 50th term of the series defined below

Question: This question I found in one of my practice papers for the JEE
$$a_{1}= \sqrt[3]{28}$$
and
$$a_{n+1}=\sqrt[3]{a_{n} + 60} \space \space \forall \space n \in\Bbb N $$
Question asks for greatest integer less than or equal to the 50th term of the series defined above.
How to approach this?
Comment: Please, give examples for the "lot" you've tried, add some background, or why you (or us) should care. Otherwise, the question will most likely be closed..
Comment: You couldn't see a pattern in the terms here?  Really?  How many did you compute?
Comment: Is it good to even compute a2?
Answer: It is easy to see that $a_n$ is a strictly increasing sequence and is bounded above by $4$. (Both these facts can be proven via induction.)
This shows that $a_n$ converges. (Of course, as a JEE student, you probably do not care about this and could have assumed this anyway.)

Now, let us calculate that limit $L = \displaystyle\lim_{n\to\infty} a_n$. Since we know that $(a_n)$ converges, we can take limit on both sides of the recurrece relation to get
$$L = \sqrt[3]{L + 60}.$$
Cube both sides and note that $L = 4$ is the only (real) solution. Thus, $L = 4$.

From this we conclude that $a_n < 4$ for all $n \in \Bbb N$. Moreover, since $(a_n)$ was increasing, we have that $a_1 \le a_n$ for all $n \in \Bbb N$.
Noting that $a_1 = \sqrt[3]{28} > \sqrt[3]{27} = 3$, we see that
$$3 < a_n < 4.$$
You can now conclude that the answer is $3$.
Comment: So it's not a question about creating telescopic series . Damn it


Merging MediaWiki contents together

Question: Currently I have two MediaWikis, one a slightly older version than the other.  I want to merge the contents of both together, without eliminating duplicate pages.  So far the best option I can think of is to use a bot (like pywikipedia) to go through all the pages of one wiki, and try inserting them into the other, renaming duplicate pages.
This solution seems like it would take a while to accomplish though.  Is there a more pleasant way to do this that I'm just unaware of? I haven't worked with the MediaWiki database directly very much, so I'm not very comfortable messing with it without knowing what I'm doing.
Answer: MediaWiki has import and export features, that you can use for moving the contents. It does merge histories of existing pages (see import link).
However, it does not handle conlicts of two different pages with the same name, so you'll have to handle moving the pages by yourself. As far as I can see in description of MediaWiki page table, you might be able to find and rename duplicate pages directly in SQL, but pywikipedia should work too (but you'll need to delete redirects that will result from "correct" page moves, otherwise they'll mess up with imported pages from the other wiki).
Comment: I agree -- unless there are going to be several hundred duplicate pages, I recommend using the XML import/export feature.
Comment: From what I see of the Import feature, it looks like it's useful for small sets of files, but not as useful for larger sets.  It looks like duplicate pages have to be handled by the user, and the customizing import options seems limited.  Right now, pywikipedia is looking to be the best option...
Answer: As a committer of https://github.com/WolfgangFahl/py-3rdparty-mediawiki i recommend using the wikibackup/wikirestore feature of that tool - it will do the export/import in a way that allows to use standard unix tools while at it e.g. doing tree diffs of the backups to see what to do with the duplicats.

Merging MediaWiki contents together