Melhor definição do EntityManager

Question: Estou estudando sobre JPA juntamente com a Injeção de Dependências e li alguns pontos sobre o EntityManager:
Se usarmos o seguinte método:
public EntityManager getEntityManager() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("exemplo");
EntityManager entityManager = factory.createEntityManager();
factory.close();
return entityManager;
}

Estamos informando a unidade de persistência que está definida no arquivo persistence.xml e criando nosso EntityManager.
Eu li também que podemos usar assim:
@PersistenceContext(unitName = "exemplo")
  private EntityManager entityManager;

Ambos acima tem o mesmo efeito ?
Em relação a Injeção de dependência com CDI eu li que ao usar o @Inject em um objeto EntityManager dentro de um DAO por exemplo, o objeto entityManager vai possuir todas as suas dependências preenchidas. Mas se quisermos dizer ao CDI como o EntityManager deve ser instanciado, podemos criar um método em uma classe X com a anotação @Produces. Outra pergunta: O @Produces juntamente com o @PersistenceContext poderiam ser usados no método getEntityManager()? Para se carregar a unidade persistência definida no arquivo persistence.xml ou para criar nosso EntityManager precisa ser o método main ? Ou estes recursos já são lidos ao se iniciar um servidor de aplicação, no meu caso o wildfly ?
Comment: `@PersistenceContext` é utilizado quando se tem mais de uma unidade de persistência. Geralmente quando sua aplicação trabalha com vários bancos. Quando é necessário dizer em qual deles se deseja persistir, editar ou ler dados. Agora quanto a injeção de dependências, gerenciamento de escopos e transações, etc.. Sugiro dar uma lida sobre o Spring Framework. Ele facilita bastante essas tarefas, tem uma excelente documentação e uma comunidade muito ativa.
Answer: Basicamente e a mesma coisa, a diferença crucial neste ponto é que em um, a JVM faz as magicas dela pra criar seu EntityManager e no outro você tem uma classe JPAUtil que trás para você esse Entity.
A melhor abordagem é a injeção pois assim você não tem que instanciar nada e nem se preocupar em como esse objeto vem e tudo mais, o java e o hibernate cuida de tudo e trás pra você, só precisa de um annotation em cima do seu atributo de classe geralmente e pronto, MAGIC.Acho bem interessante usar injeção de dependências porque quando você injeta ela, pelo menos CDI cuida de fechar as conexões, oque já ajuda bastante, geralmente da trabalho fechar as conexões da forma correta sem deixar ninguém sem ela...
O @PersistenceContext deve ser usado dentro de uma classe @Repository, como boa pratica, mais caso queira usar ele fora disso, até aonde eu sei, nada impede, faça testes, escreva pequenos códigos, veja os erros acontecer e compartilha com a gente os resultados das suas perguntas ai.

Melhor definição do EntityManager


Connecting to locahost from android device using a hostname with dynamic IP addresses (Changing Constantly)

Question: CONTEXT OF QUESTION:
I have a computer running a local webpage on a WAMP server. The computer is connected to a wireless connection.
I have an android tablet that is connected to the same wireless network.
PURPOSE (WHAT I WANT TO DO):
I want to be able to access the local webpage on the WAMP server using a hostname through my APP.
WHAT I HAVE ALREADY TRIED:
I can already address the webpage from my app by using the ip address of the computer (http://192.168.x.x/Webpage_Name). However, since my ip is dynamic (changing constantly) this implementation will not work. Please correct me if I am wrong.
My idea was to use edit the hostfile of the computer. However, my understanding is that a hostfile is static meaning that it can not resolve hostnames to changing ip addresses (it only stores an ip address and its corresponding host name). Furthermore the hostfile would not be on the Android device so the android device would not be able to connect to the server using the hostname specified in the hostfile. Please correct me if I am wrong.
My second idea was to use a DynamicDNS service. However, my only problem with that is if I want a free third party service to provide the DNS my webpage information would have to go through the internet. I want this webpage to remain local so I think DNS would not be an option. Please correct me if I am wrong.
My third idea was to first create a TCP connection between the Computer and Android device through the app. Then I would send the IP address of the computer in a string from the computer to the android device. Then the android device could use the ip address that was sent to connect to the local server. Now my understanding is that you need the ip address and port to create a TCP connection between the android device and the computer and this is why I think this implementation will not work. Since I need to hard code the ip address in this option aswell the problem persists.
MAIN QUESTION (WHAT I WANT TO KNOW FROM YOU GUYS):
Does anyone know of any other options to solve this problem? If I have wrongly understood one of the options (WHAT I HAVE ALREADY TRIED section) above and you think there is a way to make them work, please let me know.
Answer: I found a solution to this problem. I create a multicast socket client-server system between the computer running the WAMP and the mobile device. The computer would behave as the server and the mobile device would behave as the client. Once the connection is established I get the ip address of the computer in the server-side code. Then I send the ip address as a string from the computer to the client (mobile device) through the multicast socket. Then the mobile device creates the proper URL to the specified webpage on the WAMP server using the ip address provided and loads that URL.
See this page http://docs.oracle.com/javase/tutorial/networking/datagrams/broadcasting.html for example code for the server client system.


Exibir mensagem de sucesso uma única vez em laço for

Question: Tenho o código:

 for ($i=0; $i < count($descricao); $i++) {

   $id_caixa_hoje = $linha['id_caixa_hoje'];
   $valor_formatado[$i] = abs($valor[$i]);

   $inserir = mysql_query("INSERT INTO caixa_valores_extras (id_caixa, valor, descricao, funcionario) VALUES ('$id_caixa_hoje', '$valor_formatado[$i]', '$descricao[$i]', '$id_sessao')") or die("Erro: ".mysql_error());

       if($inserir == true){

        echo "<meta http-equiv='refresh' content='0'>";

       } else {

        echo "<meta http-equiv='refresh' content='0'>";

       } // Esta chave fecha o  if($inserir == true){

        } // Esta chave fecha o laço for

Por exemplo, se em meu formulário eu repetir um determinado dado 3 vezes,

invés do php exibir a mensagem de sucesso apenas uma vez, ele exibe as três vezes.
Como posso fazer com que seja exibida uma única mensagem de sucesso ao fim do processo dos três INSERT's.
Answer: Exemplo - ideone
if ($i==(count($descricao)-1)){
   echo "<meta http-equiv='refresh' content='0'>";
}

Answer: Você tem que criar uma variável de controle (auxiliar), para ficar dentro do laço, e o IF que exibe a mensagem de sucesso deve sair do laço.
Answer: funciona tmb!

for ($i=0; $i < count($descricao); $i++) {

   $id_caixa_hoje = $linha['id_caixa_hoje'];
   $valor_formatado[$i] = abs($valor[$i]);

   $inserir = mysql_query("INSERT INTO caixa_valores_extras (id_caixa, valor, descricao, funcionario) VALUES ('$id_caixa_hoje', '$valor_formatado[$i]', '$descricao[$i]', '$id_sessao')") or die("Erro: ".mysql_error());

       if($inserir == true){

        $t =1;

       } else {

        $t=0;

       } // Esta chave fecha o  if($inserir == true){

        } // Esta chave fecha o laço for
        if($t==1){
echo "<meta http-equiv='refresh' content='0'>";
}
else {
echo "<meta http-equiv='refresh' content='0'>";
}


Copy SQL data from one server to another using c# threading

Question: I am new to Threading in c#, hence asking this question. Please correct me if i am wrong anywhere in my below question, it might be because of lacking of knowledge in C# threading.
I have an array (type of string) that contains all the Table Names (of SQL server), now I want to read data of these tables using sql query and write to another server. i can do it using synchronous programming, but this will take time. Can we do it using async/await or ThreadPool or Threading.
I want 4 (or 5) threads that can run parallaly and read the string array, collect table name and read the table data from sql server, post these activities this thread should create the table in my local server and write the data.
Comment: `Parallel.ForEach` with a `ParallelOptions.MaxDegreeOfParallelism` set to 4 or 5? However: this isn't a magic wand, and using 4 or 5 threads does not mean it will *necessarily* take 1/4 or 1/5 of the time - network bandwidth, IO bandwidth, and client and server CPU can all be bottlenecks. You'd also probably want to ensure you're using tools like `SqlBulkCopy`. But frankly, this sounds like something an off-the-shelf tool (or the inbuilt RDBMS tools) should be doing...
Comment: Use your existing code (you do have some right?  Your question says are only new to Threading in c#), and then use Parallel.ForEach over the array.
Comment: Can you show us your existing code?
Comment: Why not use replication of SQL Server?
Answer: Oracle has something called database link. Probably SQL server has something similar too. I would recommend creating a db link. Then you can select the data from the source server to target server just using sql query without loading it into your C# code. Meanwhile, you can use your app for submitting the queries to the db. You can do it concurrently, one query per thread and all the threads are doing is submitting the query and waiting for its completion.


Composer - Cannot update composer.json

Question: I'm trying to use the sonata-project/user-bundle in a new symfony project.
But I got this error when I do the update :
 composer require sonata-project/user-bundle
 Using version ^3.2 for sonata-project/user-bundle
 ./composer.json has been updated
 Loading composer repositories with package information
 Updating dependencies (including require-dev)
 Your requirements could not be resolved to an installable set of packages.

  Problem 1
- Installation request for sonata-project/user-bundle ^3.2 -> satisfiable by sonata-project/user-bundle[3.2.0].
- Conclusion: remove symfony/symfony v3.2.1
- Conclusion: don't install symfony/symfony v3.2.1
- sonata-project/user-bundle 3.2.0 requires symfony/form ^2.3 -> satisfiable by symfony/form[v2.3.0, v2.3.1, v2.3.10, v2.3.11, v2.3.12, v2.3.13, v2.3.14, v2.3.15, v2.3.16, v2.3.17, v2.3.18, v2.3.19, v2.3.2, v2.3.20, v2.3.21, v2.3.22, v2.3.23, v2.3.24, v2.3.25, v2.3.26, v2.3.27, v2.3.28, v2.3.29, v2.3.3, v2.3.30, v2.3.31, v2.3.32, v2.3.33, v2.3.34, v2.3.35, v2.3.36, v2.3.37, v2.3.38, v2.3.39, v2.3.4, v2.3.40, v2.3.41, v2.3.42, v2.3.5, v2.3.6, v2.3.7, v2.3.8, v2.3.9, v2.4.0, v2.4.1, v2.4.10, v2.4.2, v2.4.3, v2.4.4, v2.4.5, v2.4.6, v2.4.7, v2.4.8, v2.4.9, v2.5.0, v2.5.1, v2.5.10, v2.5.11, v2.5.12, v2.5.2, v2.5.3, v2.5.4, v2.5.5, v2.5.6, v2.5.7, v2.5.8, v2.5.9, v2.6.0, v2.6.1, v2.6.10, v2.6.11, v2.6.12, v2.6.13, v2.6.2, v2.6.3, v2.6.4, v2.6.5, v2.6.6, v2.6.7, v2.6.8, v2.6.9, v2.7.0, v2.7.1, v2.7.10, v2.7.11, v2.7.12, v2.7.13, v2.7.14, v2.7.15, v2.7.16, v2.7.17, v2.7.18, v2.7.19, v2.7.2, v2.7.20, v2.7.21, v2.7.22, v2.7.23, v2.7.3, v2.7.4, v2.7.5, v2.7.6, v2.7.7, v2.7.8, v2.7.9, v2.8.0, v2.8.1, v2.8.10, v2.8.11, v2.8.12, v2.8.13, v2.8.14, v2.8.15, v2.8.16, v2.8.2, v2.8.3, v2.8.4, v2.8.5, v2.8.6, v2.8.7, v2.8.8, v2.8.9].

- don't install symfony/form v2.3.4|don't install symfony/symfony v3.2.1
......
- don't install symfony/form v2.3.4|don't install symfony/symfony v3.2.1

- Installation request for symfony/symfony (locked at v3.2.1, required as 3.2.*) -> satisfiable by symfony/symfony[v3.2.1].

 Installation failed, reverting ./composer.json to its original content.

What is the next step when you got this kind of errors ?
Thanks
Answer: firstname.lastname@example.com is not compatible with firstname.lastname@example.com, which you also require in your composer.json.
You have 2 solutions:

Not using sonata-project/user-bundle
Downgrade symfony/symfony to a version that works with sonata-project/user-bundle. The version needs to be ^2.3.

Composer - Cannot update composer.json


Por que não consigo capturar o KeyEvent nesse meu programa ? problemas está no main?

Question: #include<QApplication>
#include<tabuleiro.h>
#include<jogador.h>
#include<QWidget>

int main(int argc, char* argv[]){

QApplication app(argc, argv);

QWidget window;
Tabuleiro t(&window);
Jogador j(&window);

window.show();

return app.exec();
return 0;
}

Classes:
#include<tabuleiro.h>
#include<QPainter>
#include<iostream>

using namespace std;

Tabuleiro::Tabuleiro(QWidget* parent)
: QWidget(parent){

layout = new QVBoxLayout();

gerarTabuleiro(1);
repaint();
setFixedSize(960,560);
setLayout(layout);

show();

}

void Tabuleiro::gerarTabuleiro(int modo){

x=0;
y=0;
w=40;
h=40;

switch(modo){

case 1 :

 for(int x = 0;  x<14 ; x++){
        for(int y = 0 ; y<12 ; y++){
            tabuleiro[x][y] ='1';
        }
    }

 for(int x = 0;  x<14 ; x++){
        for(int y = 12 ; y<24 ; y++){
            tabuleiro[x][y] ='0';
        }
    }

 break;

}

}

void Tabuleiro::draw(){
repaint();
}

void Tabuleiro::paintEvent(QPaintEvent *event){
QWidget::paintEvent(event);
QPainter painter(this);
painter.setPen(Qt::gray);

for(int c = 0 ; c<14 ; c++){

    for(int l = 0 ; l<24 ; l++){

        if(tabuleiro[c][l]=='1'){
            painter.setBrush(Qt::black);

        }
        else{
         painter.setBrush(Qt::white);
        }

        painter.drawRect(x,y,w,h);

        x+=40;

    }
    x=0;
    y+=40;
 }
y=0;

}
O meu problema que não estou conseguindo captura o event ode teclado.
Comment: Quando você diz que "não consegue" é porque está obtendo um erro ou porque não sabe como fazer? Você já chegou a tentar reimplementar o método [`keyPressEvent`](http://doc.qt.io/qt-5/qwidget.html#keyPressEvent) na sua classe `Tabuleiro`?
Comment: Já reimplementei, mas na execução do aplicativo não chama o método.
Comment: Implementou onde, como? Não está no código que você compartilhou.
Answer: Você precisa incluir a classe QKeyEvent e reimplementar a função void keyReleaseEvent(QKeyEvent* event), para que seus eventos do teclado sejam reconhecidos.


When is multiple voices necessary for guitar standard notation?

Question: I've been transcribing music in Guitar Pro, and found that working with two 'voices' (bass/treble) on the staff is rather difficult. It's time consuming to say the least.
My question is: when is having both voices necessary, as opposed to just using ties? Obviously at some point, you have to draw the line; for example, tying 8 eighth notes together can get annoying.
I have attached two examples from a tune I'm working on. Would you say that this particular notation is ridiculous or permissible? Does having the tab below justify the standard notation, or is it just plain ridiculous/sloppy to the seasoned reader?  I understand that there may not be an objective rule for this-or maybe there is- but hopefully I can get some opinions or perhaps advice from more seasoned readers out there. Thank you
Example 1:

Examples 2:

Of the following, which would you prefer:
Answer: I would much prefer to play from a score which had the absolute minimum of ties, such as in either of the first two examples you give.
I would find it much easier to follow the musical intent of a score written more like this:

This could have been written with lots of ties, but I think this version is clearer.
Unfortunately, I have no knowledge of Guitar Pro, so I am unsure exactly how this could be achieved.
EDIT: Example 3 (the part with more rests and less ties) would be greatly to be preferred in my experience.
Comment: The fewer black marks on the page, the better. On guitar, how long you can sustain a note is often a matter of technique (i.e. how long can you use a finger to fret a string before moving it) and how long the note will sustain anyway, so lots of ties often give a spurious sense of "accuracy" to the notation. IMO the ideal situation is that every written note indicates the *start* of a note that is actually *played*, but the accurately notating the *end* of notes is not so critical. Tab doesn't have any explicit notation at all for when notes end, but tab works fine as a *practical* notation.
Comment: I have added a bit to my answer. Give me rests rather than ties, any day. I suspect I am not alone, at least amongst classical guitarists, but I may be wrong ...
Comment: Appreciate the response.
Comment: Old John, I added another example to my org. question. In this one, the ties seem, in my eyes, to be easier to read. Do you still prefer less ties still, compared to more complex rests? Thanks for any insight....
Comment: Absolutely agree, and the older I get, the more I like fewer black marks on the score ...
Comment: Appreciate the responses!


Laravel no servidor Locaweb: Unexpected character in input: '\' (ASCII=92) state=1

Question: Estou hospedando na Locaweb e está dando este erro.

Warning: Unexpected character in input: '\' (ASCII=92) state=1 in
  /home/storage/a/b7/b3/reciclaoleovegetal/public_html/public/index.php
  on line 52
Parse error: syntax error, unexpected T_STRING in
  /home/storage/a/b7/b3/reciclaoleovegetal/public_html/public/index.php
  on line 52
Comment: Qual a versão do Laravel e qual a versão do PHP no teu locaweb?
Comment: @GuilhermeNascimento php está rodando o 7.1 é o laravel está na última versão 5.4
Answer: Mensagens como:
Warning: Unexpected character in input: '\' (ASCII=92) state=1

E:
Parse error: syntax error, unexpected T_STRING

Indicam duas possibilidades, ou você editou algo que não devia e quebrou o script, ou você esta usando versão mais antiga do PHP que não suporta o Laravel.
Pela mensagem Unexpected character in input: '\' você deve estar usando PHP 5.2, pois namespaces só funcionam a partir do 5.3
Mas é importante saber que o uso de ::class, que esta na linha 52 do index.php não funciona no nem no PHP 5.3:
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
Pra ter certeza da versão crie um arquivo chamado info.php na public_html e adicione isto:
<?php
echo 'Versão Atual do PHP: ' . phpversion();

Ele vai exibir os detalhes da versão do teu PHP, então terá certeza se é o 7.1, acaso for de fato o 7.1 então significa que ou você danificou o index.php ou foi falha no upload.
Se a versão estiver correta e o index.php estiver assim:
<?php

define('LARAVEL_START', microtime(true));

require __DIR__.'/../vendor/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);

Então o problema é no upload, se estiver usando Filezilla, talvez o teu FTP esteja quebrando algo ao tentar subir como ASCII, para que não perca dados faça o upload como binário, por exemplo no Filezilla vá em:
Transfer > Transfer type > e troque Auto por Binary
Como na imagem:

Então faça o upload novamente.
Comment: consegui resolver, o problema era na hospedagem, sempre que fazia a instalação do laravel via composer, a versão do php era alterada de 7.1 para 5.2, então era preciso alterar novamente a versão do php, só descobri graças aos posts
Comment: Então, a versão do PHP é a 7.1, e ainda não alterei nenhum Script, fiz a instalação pelo composer e já apareceu este erro
Comment: @RobsonRodrigues veja a edição da resposta, se for de fato o 7.1 me confirma que eu tenho outra sugestão pra ti.
Comment: @RobsonRodrigues pela mensagem `Unexpected character in input: '\'` com certeza você esta usando PHP 5.2, isso porque no php5.2 ainda não existiam namespaces.
Comment: @RobsonRodrigues por favor então marque a resposta como correta, se não souber como leia: https://pt.meta.stackoverflow.com/a/1079/3635 - Obrigado!


Proving Handshake Theorem.

Question: I am currently learning Graph Theory and I've decided to prove the Handshake Theorem which states that for all undirected graph,
$$\sum_{u\in V}\deg(u) = 2|E|\ .$$
At first I thought the theorem is very intuitive so proving it would be easy. But then I've realized that my intuition to the theorem cannot be translated to the writing of the proof; describing how it works is easier than formalizing it into a series of logical steps that would prove the theorem. Anyway, I've tried my best but I think my proof is very clunky and too verbose so I want to ask if it is correct or maybe suggestions on writing proof in general.
Proof
Let $G = (V,E)$ be an undirected graph. We want to count the sum of the degree of vertices of $G$ so, for the sake of proving an argument, we let $$\sum_{u\in V}\deg(u) = 0 \ ,$$ i.e. we set the degree of all vertices to zero and only then will we increment the $\deg(u)$ if $u$ is incident to $e_i \in E$.
Let $e_1$ be the first edge we choose. $e_1$ is incident to $v_j,v_k \in V$ and hence we increment each of their degree by one, so $\deg(v_j) = 1 = \deg(v_k)$. Note that if $v_j = v_k$, i.e. $e_1$ is incident to only one vertex (often called a 'loop'), then the degree of that vertex would be incremented by two. For $m = |E|$, we do the same process to $e_2, e_3,\dots,e_m$, incrementing the degree of the vertices incident to an edge. We will notice that for every edge, we increment the total degree of $V $ (or $ \sum_{u\in V}\deg(u)$) by two and since there are $m$ edges, we incremented the initially zero-valued total degree of $V$ by $2m = 2|E|$.
Hence,
$$\sum_{u\in V}\deg(u) = 2|E|$$
is proved to be true. $\ \blacksquare$
Comment: "*we set the degree of all vertices to zero and only then will we increment...*"  Uh... I wouldn't phrase it that way at all.  You can maybe say "let us calculate $\deg(u)$ for each $u$ by ..." but we aren't *changing* or *setting* the value of $\deg(u)$.
Comment: You seem to be using the proof styles of "proof by contradiction" and "proof by induction" when in fact you are not using either. You are giving a direct proof, as is needed in this case. So as @JMoravitz noted, you should start with the facts given to you -- the actual degrees of vertices. Show how an edge is equivalent to a degree contribution of 2. And build up from there.
Answer: As you mentioned, the difficulty in proving this formally is that we humans intuitively "see" the bijection needed. The arguing of user598858 will be accepted in most cases, but if you look for a more formal proof, I'll give you one.
First assign an orientation to $G$, i.e. make each edge directed, i.e. assign two functions $s,t:E\rightarrow V$ such that vertices $v$ and $w$ are adjacent if and only if there is an edge $e$ such that ($s(e)=v$ and $t(e)=w$) or ($s(e)=w$ and $t(e)=v$). If $E$ is a subset of the two-element-sets of $V$ in your definition, this is equal to $e=\{s(e),t(e)\}$.
Let $\mathcal P(X)$ denote the power set of a set $X$. Next we define $O:V\rightarrow\mathcal P(E\times\{0\})$ by $O(v) := \{(e,0): s(e)=v\}$ and $I:V\rightarrow\mathcal P(E\times\{1\})$ by $I(v) := \{(e,1): t(e)=v\}$. Observe that $O(v)$ represents all edges starting in $v$ and $I(v)$ represents all edges ending in $v$, so especially we have for a loop $\ell$ in $v$ that $(\ell,0)\in O(v)$ and $(\ell,1)\in I(v)$, i.e. loops are in both the outgoing and the incoming edges. So we observe that $$\operatorname{deg}(v)=|O(v)\cup I(v)|=|O(v)|+|I(v)|,$$ since $O$ and $I$ were designed to be disjoint.
Now observe that for any vertices $v,w$ with $v\neq w$ we have $I(v),O(v),I(w),O(w)$ all mutually disjoint. Proof: Again the disjointness of $I$ and $O$ is clear because of the second coordinate. Assume that $(e,0)\in O(v)\cap O(w)$, then by definition we have $v=s(e)=w$, a contradiction, so $O(v)$ and $O(w)$ are disjoint. Analogue reasoning shows that $I(v)$ and $I(w)$ are disjoint.
Since they are mutually disjoint, we have
$$\begin{aligned}
\left|\bigcup_{v\in V} O(v)\right| &= \sum_{v \in V} |O(v)|\\
\left|\bigcup_{v\in V} I(v)\right| &= \sum_{v \in V} |I(v)|
\end{aligned}$$
Next we have
$$\begin{aligned}
E\times\{0\} &= \bigcup_{v\in V} O(v) \\
E\times\{1\} &= \bigcup_{v\in V} I(v)
\end{aligned}$$
"$\subseteq$": Simply because by $s$ and $t$ an edge $e$ gets assigned to (only) $O(s(e))$ and (only) $I(t(e))$. "$\supseteq$": Since $O(v)\subseteq E\times\{0\}$ for any vertex $v$, the same holds for their union. Analogue with $I(v)\subseteq E\times\{1\}$.
We conclude
$$\begin{aligned}
2|E|&=|E\times\{0\}|+|E\times\{1\}| \\
&= \left|\bigcup_{v\in V} O(v)\right| + \left|\bigcup_{v\in V} I(v)\right| \\
&= \sum_{v \in V} |O(v)| + \sum_{v \in V} |I(v)| \\
&= \sum_{v \in V} |O(v)\cup I(v)| \\
&= \sum_{v\in V} \operatorname{deg}(v)
\end{aligned}$$
Answer: One line proof: Each edge gives one degree to its each end points and for a loop on a vertex, it provides $2$ degree to the vertex so $2\times |E|= \text{degree sum}$.

Proving Handshake Theorem.


How string isomorphism is used in graph isomorphism?

Question: Graph isomorphism is a special case of string isomorphism problem. In the paper of Graph Isomorphism in Quasipolynomial Time,  the relation has been shown. Let,  two strings $x,y$ are associated with graphs $A, B$ (each has $n$ vertices) respectively. If there exists a permutation $\pi \in S_n$ (symmetric group of $n$ vertices), so that $x^{\pi}=y$,  it implies that $A^{\pi}=B$, i.e. graphs $A, B$ are isomorphic.
In the paper, the definition of string isomorphism is written on page 24 - $\newcommand{\Iso}{\operatorname{Iso}}\newcommand{\Aut}{\operatorname{Aut}}$

Definition 3.2 (String Isomorphism Problem).
Input: a set $\Omega$, a finite alphabet $\Sigma$, two strings
$x, y :\Omega → \Sigma,$ a permutation group $G ≤ S(Ω)$ (given by a list of
generators)
Output: The set $\Iso_G(x, y)$. If this set is nonempty, it
is represented by a list of generators of the group $\Aut_G(x)$ and
a coset representative $\sigma \in \Iso_G(x, y)$.

here,  $G$ is an arbitrary sub-group of $S(Ω)$ (see [this][2]). What  happens if  $\Iso_G(x, y)$ is empty?
If  $\Iso_G(x, y)$ is empty, then there might be $H > G$ where $\pi \in H$ and $\pi$ is an isomorphism. So,  $\Iso_G(x, y) = \emptyset$ does not imply $A, B$ are not isomorphic. In this case, what is the next step?
In general, why an arbitrary group $G$ is enough to check
graph isomorphism?
Answer: It sounds like you're somehow confused about which way the reduction goes and/or who gets choose $G$.
Someone who claims they have a solution to your "string isomorphism problem" must be able to handle every possible subgroup we throw at them. That's what it means to say that the group is arbitrary.
In particular if you're trying to solve the usual graph-isomorphism problem with the help of a string-isomorphism solver, having freedom to choose a group yourself makes your job easier. It means that you can construct a subgroup to represent exactly all of the possible permutation of the vertices in your graph, and then the string-isomorphism solver has to work with the group you constructed.
The group $G$ is part of the input to the string-isomorphism problem. Having a wide variety of possible inputs makes it (potentially) more difficult to find a general solution to the problem, but on the other hand makes it easier to use a solver as a tool for solving other problems.
So asking "why is an arbitrary group enough to check graph isomorphism" is fundamentally misunderstood. The more groups you have to choose between, the better the chance that the one you need in order to check a graph isomorphism. And when you get a free choice between all of them, as you do here, you can be sure that the group you need will be supported.
Comment: @MikeSQ: Why would you do that? **As the user of the string-isomorphism solver, YOU get to choose dictatorially which group you ask it about**. If it answers that there is no isomorphism between the strings you have constructed form your graphs, using the group you have constructed from the graphs together with the strings, then you already know that the graphs are not isomorphic -- no need to do anything more. The string-isomorphism solver is not going to get its feelings hurt just because you don't keep running it until it can answer "yes" to something.
Comment: Do you mean every subgroup of $S_n$ when you write every posible subgroup? then if $ISO_G$  is  empty we take another group $H$ where $G <H$ and run the same routine/algorithm and keep doing it untill we find a non empty $ISO_G'$  set ?
Comment: I have started  reading the paper in detail. I get the imprssion from your above comment that the $G$ is constructed ( 'using the group you have constructed from the graphs together with the strings' ),probably during some process. If you meant this, then see The Master Algorithm on page 74,  I see  no construction of $G$.  Can you tell me, how  $G$ is choosen/constructed ?If this is  not what you meant, then If  $Iso_G(x, y)$ is empty, there might be $H$ such that $G<H$ where $\pi \in H$ and $\pi$ is an isomorphism. So,  $Iso_G(x, y) = \emptyset$ does not imply $A, B$ are not isomorphic.
Comment: @MikeSQ: Do you mean page 78? What starts there is an _algorithm for solving the string-isomorphism problem_. It gets $G$ (as well as $x$ and $y$) as inputs. What I have been talking about is something else: a **reduction from graph-isomorphism to string-isomorphism**, which takes two graphs as input and produces $x$, $y$ and $G$ as output.
Comment: In other words, what I'm talking about -- and what I thought you were asking about -- is how the paper's Corollary 1.1.2 follows from Theorem 1.1.1. The paper does not seem to contain an explicit proof, perhaps because the author considered it trivial: Given two graphs both with k
nodes, let x and y be representations of their adjacency matrices, and let G be the group of permutations that permute the rows and columns of the adjacency matrices equally. Then this particular G contains a σ such that σ(x)=y exactly if the graphs are isomorphic.
Comment: Thanks for your feedback. I am sorry  about the vagueness of my query. I know how GI is reduced into SI. My questions are - (1) how is group $G$ constructed ? (2) how  group $G$ is initiated in the algorithm .  Can you shed some light on that?  It appeared to me that the algorithm was  started with a subgroup of $S_n$, and it is choosen randomly.
Comment: @MikeSQ: I'm afraid I'm more confused than ever about what you're actually asking, then. As far as I can see, (1) $G$ is constructed as part of the reduction from GI to SI, which you say you already understand, and (2) $G$ is explicitly an _input_ to the master algorithm on page 78, so that's where it comes from. It says so right after the "Procedure String-Isomorphism" heading: $$\text{Input: group }G\le\mathfrak S(\Omega)\text{, strings }\mathfrak x,\mathfrak y: \Omega\to\Sigma $$ It is not clear to me why you think it would be chosen randomly.


custom serialization data on laravel

Question: this is my first post. I have a problem with my Laravel application.
I need to modify the serialization of the data for my endpoint to get the data of a specific bike.
The endpoint return this:
{"bike":{"id":32,
         "unlock_code":2342,
         "rack": {"id":3,
                  "available_stands":10,
                  "latitude":"46.754",
                  "longitude":"8.5732",
                  "available_bikes":10
                },
        "bike_state":{"description":"Available"}
        }
}

but i want to have this:
{"bike":{"id":32,
         "unlock_code":2342,
        "rack":{"id":3,
                "available_stands":10,
                "latitude":"46.754",
                "longitude":"8.5732",
                "available_bikes":10
                },
        "bike_state":{"Available"}
        }
}

the field name ('description') must be hidden. It's the first time i use laravel and i don't know if it's possible to do this.
This is the model
class BikeState extends Model
{
    protected $hidden = ['id'];

    public function bikes()
    {
        return $this->hasMany('App\Bike');
    }
}

this is the repository with the method to retrieve the data:
class BikeRepository
{
    public function findBikeById($id)
    {
    return Bike::with('rack','bikeState')->findOrFail($id);
    }
}

and this is the controller
class BikeController extends Controller
{
     private $bikeRepository;

     public function __construct(BikeRepository $bikeRepository)
     {
          $this->bikeRepository = $bikeRepository;
     }

     public function getBike($id)
     {
          return response() ->json(['bike' => $this -> bikeRepository ->
          findBikeByid($id)], 200);
     }
}

Thank you
Comment: **You cant** As what you want is invalid JSON
Comment: please full code
Comment: @SergeyB. i added the code
Answer: Create an accessor on your Bike model like this:
public function getBikeStateAttribute($value)
    {
        return json_encode($this->attributes['description']);
    }

Then add accessor to Bike model's array like this:
protected $appends = ['bike_state'];

custom serialization data on laravel


How to revert back to Desktop website from Mobile Website when using CSS Media Queries?

Question: I'm using CSS media queries to create a responsive theme. I want to add a link at the footer of the website labeled "GO TO DESKTOP WEBSITE". This link will specifically be displayed on the mobile devices. How can I do it so that when a visitor click on the desktop website link, the website is loaded with desktop media query, not of mobile. I hope I've made myself pretty clear on my issue. I've searched on Google for the solution but can not find anything related.
Answer: You unload your responsive.css file using:
document.getElementsByTagName('link')[0].disabled = true;

for example you might have:
<link rel="stylesheet" href="base.css" type="text/css" id="css_base" />
<link rel="stylesheet" href="responsive.css" type="text/css" id="css_responsive" />

then you can have:
Show Full site

$("#site_view").click(function() {
   $("#css_responsive").prop("disabled", true);
});

Here's a quick example: http://jsbin.com/elukab/1 (just minimize the browser window)

or
you can redirect the user to a new URL where you specify that you want the mobile version off, for example:
$("#site_view").click(function() {
   document.location = document.location.href + '?mobile=off';
});

and with your dynamic language, just read the query string and don't load the responsive styles, as I'm a .NET developer, I would do:
<link rel="stylesheet" href="base.css" id="css_base" />
@if(Request["mobile"] == null || Request["mobile"] != "off") {
    <link rel="stylesheet" href="responsive.css" id="css_responsive" />
}

Comment: Well what language is it in the end, which starts with `@if`?
Comment: As I specified, I'm a .NET Developer, for such that's [ASP.NET MVC](http://www.asp.net/mvc) with [Razor View](http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx) :) - You apply what language you use, PHP, Java, RubyOnRails, etc ... or you can do it the same with javascript as well.
Comment: I guessed it would have been a RazorView, but the question is tagged just for CSS Media Queries. :)
Comment: and I did answer that ... in the first part of my answer, together with the example link is exactly what you can and should do... the second part is to be more creative ...


Converting Decimal to String to Decimal

Question: I copied this code from another post.  I tried the example, however, I am getting a EXEC_BAD_ACCESS.  From what I have read, this error happens when trying to use an object that has been deallocated, but I just don't see where I am doing that:
The call
...
float weighted_average = num_of_passes / total_of_all_passes;
NSString *newNumber = [[NSString alloc] init];
newNumber = [self formattedStringWithDecimal:weightedAverage]; //weighted average (float) = 15.875145

...
The Function
- (NSString *)formattedStringWithDecimal:(NSDecimalNumber *)decimalNumber
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setMaximumFractionDigits:2]; //two deimal spaces
    [formatter setRoundingMode: NSNumberFormatterRoundHalfUp]; //round up

   NSString *result =[NSString stringWithString:[formatter stringFromNumber:decimalNumber]];
    [formatter release];
    return result;
}

Comment: NSZombieEnabled will not prevent a crash, but gives you information about what deallocated object was used.
Comment: Can you post the error message? Enable NSZombieEnabled for your executable first.
Comment: And how is formatterstringFromNumber defined? I am not able to run the code. Please add the code. How is weightedAverage initialized?
Comment: that should have read: [formatter stringFromNumber
Comment: I have enabled NSZombie but the program still crashes.
Comment: Both your initialization of `newNumber` and your use of `stringWithString:` are unnecessary. You don't need to initialize a variable to hold a pointer to one object before you put a pointer to a different object in it, and since you didn't release the object you initialized the variable with, you leaked it. Since you're not using that initial string at all, cut it out and simply initialize the variable with the object returned by `formattedStringWithDecimal:`.
Comment: As for `stringWithString:`, when you're passing it a string, you already have a string, so you generally don't need to create another string with it. When you're not passing it a string, that's a mistake; you must pass it a string. The only time it's worth using is when going from mutable to immutable (e.g., when you build a string as a mutable string and then want to return an immutable string) or vice versa. Basically, whenever you would use `copy` or `mutableCopy` but want an exception when the string to copy is `nil`. Whenever you don't need a copy, just use the string you have.
Comment: Also, the Zombies template in Instruments is far better than NSZombieEnabled, since you can look back over the entire history of the zombie object. With NSZombieEnabled, you can only examine the present; Instruments lets you look at the past and the present.
Answer: Call the method like this:
newNumber = [self formattedStringWithDecimal:[NSDecimalNumber numberWithFloat:15.434]];

You've tried to pass a primitive, but the method expects an object: an NSDecimalNumber. You've got to use the static convenience method numberWithFloat to create an object of that type.
And by the way, I have the feeling that
newNumber = [NSString stringWithFormat@"%.2f", 15.434];

could achieve the same result with less lines of code. Note this will not round up your number though.
Answer: You are returning an autoreleased object. Does the function that uses it retain it? If not, it could be released and then later (later run loop) its trying to be (re)used. Agreed on the enabling zombies to spot that kind of thing.

Converting Decimal to String to Decimal


Compute $\delta(\sin{x})$

Question: I would like to show that $$\delta(\sin{x})=\sum_{n=-\infty}^{\infty}\delta(x-n\pi),$$
where $\delta(x)$ satisfies the relation $$\int_{-\infty}^{\infty} \delta(x-a)\phi(x) \, dx =\phi(a),$$ for some test function $\phi$.
The $n\pi$ term makes it clear that at some point I need to be considering the roots of $\sin{x}$, but aside from that, I'm not sure what to do.
Comment: Depends on what you are allowed to assume here.  You might want to take a look at https://math.stackexchange.com/questions/276583/dirac-delta-function-of-a-function and substitute in $\sin x $ for $f(x)$ there.
Comment: What's the _definition_ of $\delta(\sin(x))$ Saying $\int_{-\infty}^{\infty} \delta(x-a)\phi(x) \, dx =\phi(a)$ doesn't tell me what $\delta(\sin(x))$ is...
Answer: HINT
You should read this, but the idea is basically
$$
\int _{-\infty }^{\infty }f(x)\,\delta (g(x))\,dx=\sum _{i}{\frac {f(x_{i})}{|g'(x_{i})|}}.
$$
where $x_i$ are roots of $f$, that is $f(x_i) = 0$. Call $g(x) = \sin(x)$, so that $x_i = i \pi$

Compute $\delta(\sin{x})$


On which thread do Async Callbacks run?

Question: I'm making several HttpWebRequest.BeginGetResponse calls, and in the callback method of the BeginGetResponse, I'm invoking an EventHandler.  In the EventHandler, there is logic to test if the download was successful.  If not, it tries to redownload the Html.  I'm noticing lots of threads being generated especially when there are errors. So, on which thread do the Async Callbacks run?
Is there anyway I can invoke the EventHandler on the original thread?  If that is not posible, can I invoke it on the UI thread?
Thanks!
Answer: What do you mean by "on the original thread"? Which original thread? You can marshal to the UI thread using Control.BeginInvoke or Dispatcher.BeginInvoke. You can't marshal to an arbitrary thread - it has to have something like a message pump waiting for work.
As for which thread HttpWebRequest async callbacks are executed on - I would expect either a general thread pool worker thread, or possibly an IO completion port thread.
Comment: "on the original thread" being the thread from where the `HttpWebRequest.BeginGetResponse` is called. So, for example, if the UI spawns a thread A and A calls `HttpWebRequest.BeginGetResponse` (which as you said, puts a new thread in the thread pool.  We'll call it thread B) and then the EventHandler is invoked, I want it to run on thread A or the UI thread.  But from what I've been observing it runs on thread B.  Then, if there is an error, thread B calls `HttpWebRequest.BeginGetResponse` which then creates thread C and so on...  Hope that helps
Comment: @joe_coolish: Why would it run on thread A, and why would you care? What would you expect to happen if thread A is still executing some other code? I'm not at all sure what you mean by BeginGetResponse "putting a new thread in the thread pool" though... or why thread B is calling BeginGetResponse again... is that in your own code? The thread pool will reuse threads when possible of course.
Comment: The reason I care is because I'm getting OOMEs because the thread pool is too big. My code (which is where the real problem lies I'm sure) has 2 methods. 1 accepts a URL and an EventHandler Callback.  It creates the HttpWebRequest object and calls the BeginGetResponse.  Method 2 is the AsyncCallback and if the call errors out it makes a call to method 1 passing the URL and the EventHandler. The problem is that every call from method 2 to 1 generates a new thread and keeps the original thread active so if I start downloading 6 things and each errors out 6 times I now have 36 threads in the pool
Comment: If my design/logic is the problem, my end goal is download HTML from a URL and when it's done, call an event handle.  The downloader needs to have the ability to retry the download X number of times, where X is a constant int.  I also wanted to thank you for your help, and apologize for any errors on my part.  If anything, you can get a good laugh from it :)
Comment: @joe_coolish: How many threads do you *actually* have in the thread pool by the time it goes wrong? The thread pool really should be reusing the threads when it can - I doubt that it's actually spiralling out of control... unless you're in the situation where it's returning an error *really quickly* and you're *always* retrying (i.e. if your counting isn't working). How much memory does your machine have? While threads are *somewhat* expensive, you'd need a lot of them before you ran out of memory on most machines.
Answer: Callbacks are made on a threadpool thread.  There is no mechanism in .NET to make code run on a specific thread.  That is very hard to come by, you can't just interrupt a thread while it is busy and make it run some code.  That causes horrible re-entrancy problems that a lock cannot solve.
A thread must be in an idle state, not actively mutating the state of the program.  There's one kind of thread that behaves that way, the UI thread in a Winforms or WPF app.  That's also the thread that has to deal with objects that are fundamentally thread-unsafe, anything related to the UI.  This is not a coincidence.
Both class libraries make it possible to marshal a call from a worker thread to the UI thread, specifically to help getting the UI updated in a thread-safe way.  In Winforms you use Control.Begin/Invoke(), in WPF you use Dispatcher.Begin/Invoke().  BackgroundWorker is a handy class to get this done without explicitly managing the marshaling.  But isn't suitable for I/O completion callbacks.
Comment: EventHandlers are just code - when you call one, the handlers subscribing to the event are run on the calling thread; there's no transition, no magic.
Comment: Invoke() runs on the same thread, BeginInvoke() runs on a tp thread.
Comment: Ok, so the Callbacks are made on a thread in the threadpool.  So, if on a threadpool thread I invoke an EventHandler, which thread will it run on?
Comment: Thank you!  One last dumb question.  If I call Invoke on the EventHandler, will it run on the UI thread?
Answer: Using the Begin/End Async pattern, be aware that it's possible for many kinds of tasks to complete on the thread they were called from.  When you call BeginXXX, it returns a boolean that signifies if the task was completed on the calling thread or not.
The basic answer is, it could be any thread.
Comment: Thank you, I am beginning to find that this is infact the case.  I just now need to get my logic straightened out and I'll be good!
Answer: If you are using WPF you can use the Dispatcher to invoke your logic on the UI thread.
Otherwise, (if not in WPF) you could use a SyncrhronizationContext to accomplish the same thing.

On which thread do Async Callbacks run?


Get the latest updated value in R

Question: I would like to make another question following this (Get the latest updated value based on other columns) since my question might not be clear.
Initially, I have 2 dataframes in which one contains NA value in column name2, and the other contains NA value in column name1. Then, I used bind_rows to get one big dataframe as example here. The column name3 is the combination of name1 and name2.
name1               name2                  name3
Acer laurinum        NA                     Acer laurinum
Acmella paniculata   NA                     Acmella paniculata
Aglaia lawii         NA                     Aglaia lawii
............         NA                     ...................
NA                   Acer laurinum Hassk.   Acer laurinum Hassk.
NA                   Aglaia lawii (Wight)   Aglaia lawii (Wight)
NA                   ....................   ....................

As you can see, several names in column name3 missing the author part. That why I would like to update those names based on either the column name2 or name3.
Any suggesstion for me using tidyverse?
Code for example
df <- data.frame(
name1 = c("Acer laurinum", "Acmella paniculata", "Aglaia lawii", NA, NA),
name2 = c(NA, NA, NA, "Acer laurinum Hassk.", "Aglaia lawii (Wight)"),
name3 = c("Acer laurinum", "Acmella paniculata", "Aglaia lawii", "Acer laurinum Hassk.", "Aglaia lawii (Wight)"))

My desired output
name1               name2                  name3
Acer laurinum        NA                     Acer laurinum Hassk.
Acmella paniculata   NA                     Acmella paniculata
Aglaia lawii         NA                     Aglaia lawii (Wight)
NA                   Acer laurinum Hassk.   Acer laurinum Hassk.
NA                   Aglaia lawii (Wight)   Aglaia lawii (Wight)

Comment: Ok, I think i had a confusion with your expected.  I thought `name3` was not present in the data
Comment: oh, i see. I did create a vector of good name before and then I used `lapply` to bind the author name, like this post. (https://stackoverflow.com/questions/68637196/extract-components-of-strings-and-fill-down-where-missing-in-r). However, some cases when I matched going wrong, then I think that might be not a good option
Answer: You could do something like this:
The idea:

bring data in long format
create a helper column with the first word of the names using word from stringr
group by helper and mutate value with the last of the group
bring back to wide format

library(dplyr)
library(stringr)

df %>%
  mutate(id = row_number()) %>%
  pivot_longer(
    cols = -id
  ) %>%
  mutate(helper= word(value, 1)) %>%
  group_by(helper) %>%
  mutate(value= last(value)) %>%
  pivot_wider(
    names_from = name,
    values_from = value
  ) %>%
  ungroup() %>%
  select(-id, -helper) %>%
  filter(if_any(everything(), ~ !is.na(.)))

  name1                name2                name3
  <chr>                <chr>                <chr>
1 Acer laurinum Hassk. NA                   Acer laurinum Hassk.
2 Acmella paniculata   NA                   Acmella paniculata
3 Aglaia lawii (Wight) NA                   Aglaia lawii (Wight)
4 NA                   Acer laurinum Hassk. Acer laurinum Hassk.
5 NA                   Aglaia lawii (Wight) Aglaia lawii (Wight)

Comment: thank you so much. It worked well here. However, something weird happened when I ran for my data. The row was not the same anymore, it was increased by some reasons. For example, several unique row with good solution for `name1`  and `name3` splited to 2 different rows
Comment: Maybe you could create this as a new question. It seems worth to handle it!
Comment: thank you. Problem happend when we created the `value` column, some how the `id` matching wrong name. I will create a new topic

Get the latest updated value in R


ftp client multi user

Question: I cannot find anything on point so here goes.   We need to ftp a single file three times a day.  Different users need to be able to share the client.
I tried WinSCP but it seems to store the configs on each user's profile.  I cannot put a shortcut to the site in the Public profile and allow any user logged into the workstation access to make it work.   WinSCP mentions copying the .ini file for each user but I am wondering if there is another option.  I don't want to have to try to remember to set this up when I get new users every year - amongst all the other setups we have to do.
Filezilla is another big name - will I have the same problem with that or will it allow multiple users access to the same app/site.
I really just need a very simple,free GUI interface which all users will be able to use without extra configuration.   And it only goes to a single sftp site.  I like the drag and drop offered by WinSCP - again simple.  Am I off base or is this possible?   My users are NOT all tech friendly so the fewer steps the better.   If there is a CLI way to do that I might even try and ask a tech to script a task to run automatically.
This is all brand new to me and I am doing lots of reading but am not even sure of the questions I need to ask yet!
Comment: Is the file the same filename or variant thereof? It might be easier to set up a script to perform the action to transfer the file and you can define the options required in parameters or options or batch file.
Answer: I seem to have resolved my own question by a little trial and error.  I tried Filezilla but it didn't seem to want to share the config between users either.  There is an option while setting up both to allow only a local account or all users but this seems to only allow all users to use the app, not share a common config.
I will probably follow up on the scripting option - yes the file name is a slight variant every time it is created - same file name with the current timestamp appended.  I need to have it in place immediately so for now I copied the WinSCP.ini file from my AppData/Roaming folder to all the other users' AppData/Roaming profile folders.  I had several other users log on and it brought over the config data I had originally set up and allowed them to work with the correct site.

ftp client multi user


Training and Influences of J. S. Bach

Question: Johann Sebastian Bach is undoubtedly among the most celebrated of Baroque composers, and to many the great composer in all history. The era of the late 17th and early 18th centuries in which he lived, however, means that his life was not as well documented as (say) Beethoven's was.
In particular, I am interested in the following points relating to his musical career and pursuits:

Bach came from a family of notable amateur and professional musicians. Was he exposed greatly to instruments/musical theory/composition at a young age?
What sort of formal training and musical education did Bach undergo?
Was he self-taught in one or more areas of theory/composition/performance?
Bach's style is often said to blend North & South German with Italian (and even French) styles to varying degrees. Did any in particular dominate him? How did he acquaint himself with such a wide range of music at the time?
Which contemporary/past composers did Bach most admire, and which influenced his own music most? (I am aware he transcribed many of Antonio Vivaldi's pieces, and was also familiar with Buxtehude's work.)

How much do we know about these things? Or if little, does anyone perhaps have any educated opinions in these respects?
Comment: I highly recommend Christoph Wolff's *Johann Sebastian Bach: The Learned Musician*(2000, W.W. Norton). Very enjoyable read and outstanding biography. In regard to your questions about his training, the first three chapters address this very well.
Answer: About his development as a composer and the links with his 2 older brothers Johann-Christof and Johann-Jacob.
Yes JS was exposed very early to music, music practice and various instruments. He and his brothers were expected to master various instruments and to play ex tempore and generally become proficient in the family's trade, go to other members of the family who could help them secure jobs and teach them new things, but they also were schooled in education institutions of their time and place. Johann-Jacob was centered on wind instruments (flute, oboe) like their father. Johann-Christof was essentially an organist. Johann-Sebastian is known to have been a good singer when young and good at all keyboard instruments but also at the violin and viola.
The three brothers lived together with their uncle for some time when their father died but could not stay close together as they began their professional career and their uncle died as well. We know about a visit of JS to Ohrdruf where JC was installed and married, and the Capricio was probably written on the occasion of Jacob's departure for Sweden.
Johann Sebastian composed a piece for keyboard which is not often recorded. Capricio "On the departure of his beloved brother" BWV 992 (original title in Italian). This is a remarkable piece, in 6 very contrasted movements, showing the very extended composition skills of the young Bach, in different moods and styles, external imitation, counterpoint, themes transformation.
Everyone interested in Bach's development should hear it and look at the score. The composition date is accepted as before 1705 (when JS was 20) and probably 1704, recycling in parts some older ideas. It shows a young adult Bach ready to explore or illustrate many paths he would not later pursue.
The kind of works Bach composed were closely linked, over all his life, to the job position he had and the fancy of his masters.
Answer: Bach received instruction form his older brother, who was a student of Pachelbel.
Bach copied a lot of music of other composers: Buxtehude (famously), Couperin, Frescobaldi, Kerl, Froberger, Pachelbel and many others.
Regarding the wide range of influences from German (both North and South), Italian and French music, I don't know that it was that unusual. His brother probably introduced him to that range.
Comment: Interesting; I did not know that his brother taught him in part. His brother seems to have disappears into the annals of history! When you say copied, do you mean transcribed? The sheer amount of music he copied from Vivaldi and Buxtehude suggests these were the two composers he most respected, but perhaps I am wrong...
Comment: @Noldorin: Buxtehude was a famous organist and titular organist in a large city (such as Hamburg) was one of the most lucrative and stable position a musician could have at the time. It was also usually associated with being a Kappelmeister for one or several churches, another very prominent position for a professional musician.

Training and Influences of J. S. Bach


How delete row on SQL DataBase

Question: I have a ListView with a SQL DataBase. The values for it can be added dynamically with two EditText.
I want know how to delete a row in my SQL DataBase. Now I can just delete a row by the rowId, so the whole row with all values will be deleted. But I want that just the row is deleted so there so that there will be consecutive numbers.
For example a ListView.
1 Text1
2 Text2
3 Text3
4 Text4

With my code it would like that if I would delete row 3:
1 Text1
2 Text2
4 Text4

But I want that it look like when I delete row 3:
1 Text1
2 Text2
3 Text4

My code :
MainActivity
private void listViewItemLongClick() {
        ListView myList = (ListView) findViewById(R.id.list);
        myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View viewClicked, final int position, final long id) {

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        //Set header
                        builder.setTitle("delete");
                        builder.setMessage("Are you sure ? ");
                                //set the OK button with an onClickListener
                        builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
                            //edit the userinput
                            public void onClick(DialogInterface dialog, int whichButton) {
                                myDb.deleteRow(id);
                                populateListView();
                            }
                        }).setNegativeButton("no", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Do nothing.
                    }
                }).show();

                return false;
            }
        });
    }

DBAdapter
public class DBAdapter {

    private static final String TAG = "DBAdapter"; //used for logging database version changes

    // Field Names:
    public static final String KEY_ROWID = "_id";
    public static final String KEY_WDH = "task";
    public static final String KEY_KG = "date";

    public static final String[] ALL_KEYS = new String[]{KEY_ROWID, KEY_WDH, KEY_KG};

    public static final String DATABASE_NAME = "dbToDo";
    public static final String DATABASE_TABLE = "mainToDo";
    public static final int DATABASE_VERSION = 2; // The version number must be incremented each time a change to DB structure occurs.

    //SQL statement to create database
    private static final String DATABASE_CREATE_SQL =
            "CREATE TABLE " + DATABASE_TABLE
                    + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + KEY_WDH + " TEXT NOT NULL, "
                    + KEY_KG + " TEXT"
                    + ");";

    private final Context context;
    private DatabaseHelper myDBHelper;
    private SQLiteDatabase db;

    public DBAdapter(Context ctx) {
        this.context = ctx;
        myDBHelper = new DatabaseHelper(context);
    }

    // Open the database connection.
    public DBAdapter open() {
        db = myDBHelper.getWritableDatabase();
        return this;
    }

    // Close the database connection.
    public void close() {
        myDBHelper.close();
    }

    // Add a new set of values to be inserted into the database.
    public long insertRow(String task, String date) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_WDH, task);
        initialValues.put(KEY_KG, date);

        // Insert the data into the database.
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    // Delete a row from the database, by rowId (primary key)
    public boolean deleteRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        return db.delete(DATABASE_TABLE, where, null) != 0;
    }

    // Return all data in the database.
    public Cursor getAllRows() {
        String where = null;
        Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Get a specific row (by rowId)
    public Cursor getRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
                where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Change an existing row to be equal to new data.
    public boolean updateRow(long rowId, String task, String date) {
        String where = KEY_ROWID + "=" + rowId;
        ContentValues newValues = new ContentValues();
        newValues.put(KEY_WDH, task);
        newValues.put(KEY_KG, date);
        // Insert it into the database.
        return db.update(DATABASE_TABLE, newValues, where, null) != 0;
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DATABASE_CREATE_SQL);
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading application's database from version " + oldVersion
                    + " to " + newVersion + ", which will destroy all old data!");

            // Destroy old database:
            _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

            // Recreate new database:
            onCreate(_db);
        }
    }

}

Answer: It's messy because it looks like it is your identity column and you're trying to remove the gaps.  This isn't good practice, but there is a mechanism for doing it.  Conceptually, this is going to be a 4 step process.

Create a new temporary table with the same structure (including the auto-incrementing identity field).
Shove the remaining rows from your main table into the temp table.  I was about to write this up, but pseudo code to do this already exists all over.  For example, here's an answer to a similar question with a good one (including a disclaimer that I am seconding about this being a bad idea).
Drop your original table.
Rename your temp table to the name of your original table.

Note that you are re-writing the entire table every time you do a delete, so this solution doesn't scale well.
A better way to do this would be to add a non-identity integer field to your table where you store your always sequential integer value.  It's going to be your responsibility to maintain this field.  For example...
On initial population of your data, set this field equal to the identity field.
In your "delete a row" routine
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    boolean myReturnValue;
    myReturnValue = db.delete(DATABASE_TABLE, where, null) != 0;
    db.execSQL("UPDATE " + DATABASE_TABLE + " SET MyNewNonIdentitySequentialIntegerField = MyNewNonIdentitySequentialIntegerField -1) WHERE KEY_ROWID > " + String.valueOf(rowId) + ";") ;
    return myReturnValue;
}

When inserting, or immediately after inserting a new record you'll need to populate it by setting it equal to MAX(MyNewNonIdentitySequentialIntegerField) + 1.

How delete row on SQL DataBase


Map Network Drive in Windows Server 2008 R2 via GPO

Question: I'm trying to map a network share in Windows Server 2008 R2 x64 for hours now. We have an AD Domain, DNS, etc. It is working. I have a batch file which contains only 1 line.
net use z: \\Storage\backup /persistent:yes
and I have a GPO. What I tried until now:
Setup batch file in the GPO as
Startupscript (Computer Configuration - Windows Settings - Scripts - Start),
put the batch under
\\domainname\SysVol\domainname\Policies\{GUID}\Machine\Scripts\Startup
setup batch file as
Logonscript (User Configuration - Windows Settings - Scripts (Logon/Logoff) - Logon),
put it under
\\domainname\SysVol\domainname\Policies\{GUID}\User\Scripts\Logon
and also under \\domainname\NETLOGON
Then I discovered that Logon scripts and UAC don't play well together, so I tried Microsoft's preferred workaround described here.
So same thing as above with launchapp.swf and my batch as parameter. I also tried "EnableLinkedConnections" as described here. And I have "Always wait for the network at computer startup and logon" enabled in the GPO. The user on the Server is a local administrator and I can not change this. I'm viewing the server via Remote desktop and I always did gpupdate /force after changing the GPO...
The drive won't map and I don't see an entry in the Event Viewer. I'm lost and frustrated, please put me in the right direction.
The share is read only for normal users and writable for the user who logs on to the server which I want the drive mapped to. If I execute the batch and/or the launchapp.wsf after logging in, everything works fine. Sorry for my bad english.
Comment: possible duplicate of [Windows Server 2008 mapped drives not showing on workstations?](http://serverfault.com/questions/187676/windows-server-2008-mapped-drives-not-showing-on-workstations)
Comment: The problem with UAC is described in the linked Technet Article under subsection **Group Policy Scripts can fail due to User Account Control** Your 2nd point is interesting, I linked on the OU containing the targeted computer. So maybe here is my mistake, unfortunately I can not work on this problem in the next 2 weeks. But thanks so far, I will also definitely take a look at Group Policy Preferences, seems promising.
Comment: Yes, that is likely the problem. A user GPO containing a user logon script will not affect a computer object.
Answer: I'm not sure if this is exactly what you are trying to do, but I recently moved from a script to map network drives to using Group Policy Preferences to do this. The level of control and automation is incredible. Here is the Microsoft "Getting Started" link. There are a ton of references on the web that go into greater detail about the types of things that you can besides just map drives.
We have different shared drives for different departments, and some people should have access to multiple drives. GPP allows us to assign the drives to specific Organizational Units, Security Groups, or pretty much any level of targeting that you can imagine. This greatly simplifies setting up new computers for users.
We also use this for Shared Printers, if that is something you do as well.
Some issues that we have run into, Windows XP machines must have a few prerequisites installed before they can process the GPP. We also had to set each mapped drive to "run as the logged on user", to ensure that the proper permissions were set so that the drives would actually mount.
This could be an alternate route around your problem, while at the same time, providing a more "visible" method to administer these shares.
Comment: Small question: If my Domain Controler is a Windows Server 2008 and the client which I want to map the drive also then I did not have to install further software, right?
Comment: Are you saying the client is Server 2008 as well? If so, that should be correct. I only had to install software on our XP clients. Windows 7 and Server 2008R2 picked up the GPP automatically. (We do not have any Vista clients, so I don't know how it works.)


How to show that polar coordinates in a uniform distribution on a disk are independent?

Question: Let the random point $(X,Y)$ be uniformly distributed on the unit disc $D=\{(x,y):x^{2}+y^{2}<1\}$.
Show that the polar coordinates $R\in [0,1)$ and $\theta \in [0,2\pi)$ of the point are independent.
Can you help me with this exercise please?
Comment: A first hint: $R$ and $\theta$ are independent iff their joint density function is the product of their marginal density functions. A good place to start with this kind of problem is usually to try to find these functions.
Comment: Please make edits to your question to show what you have tried and where you are finding difficulty. It is hard for us to provide much assistance in the learning process, otherwise.
Comment: For any $r > 0$ and any $\theta \in [0,2\pi)$, find the probability that $\{R \leq r, \Theta \leq \theta\}$. If you draw  a crude sketch of the region and describe on it the region of interest, you will see that you can calculate this probability without needing to do any explicit integration (simple mensuration formulas suffice), and that this probability equals $P\{R \leq r\}P\{\Theta \leq \theta\}$ both of which can also be worked out without explicit integration. This allows you to conclude that  $R$ and $\Theta$ are independent. No need for densities or Jacobians etc.
Comment: **Follow-up exercise**: Prove that the answer you get for the density function for the radius is completely invariant to the choice of norm. That is, if you define the disc with respect to any other norm, you will get exactly the same answer when considering the radius with respect to the same norm.
Comment: @Dilip: What you state is true for the Euclidean norm but will not be true for (any) other norms. The point the exercise is trying to draw out is that the answer you get for the marginal distribution of the radius is not a consequence of the particular choice of norm here.
Comment: Homework question? please include homework tag.
Comment: @cardinal Actually, if one is not restricted to looking at the matter in terms of densities and distributions, it is possible to argue that if I am given that the value of $R$ is $r$, all I can say is that $(X,Y)$ lies on the circle of radius $r$ but I have no idea _where_ on the circle, since all the points on the circle of radius $r$ are equally likely. In other words, knowing $R$ tells me nothing that I didn't already know about $\Theta$, and so $R$ and $\Theta$ must be independent random variables.
Comment: Maybe another tip:area of the circle covered by random r and theta is r*theta; given the above definition of independence I think the answer is right in front of you.
Comment: @cardinal: I'm trying to understand what you mean by your last comment.  Do you mind explaining it a little bit?
Comment: @Neil: Sure. The reference to "exercise" in my last comment may have been confusing; it refers to the "follow-up exercise" in a prior comment. I expand on the invariance of the distribution of the radius with respect to the norm [near the end of this answer](http://stats.stackexchange.com/questions/28658). The distribution of the radius and the angle will be independent only for the Euclidean norm.
Answer: The solution may be a bit quirky, with a lot of variables, but it works fine for me.
We know that $X$,$Y$ - random variables in $\mathbb{R}^n$ and $\mathbb{R}^m$ are independent iff
$$\mathbb{E}(\varphi (X) \psi (Y) )= \mathbb{E}(\varphi(X)) \cdot \mathbb{E}(\psi(Y)) $$
$ \forall \varphi \in C^{\infty}_{0} $, $ \forall \psi \in C^{\infty}_{0} $, where $C^{\infty}_{0} $ are continuos on compact smooth functions.
If $(X,Y)$ are uniformly distributed on the unit disc $D=\{(x,y):x^{2}+y^{2}<1\}$. Then we have that $$\mathbb{P}_{(X,Y)}(dxdy)=\frac{1}{\pi}\mathbb{1}_D (x,y) dxdy$$
Analogically we define two distance and angle functions: $$\begin{cases}r:\mathbb{R^2}\rightarrow \mathbb{R}\\ \vartheta:\mathbb{R^2}\rightarrow \mathbb{R}\end{cases}$$
Now we have $R=r(X,Y)$ and $\Theta=\vartheta(X,Y)$ and by passing to polar coordinates with $\begin{cases}\rho=r(x,y)\\ \gamma = \vartheta(x,y) \end{cases}$ we can show that
$$\mathbb{E}(\varphi(R))=2 \int\limits^1_0 \varphi(\rho)\rho d\rho$$
$$\mathbb{E}(\psi(\Theta))=\frac{1}{2\pi}\int\limits^{2\pi}_{0} \psi (\gamma) d\gamma$$
Now we see that
$$\mathbb{E}(\varphi(R)\psi(\Theta))=\frac{1}{\pi} \int \limits_{D} \varphi(r(x,y))\cdot \psi(\vartheta(x,y))dxdy=\\
\frac{1}{\pi}\int\limits^1_0[\int\limits^{2\pi}_{0} \varphi(\rho) \psi(\gamma)d\gamma]\rho d\rho=\frac{1}{\pi} \int\limits^1_0 \varphi(\rho) \rho d\rho \cdot \int\limits^{2\pi}_{0} \psi(\gamma)d\gamma= \\  \mathbb{E}(\varphi(R)) \cdot \mathbb{E}(\psi(\Theta))
$$
Using Fubini's theorem we prove that $R$ and $\Theta$ are independent.


improving performance of table navigation in jquery

Question: I am trying to write table navigation using keys for asp.net gridview. This is what I have so far. It is working fine but it is slow. Please look at it and let me know how to improve the performance if possible.
Basically it is html table with input elements. The structure of table is like this

     <input type = "text">

     <input type = "text">

...

jQuery(function($) {
             $('table#<%= myTable.ClientID %>')
                .bind('keydown', funcKeyDown)
        });

function funcKeyDown(event)
        {
            //get cell element.
            var cell = event.target;

            //get current cellIndex
            var $cell = $(cell);
            var currCell = $cell.parents("td");
            var cellIndex = currCell[0].cellIndex;
            //get current rowIndex
            var currRow = $cell.parents("tr");
            var rowIndex = currRow[0].rowIndex;

            var nextRowIndex, targetElem = null;
            var nextCell;
            switch(event.keyCode) {
                case 13: //enter key
                    if(shiftKeyPressed == 1){
                        //move left
                        if(!(cellIndex == 0)){
                        targetElem = currRow.children("td").eq(cellIndex-1).find("input[type=text]");
                        if(targetElem){targetElem.select();}}}
                    else {
                        //move right
                       if(!(cellIndex == (numElements -1))){
                            targetElem = currRow.children("td").eq(cellIndex+1).find("input[type=text]");
                            if(targetElem){
                                targetElem.select();
                            }
                        }
                    }
                    return false;
                case 16: //shift key
                    shiftKeyPressed = 1;
                    return false;
                case 33:
                case 34: //page-up, page-down
                    if(event.keyCode == 33){
                        nextRowIndex = rowIndex - pageSize;
                        if(nextRowIndex < 0) nextRowIndex = 0;
                    }
                    if(event.keyCode == 34){
                        nextRowIndex = rowIndex + pageSize;
                        if(nextRowIndex > numRows) nextRowIndex = numRows;
                    }
                    targetElem = currRow.parent().children("tr").eq(nextRowIndex).children("td").eq(cellIndex)
                                    .find("input[type=text]");
                    if(targetElem != null){targetElem.select();}
                    return false;
                case 37: //left
                    if(!(cellIndex == 0)){
                        targetElem = currRow.children("td").eq(cellIndex-1).find("input[type=text]");
                        if(targetElem != null){targetElem.select();}}
                    return false;
                case 38: //up
                    if(rowIndex != 0){
                        targetElem = currRow.parent().children("tr").eq(rowIndex-1).children("td").eq(cellIndex)
                                        .find("input[type=text]");
                        if(targetElem != null){
                        targetElem.select();}}
                    return false;
                case 39: //right arrow
                    if(!(cellIndex == (numElements -1))){
                        targetElem = currRow.children("td").eq(cellIndex+1).find("input[type=text]");
                        if(targetElem != null){targetElem.select();}}
                    return false;
                case 40: //down
                    if(rowIndex >= 0){
                        targetElem = currRow.parent().children("tr").eq(rowIndex+1).children("td").eq(cellIndex)
                                        .find("input[type=text]");
                        if(targetElem != null){targetElem.select();}}
                    return false;
            }
        }

Answer: First off all you've got code running for every key press before you get into the switch statement and determine whether you actually need to do anything.
You need to factor that code into a function that simply gets the TD (as a simple element variable not a Jquery wrapper).
On top of this you have to understand that JQuery abstracting the differences between browsers comes with a price, performance.  For example when a bound event fires the event has a moderate chunk of Javascript to run through before your actual event function gets called.
Your use of currRow.children("td").eq(cellIndex+1).find("input[type=text]"); isn't going to be particularly great.  You could elminate the extra div by specifying height on the td.  Then assuming the td only contains such an input.
var tdNext = td.nextSibling;
var textBox =  tdNext ? tdNext.firstChild : null;
if (textBox) $(textBox).select();

The lesson is sometimes you need to circumvent JQueries advantages for the sake of performance.  The above code is still very compatible across multiple browsers.
You can apply similar techniques to the other main keys left, up, down and enter.
Is there a reason you are not using event.shiftKey to detect the shift key?  Using a global variable as you appear to be doesn't seem sound.


Dart passing data to a dynamically created polymer element

Question: I have read this thread about how to pass data to a polymer element
Button click in polymer dart does not work; needs polymer-element
But however, if I want to pass data to a programmatically created element by using createElement() in polymer.dart, there's no wrapping template. How am I going to pass the data as mentioned above?
Btw, even though I think dart is a really cool language (I dislike JavaScript,) I found polymer in dart maybe still not ready yet. A lot of things are not documented and have to go though examples or ask here.
Thanks,
Yi
Answer: I think you should remove the start()-function from MyElementElement-class and add it to upper level. Basically you shouldn't have any reference in custom-element to upper level objects. Now the custom element is not reuseable, it works only within this context.
Answer: Here is my example on how i passed data to a dynamically created custom polymer-element.
My intention was, click on an "a href" and load a polymer-element in a container div.
polymer_element.html
<polymer-element name="my-element">
  <template bind>

 {{ mytext }}

  </template>

</polymer-element>

polymor_element.dart
import 'dart:html';
import 'package:polymer/polymer.dart';
import 'package:custom_element/custom_element.dart';

@CustomTag('polymer-myelement')
class MyElementElement extends PolymerElement with ObservableMixin {

  bool get applyAuthorStyles => true;

  @observable String mytext = "initial text";

  void start() {

    query('#a href to click').onClick.listen((MouseEvent event){
      query('.container').children.clear();
      var myElem = createElement('polymer-myelement');

      MyElementElement myel = myElem.xtag;
      myel.mytext = "i changed the text now or import w/e you want";

      query('.container').children.add(myElem);

    });
  }
}

main() {
  MyElementElement el = new MyElementElement();
  el.start();
}

index.html

  <link rel="import" href="polymer_myelement.html">
  and everything you need ...

  click me for new text

So here is the explanation:
In my main() i just run my start() function and set an onclickListener for my navigation bar  href. When i click my href now, i just clear all children in my "div class="container", because i always want a clear div before i insert my polymer-elements.
Now create a polymer-Element with "createElement('polymer-mylement');".
Create a MyElement object and assign the polymer-element "xtag" to it.
Now you have access to all the properties and can change them.
Just add your created Element to your div and you are done.
You just dynamically created a polymer-element, assigned your new data to it and see it in your index.html
Comment: Thanks. It does work. I'm curious that does it document anywhere?
Answer: I have searched for a long time but anything work. Only one solution work fine for me:  https://stackoverflow.com/a/20067111/189411


Is there a open source Android 3D game develop kit?

Question: I found Kilobolt. It seems good to use, but I am not sure if it is open source.
And there is some similar question before, but posted 2 or 3 years ago. I think things have changed?
Comment: Although this is a question asking for tool/lib suggestion, but to me it seems a useful one.
Answer: There are few of them out there which are ope source and really good. Couple of them which I have tried and found useful are:

Cocos3D for Android
AndEngine

These are 2D and 3D game development Library for android
Answer: I suggest : libgdx.
It's the best for me.
Download from here : LibGdx
Answer: There are plenty of them....
Alien3D
Ardor3D
Cocos3D
These are just some of them...  You might want to check out http://mobilegameengines.com/android/3d_game_engines
(Also I don't believe AndEngine supports 3D games but I may be wrong)
Answer: Also jMonkeyEngine: http://jmonkeyengine.org/ although it's not only for Android, but for Java in general.


Xcode Error "Expression Result Unused"

Question: I'm getting an yellow error in my code and I'm not sure really why I'm getting it. Here is my code:
for (int lives = 5; lives > 0; lives--)
{
     self.HangmanStatus.text = @"Lives Left: %d", lives; //<-- Getting error here
}

Any help would be really appreciated,
Thanks!
Comment: What's the specific error you're getting?
Comment: The reason for the confusing error message is that in (Objective) C the comma in your example (`...%d", lives`) is actually a use of the *comma operator* - which is little used - and not a use of the comma as a separator. (@JohnSauer has already pointed you to how to fix your code.)
Answer: Is this your first time creating an NSString? You're not using any of the NSString methods used to create one.
Answer: The right syntax is:
self.HangmanStatus.text = [NSString stringWithFormat: @"Lives Left: %d", lives];

Look at NSString reference.

Xcode Error "Expression Result Unused"


A simple counting code which i dont understand how it work

Question: words = "Fine and Cloudy"
vowels = 'aeiouAEIOU'
my_words = [words.index(c) for c in words if c not in vowels and words.count(c) == 1]
print(my_words)

I'm just don't understand why the output is [0, 9, 10, 14] and how does this simple code works?
Can somebody explain in detail? Please!
Thanks in advance.
Answer: It prints the position of those letters in the string "Fine and Cloudy" that are not vowels and that occur exactly once. Those are the "F" (position 0), "C" (position 9), "l" (position 10), and the "y" (position 14).
Comment: Now I totally get it. Thank you so much!


Measurability of limit of sequence of measurable random variables

Question: Let $X_n$ be a sequence of random variables on a complete probability space, converging in $L^2-$norm to some $X$.
Suppose that $X_n$ is $B_n$ measurable, for some $B_n$ in $L^2$ and suppose that $B_n$ converges in the $L^2-$norm to some $B$.
Is there any way to guarantee that $X$ is $B-$measurable ?
Comment: Could you please clarify what $B_n$ is? It's a little unclear to me
Answer: No. Let $X\sim N(0,1), B_n=\frac X n$ and $X_n=X$ for all $n$. Then $X_n$ is $B_n$ measurable, $X_n \to X$ in $L^{2}$, $B_n \to B=0$ in $L^{2}$. However $X$ is not $B$ measurable.


Passing environmental variables as parameters

Question: I need to pass few environmental variables as parameters that can do some job.
Example: In Perl, it would be something like this
my $g_folder = $ENV{'g_folder'};
my $assembly_name = $ENV{'genome_assembly_name'};

my $genome_seq = $g_folder . '/' . $assembly_name .".fa";

Is there a simple way to do this in Python. Any help is appreciated. Thanks.
Comment: `os.environ` ? I guess ?
Comment: You want to read an environment variable or pass on in to the program?
Comment: What are you actually doing?
Comment: From a galaxy like environment, I have few environmental variables passed eg g_folder and assembly. I need these parameters in my plugin .
Answer: I would translate this to Python as:
import os

g_folder = os.environ['g_folder']
assembly_name = os.environ['genome_assembly_name']
genome_seq = os.path.join(g_folder, assembly_name + '.fa')

Comment: Thanks. I did think of this first but this did not work. I tried the os.environ.copy to call the parameters to my subprocess but that didnt pass the parameter.
Answer: import os

env_name = 'g_folder'
assembly_name = 'genome_assembly_name'

g = os.getenv(env_name)
assembly = os.getenv(assembly_name)

file_name = os.path.join(g, assembly) + ".fa"

Answer: here's the link to the os.environ module that should accomplish what you are looking for. https://docs.python.org/2/library/os.html#os.environ
Answer: os.system("some.exe.bin {genome_assembly_name}".format(**os.environ)

is yet another way of doing this ...


Confidence intervals for mixture of Gaussian distributions

Question: I have a mixture distribution of 2 Gaussians.  Here, the left has a weight of 0.1 and the right has a weight of 0.9.  In this example, they have identical $\sigma$, but that may not always be the case.
In my use case, the $\mu$, $\sigma$, and weights of the component distributions which comprise the mixture are always known.
Knowing the parameters of the component distributions, is there an analytical method for me to calculate the threshold probability density $D_{thresh}$, for which all density values $D \ge D_{thresh}$ constitute the region of 95% cumulative probability in this mixed distribution?

Red lines indicate the +/- 1.96 SD for each component distribution.
Answer: I also have been looking for a similar thing for a while.
However, determining a confidence interval for an arbitrary Gaussian mixture is not trivial. Think of a case where several densities have overlapping domains.
Refer to:
https://hal-enac.archives-ouvertes.fr/hal-00934773/


Posso usar empty e isset em uma variável?

Question: Segue um exemplo:
if(isset($_POST['nome']) && !empty($_POST['nome'])) {
    session_start();
    $_SESSION['nome'] = $_POST['nome'];
}

Ver demonstração
Caso eu não possa usar isto, qual seria o recomendado? Estou tentando adotar as melhores questões de segurança para meu site.
Citação interessante de uma referência exibida na resposta de @qmechanik:

isset() testa se a variável foi "iniciada(isset)" e se não está null.
empty() pode retornar "true" quando a variável foi "iniciada(isset) por certos valores.

Lógica final: !empty verifica se não está vázio, logo se não está vazio ele foi iniciado, portanto !empty já basta e não depende de isset, ao contrário do isset que depende do !empty (isto não remove o fato de poder colocar isset e empty em tal situação) em algumas situações, enfim qualquer pensamento ou citações que contradiz isto, por favor responda se possível, obrigado.
Comment: Qual é a intenção, em termos de segurança?
Comment: Qualquer cuidado é pouco, quero ter segurança em qualquer coisa pois minha web vai mecher com alguns dados pessoais e não quero que isto vaze para qualquer outro hacker que nao tem o que fazer..
Answer: Poder pode, mas é redundante.
Ambos tem diferentes objetivos, o empty determina se uma variável está vazia (uma array vazia, FALSE, NULL, 0 número ou no formato string), o isset por sua vez informa se uma variável foi iniciada, por exemplo, se uma variável é nula ou foi destruída com unset, o isset vai retornar FALSE. Um detalhe importante: ela não verifica se uma variável está vazia.
Utilizar os dois é redundante, basicamente o empty é uma abreviação para !isset($variavel) || !$variavel, !empty() é análogo à isset($variavel) && $variavel, mas sem emitir avisos, o manual do PHP cita:

empty() é o oposto de (boolean) var, com exceção de não gerar um
  alerta (warning) se a variável não existir.

O empty é implementado no arquivo zend_language_parser.y - linha 1204 que executa o método zend_compile_isset_or_empty presente no arquivo zend_compile.c - linha 6117, empty é praticamente um !$variavel. Esse é o ponto principal desta função: fazer uma comparação booleana sem ter a preocupação do conjunto ser variável ou não.
Se for para usar um ou outro, use o empty.
Exemplo
$variavel;      // Variável indefinida
echo $variavel; // Notice: Undefined variable: variavel in...

if (!empty($variavel))
    echo "A {$variavel} pode ser usada, pois não está vazia ou indefinida.";
else
    echo "A variável está vazia ou não foi definida.";

Ver demonstração
O isset não foi necessário para verificar se a variável foi iniciada ou não.
Referências:

Why check both isset() and !empty()
The empty($v) function is actually (!isset($v) || $v != true)-and-silence-warnings
Comment: Ok, obrigado pelas respostas, e pelo suporte rs, merece best answer amigo!
Comment: Obrigado pela resposta bem detalhada amigo, mas agora estou em dúvidas pois de acordo com o manual do php.net eu nao entendo nada sobre os exemplos :s e tem a resposta oposta do amigo ali :s
Comment: atualizado o #código, detalhes: isset = variavel foi iniciada, empty = a variavel nao está vazia, entao neste caso não ira dar qualquer tipo de erro, o amigo da outra resposta ali me traduziu e agr estou convertendo em pequenas formas. Mas irei tirar isto a limpo no meu xampp quando chegar em casa.
Comment: Tirei a limpo no ideone mesmo, confira: http://ideone.com/09MxuQ
Comment: Mas nao seria mais seguro isset e empty juntos?
Comment: @Kevinmtk O `empty` por si só já usa o `isset` internamente. Faça testes, olhe o código fonte, veja as referências. =)
Comment: Concordo com a lógica de que se a variável nao está vazia, logo ela foi iniciada anteriormente,  a nao ser que um hacker bugue isso...
Comment: @Kevinmtk Você mencionou na pergunta que estava preocupado com *segurança*, talvez esse [**link**](http://www.cyberciti.biz/tips/php-security-best-practices-tutorial.html) possa dar um início e esse [aqui](http://br.phptherightway.com/) também, *em português*. Sobre *boas práticas* [esse](http://blog.thiagobelem.net/php-as-10-melhores-praticas-pra-um-iniciante/) também é informativo. Qualquer dúvida crie uma pergunta. =)
Answer: Pode!
Você está verificando se uma variável existe e se possui algum valor.
Uma variável em php pode ser inicializada sem valor, portanto ela pode sim ser iniciada e não ter nenhum valor atrelado a ela, sendo assim existem vários casos onde você precisa verificar se a variável existe e se ela possui valor.
Observação
No seu código você está verificando se existe ou está vazio, isso pode gerar um erro na verificação, pois a verificação do isset() está depois do empty().
Portanto faça sua verificação assim para garantir o funcionamento do seu código:
$post = $_POST['nome'];

if(isset($post) && !empty($post)) {
    session_start();
    $_SESSION['nome'] = $post;
}

Note que eu utilizei && no lugar de usar || assim eu preciso que a variável tanto exista quanto não esteja vazia.
Comment: Obrigado pela resposta bem detalhada, e a correção do meu código exemplo. :D
Comment: muita gente está confusa em relação ao `empty`. em alguns casos é melhor utilizar somente o `empty`, mesmo que uma variável não exista!


Arquivo html+css(bootstrap) quando inserido pelo "require_once()" do php não funciona o menu dropdown

Question: Estava criando o menu do meu sistema e estava tudo funcionando corretamente, o arquivo menuHorizontal.php contem o menu e nele tem um dropdown que estava funcionando, quando eu clico, ele abre o submenu, até ai tudo bem, o problema é que agora no arquivo index.php, eu coloquei la na linha 2 o require_once("menuHorizontal.php"); e indo no index.php, o menu aparece certinho o problema é quando eu clico no dropdown, ele não desce, funciona a função "hover" que eu coloquei, porém o dropdown não desce. Alguma ideia de algo?
index.php
<?php
require_once("menuVertical.php");
require_once("menuHorizontal.php");
?>

<!DOCTYPE html>

    <title>Menu</title>

menuHorizontal.php
<!DOCTYPE html>

    <title>Menu</title>
    <link href="http://netdna.bootstrapcdn.com/font-awesome/3.1.1/css/font-awesome.min.css" rel="stylesheet" />
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="css/menu_style.css" />

    <link href="css/font-awesome.min.css" rel="stylesheet" />
    <link href="css/font-awesome.css" rel="stylesheet" />

                    Requisições

                                 Paciente: Lorem ipsum dolor sit amet
                                 Requisição N°: 220
                                 Atendimento N°: 4933
                                 Setor Solicitante: Emergência

                                 Paciente: Lorem ipsum dolor sit amet
                                 Requisição N°: 222
                                 Atendimento N°: 9844
                                 Setor Solicitante: Ambulatorial

Ver Todas

javascript
jQuery(document).ready(function() {
    jQuery('ul.form li a').click(
        function(e) {
            e.preventDefault(); // prevent the default action
            e.stopPropagation; // stop the click from bubbling
            jQuery(this).closest('ul').find('.selected').removeClass('selected');
            jQuery(this).parent().addClass('selected');
        });
});

Comment: No devtools ou equivalente aparece algum erro no console quando você clica no dropdown? Mostre a parte do javascript.
Comment: O javascript dele é bem pequeno, inclui na pergunta.
Comment: E tenho a seguinte informação também: Além do dropdown não funcionar, eu coloquei um href="https://www.google.com"  e mesmo assim não funcionou, não abriu o dropdown e não abriu o link do google. É como se estivesse "desabilitado", clica mas não acontece nada.
Comment: E também tenho a seguinte informação: Se eu abrir uma tag php e colocar um "echo" por exemplo, o dropdown funciona, se eu colocar um "include" que inclua um arquivo simples, apenas um HTML escrito "teste", o dropdown também funciona. Estou imaginando que o problema possa ser incluir um arquivo com códigos característicos do bootstrap, no meu caso, o "menuVertical.php".
Answer: O problema aconteceu por incluir o arquivo menuVertical.php que continha os seguintes comandos dentro das tags

<title></title>
<link href="http://netdna.bootstrapcdn.com/font-awesome/3.1.1/css/font-awesome.min.css" rel="stylesheet" />
<link href="css/bootstrap.min.css" rel="stylesheet">

<link rel="stylesheet" type="text/css" href="css/menu_style.css" />

Esses comandos existiam no arquivo menuHorizontal.php e no arquivo menuVertical.php e isso estava ocasionando um conflito. A solução foi remover esse bloco de códigos de um dos arquivos.