Use Pigeonhole to show of any set of $2^{n+1}-1$ positive integers is possible choose $2^{n}$ elements such that their sum is divisible by $2^{n}$.

Question:
Show that, of any set of $2^{n+1}-1$ positive integers numbers is possible choose $2^{n}$ elements such that their sum is divisible by $2^{n}$.

My approach: Let $a_1,a_2,\ldots,a_{2^{n+1}-1}$ positive integers numbers. Define, $s_j=a_1+a_2+a_3+\ldots+a_{2^{j+1}-1}$, $j\in\{1,\ldots,n\}$.
If any of the $2^{n+1}-1$, $s_j$, are divisible by $2^n$, we are done.
In case contrary, $s_j$ have a remainder $1,2,3,\ldots,2^{n}-1\mod(2^n)$. And, we know that $2^{n+1}-1>2^n-1$, so by Pigeonhole Principle, there exist a tleast two $s_j$ such that has a same remainder ($\mod(2^n)$), i.e., if $p<q$, then $$s_q-s_p=a_{2^{p+1}}+a_{2^{p+1}+1}+\ldots+a_{2^{q+1}-2}+a_{2^{q+1}-1}\equiv 0\mod(2^{n})$$
So, the set $\{a_{2^{p+1}},a_{2^{p+1}+1},\ldots,a_{2^{q+1}-2},a_{2^{q+1}-1}\}$ is the set we need. I know, this answer doesn't be right, but is the idea I have to occupy Pigeonhole.
EDIT: Both answers were very good, but, how I could occupy the pigeonhole principle in this problem?
Comment: I added an answer explaining the precise relation to EGZ.  One can recycle the easier part of the EGZ proof to solve this. @user4759923
Comment: Do they have to be distinct elements in the sum?
Comment: @Andrew it'd be pretty easy if not. You could just pick the same element $2^n$ times.
Comment: I think he means if it is possible to repeat an element more than once.
Comment: @AndrewWhelan In the problem doesn't says nothing about it. So, I suppose should to be distinct elements.
Comment: Looks quite similar to Erdös-Ginzberg-Ziv
Comment: it seems to be a weaker case of it, do you agree?
Comment: It seems weaker, but very different to approach.
Answer: We proceed via induction over $n$.
The base case is $n=1$ and it is trivial, we have $3$ numbers, so clearly we can pick two with the same parity.

Inductive step:
Split the $2^{n+1}-1$ elements into two groups of size $2^{n}-1$ and an extra element.
By the inductive hypothesis we can pick two groups of $2^{n-1}$ elements from each group, with sum divisible by $2^{n-1}$. If these sums are congruent $\bmod 2^{n}$ we are done (just take the union).
Otherwise notice we have $2^{n+1}-1-2^{n-1}-2^{n-1}=2^n-1$ elements that are in none of the two groups. So by the inductive hypothesis we can form a third group of $2^{n-1}$ elements with sum divisible by $2^{n-1}$. This sum must be congruent $\bmod 2^n$ to one of the other two groups.
Comment: It can be slightly reworded, if we have $2^n-1$ elements we can extract a subset of $2^{n-1}$ elements with sum divisible by $2^{n-1}$. We can use this to extract three disjoint subsets of size $2^{n-1}$ and sum which is either $0$ or $2^{n-1}\bmod 2^n$. Take two which are congruent $\bmod 2^n$, their union does the trick.
Comment: Yeah, we have three groups. They are $A,B$ and $C$. Each of them has a sum that is either $0$ or $2^{n-1}\bmod 2^n$. So there are two groups that are congruent $\bmod 2^n$. Their union is the set we need.
Comment: Very nice answer, but I have a confusion with your last phrase "This sum must be congruent $mod(2^{n})$ to one of the other two groups". Thanks again for your answer!
Comment: Can you extend/modify  your method to prove  that in every set of 2n integers, you can choose a subset of size n whose sum is divisible by n ?
Comment: @HemantAgarwal I doubt it, this method seems to rely on those hypotesis a lot. But you can post that as a seperate problem if you want, I will try to solve it if you do.
Comment: Oh, apparently it is called Erdos-Ginzburg-Ziv
Comment: You can post your answer here if you want : [subsets and sums](https://math.stackexchange.com/questions/3754764/proving-that-among-any-2n-1-integers-theres-always-a-subset-of-n-which-s)  . Request you to post an answer that is simple to understand and also intuitive . A lot of complicated answers using the Erdos' theorem etc are already post on the above link and on other posts. I have not been able to understand these answers .
Answer: As suggested in the comments this is Erdos-Ginzburg-Ziv theorem for a power of $2$.
The proof of E-G-Z has an easy inductive part, that if the theorem is true for $p$ and $q$ it is true for $pq$, and a nontrivial base case of proving the theorem true for primes.  Here the prime is $2$ so the base case is true by inspection. The proof of the  multiplicative property is the same whether or not $p=q$ or if they are powers of $2$.
https://en.wikipedia.org/wiki/Zero-sum_problem
Comment: Thanks for your answer!, but exist other method for prove this?? I think the pigeonhole principle is enough.


Erro ao tentar declarar o tipo de uma variável proveniente de um relacionamento dentro de um método listar

Question: Boa tarde, estou com um problema em setar a variável [fornecedor] em um método [listarProduto] que é do ProdutoDAO, e quero receber o atributo [id] do fornecedor.
Aonde tentar setar o tipo da variável dá erro em [rs.getInt("fornecedor")] e é informado pelo netbeans que [incompatible types int cannot be converted to Fornecedor] como se ela não aceitasse declarar o id que vem de fornecedor como int.
Mas essa classe produto tem que se relacionar com o fornecedor, porque como estou tentando fazer para uma interface gráfica aonde eu vou utilizar essas informações obtida através combobox ou jtable em um jframe de cadastrar produto, para quando eu clicar em um dos dois ele possa listar automaticamente os nomes dos fornecedores e os id para eu escolher e depois cadastrar o produto com o resto das informações. Então não posso tirar o relacionamento da variável Fornecedor fornecedor e declarar ela como Int.
peço desculpas se não conseguir informa direito o problema primeira vez aqui.
Essa é minha classe fornecedor
public class Fornecedor {

    private int id;
    private String nome;
    private String cnpj;
    private String fone;
    private String email;
    private String ie;
    private String cep;
    private String cidade;
    private String uf;
    private String endereco;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getCnpj() {
        return cnpj;
    }
    public void setCnpj(String cnpj) {
        this.cnpj = cnpj;
    }
    public String getFone() {
        return fone;
    }
    public void setFone(String fone) {
        this.fone = fone;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getIe() {
        return ie;
    }
    public void setIe(String ie) {
        this.ie = ie;
    }
    public String getCep() {
        return cep;
    }
    public void setCep(String cep) {
        this.cep = cep;
    }
    public String getCidade() {
        return cidade;
    }
    public void setCidade(String cidade) {
        this.cidade = cidade;
    }
    public String getUf() {
        return uf;
    }
    public void setUf(String uf) {
        this.uf = uf;
    }
    public String getEndereco() {
        return endereco;
    }
    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }
}

Essa é minha classe Produto
public class Produtos {

    private int idProd;
    private String nome;
    private String unidade;
    private int precoDeCompra;
    private int precoDeVenda;
    private Fornecedor fornecedor;
    //private String fornecedor;
    private String estoque;

    public int getIdProd() {
        return idProd;
    }

    public void setIdProd(int idProd) {
        this.idProd = idProd;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getUnidade() {
        return unidade;
    }

    public void setUnidade(String unidade) {
        this.unidade = unidade;
    }

    public int getPrecoDeCompra() {
        return precoDeCompra;
    }

    public void setPrecoDeCompra(int precoDeCompra) {
        this.precoDeCompra = precoDeCompra;
    }

    public int getPrecoDeVenda() {
        return precoDeVenda;
    }

    public void setPrecoDeVenda(int precoDeVenda) {
        this.precoDeVenda = precoDeVenda;
    }

    public Fornecedor getFornecedor() {
        return fornecedor;
    }

    public void setFornecedor(Fornecedor fornecedor) {
        this.fornecedor = fornecedor;
    }

    public String getEstoque() {
        return estoque;
    }

    public void setEstoque(String estoque) {
        this.estoque = estoque;
    }

}

E esse é o metodo listar em ProdutosDAO que ocorre o erro
public List<Produtos> listarProdutos(){
        try {
            List<Produtos> lista = new ArrayList<>();

            String sql = "select * from produtos";

            PreparedStatement stm = conProd.prepareStatement(sql);
            ResultSet rs = stm.executeQuery();

           while (rs.next()){
               Produtos obj = new Produtos();

               obj.setIdProd(rs.getInt("idProd"));
               obj.setNome(rs.getString("nome"));
               obj.setUnidade(rs.getString("unidade"));
               obj.setPrecoDeCompra(rs.getInt("precoDeCompra"));
               obj.setPrecoDeVenda(rs.getInt("precoDeVenda"));
               obj.setFornecedor(rs.getInt("fornecedor"));//o erro dá na parte rs.getInt("fornecedor")
               obj.setEstoque(rs.getString("estoque"));

               lista.add(obj);

           }
           return lista;
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Erro ao listar Produtos: "+e);
            return null;
        }
    }

Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Comment: Está tentando fazer um `getInt` em uma variável que possui o tipo `Fornecedor`.
Comment: Por que não produto.getFornecedor().getId()?
Comment: @epx eu tentei fazer isso obj.getFornecedor.getId((rs.getString("fornecedor"))); e obj.getFornecedor.getId(rs.getString("fornecedor")); e deu esse erro [link](https://prnt.sc/1tdha3t)
Comment: @Danizavtz s, mas eu não sei qual tipo usar para puxar a informação id do fornecedor
Comment: Tem que ser o tipo que está na Descrição da coluna `fornecedor` da tabela `produtos`. Verifique o DDL da tabela `produtos`.
Comment: @Danizavtz peço desculpa por n saber oque é DDL, mas na classe produto eu atribuir fornecedor como fornecedor para ter uma variavel que possa acessar todas as informações de fornecedor, mas como eu só queria salvar o id eu coloquei como int no metodo listar pq é como eu declarei o id na classe fornecedor, se eu não entendi oque vc quis falar peço desculpa
Comment: Então não seria só mudar o tipo da variável  `private Fornecedor fornecedor;` para `int`? Exemplo: `private int fornecedor;` e depois mudar getter e setter.
Comment: @Danizavtz sim assim resolveria, mas essa classe `produto` tem que se relacionar com o `fornecedor`, porque como estou tentando fazer para uma interface gráfica aonde eu vou utilizar essas informações obtida através `combobox` ou `jtable` em um `jframe` de cadastrar produto, para quando eu clicar em um dos dois ele possa listar automaticamente os nomes dos `fornecedores` e os `id` para eu escolher e depois cadastrar o produto com o resto das informações. Só q eu não sei se vou ter como fazer isso só colocando `int` e não o relacionamento
Comment: Poderia adicionar estas informações que adicionou nos comentários na pergunta? Assim podemos ser mais assertivos quando responder. Agora está claro qual o problema. Você pode editar a pergunta para incluir as informações. Clicando em [editar](https://pt.stackoverflow.com/posts/528817/edit)
Comment: @Danizavtz peço desculpa por não saber como fazer a pergunta, é a minha primeira vez fazendo alguma pergunta relacionada a programação desde que comecei a programar, se vc poder me dizer se falto colocar algo ou mudar alguma coisa pf me avisa que como é minha primeira vez aq não sei como fazer as coisas direito ainda
Comment: O que usa pra fazer o mapeamento? JPA?
Comment: @Danizavtz na verdade eu não utilizo nada para mapear como hibernate ou JPA, esse trabalho é só utilizando comandos para o mysql e fazer um crud basico para interface grafica, então oque eu estou utilizando para tentar pegar as informações é precisamente essa variável fornecedor que fica dentro do object produto
Comment: @Danizavtz afinal esse projeto não utiliza controller nem regras de negocio, então por isso que é mais simples
Answer: Se quer numa só consulta do seu DAO trazer o produto junto com os dados do fornecedor, precisa mexer no seu SQL.
Select * from produtos traz só uma lista de produtos sem indicação de qual produto deseja e nem quem são os fornecedores (só os id's de fornecedor na tabela produtos). Essa consulta em SQL não está referenciando a tabela fornecedores e não está fazendo nenhuma associação entre o produto e o fornecedor, que seria um where produto.id_fornecedor = fornecedor.id, por exemplo.
Esse é só o erro principal, tem outros. A modelagem de estoque está ruim. Pense muito bem o que quer dizer com estoque. Na tabela produtos, cada registro (linha) é um produto, representado por um objeto da classe que deveria estar com o nome no singular (Produto). Estoque de um produto é o quê? Uma coluna que guarda um valor inteiro? Ou seu estoque é uma lista de produtos de determinado tipo? Qual fica melhor no seu caso? Entre alguma outra eventual possibilidade.


Como montar um Json com jackson tendo as classes modelos?

Question: Tenho as seguintes classes:
public class OnesignalRequestModel {

    private String app_id;
    private List<IDModelJson> include_player_ids;
    private ContentJsonModel content;

    public String getApp_id() {
        return app_id;
    }

    public void setApp_id(String app_id) {
        this.app_id = app_id;
    }

    public List<IDModelJson> getInclude_player_ids() {
        return include_player_ids;
    }

    public void setInclude_player_ids(List<IDModelJson> include_player_ids) {
        this.include_player_ids = include_player_ids;
    }

    public ContentJsonModel getContent() {
        return content;
    }

    public void setContent(ContentJsonModel content) {
        this.content = content;
    }
}

public class IDModelJson {

    private Integer id_onesignal;

    public Integer getId_onesignal() {
        return id_onesignal;
    }

    public void setId_onesignal(Integer id_onesignal) {
        this.id_onesignal = id_onesignal;
    }
}

class ContentJsonModel {

    public String getEn() {
        return en;
    }

    public void setEn(String en) {
        this.en = en;
    }

    private String en;
}

E gostaria de montar um JSON nesse estilo (montei em Python com tanta facilidade...)
{"app_id": "app_id_do_usuario", "include_player_ids": [id_onesignal], "contents": {"en": mensagem}}

Mas não entendi como posso, efetivamente, montar ele usando o Jackson e aproveitando os modelos que escrevi.
A classe que quero implementar é essa aqui:
public class RequestOneSignal {

    final ObjectMapper mapper = new ObjectMapper();

    public int doPost() throws IOException {
        HttpClient client = HttpClientBuilder.create().build();
        try (CloseableHttpClient clientClose = HttpClients.createDefault()) {
            HttpPost post = new HttpPost("url");
            post.setHeader("Content-Type", "application/json; charset=utf-8");
        }
    }

    private HttpEntity createEntity(List<Integer> clientsID){
        //Aqui, quero gerar o JSON e poder setar numa entity para fazer o post

    }

}

Answer: Oi, boa noite.
Monte toda a sua resposta (OnesignalRequestModel) e a envie com o comando
OnesignalRequestModel onesignalRequestModel = new OnesignalRequestModel();
.. sete os atributos
mapper.writeValue(new File("caminhoDoArquivo.json"),onesignalRequestModel);

Dê uma olhada aqui https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
Espero que tenha ajudado!


How can I avoid unnecessarily checking the same if-statement in my while loop?

Question: I want to implement k-means clustering in MATLAB and at the moment I have a function that looks like this:
function clusters = kmeans(k, data, measure)
...
iterate = true;
while (iterate)
    ...
    if(strcmp(measure, "euclidean")
        dists = getEuclideanDists(centroids, data)
    elseif(strcmp(measure, "pearson")
        dists = getModifiedPearson(centroids, data)
    end
    ...
end
end

I only need to check what the string measure is equal to once, but I need the body of the if-statement in the while loop because the value of centroids changes during the while loops, and in turn, so does dist. Is there a more efficient way of making the check just once but continuously updating the value of dist?
Also is there a 1-liner / function that I can use to calculate the Pearson Correlation Coefficient of each row in my dataset?
Answer: I'd define a function handle before the loop based on the comparison:
function clusters = kmeans(k, data, measure)
    ...
    if(strcmp(measure, "euclidean")
        getDists = @getEuclideanDists;
    elseif(strcmp(measure, "pearson")
        getDists = @getModifiedPearson;
    end

    iterate = true;
    while (iterate)
        ...
        dists = getDists(centroids, data);
        ...
    end
end

Answer: You can either simplify the test:
douec = strcmp(measure, "euclidean");
dopea = strcmp(measure, "pearson");
while (iterate)
    ...
    if (doeuc) {
        dists = getEuclideanDists(centroids, data)
    elseif (dopea) {
        dists = getModifiedPearson(centroids, data)
    end
    ...
end

or make two loops:
if (strcmp(measure, "euclidean")) {
   while (iterate) ...
}
if (strcmp(measure, "pearson")) {
   while (iterate) ...
}

BTW, not sure your use of strcmp is what you want.
Also, if ueclidean and pearson are are the only 2 possibilities then a simple (if-else) is sufficient (no need for the elseif's compare).
Comment: If I use two loops I will have practically the same code written twice which doesn't seem like a good approach. I want efficiency in both writing and executing the actual code. Are there any other alternatives or is there just no way around it?
Comment: Unless matlab supports function pointers, I think those are your alternatives.  In any event, unless testing has revealed an actual need for optimization, my opinion is just write the clearest, simplest code you can.


Adding files in subfolders to sphinx documentation (sphinxcontrib-matlabdomain)

Question: I have a directory containing various folders, with each of them having matlab source files in them. Some of these folders have sub-folders containing matlab source files.
How can I create a TOC tree with Sphinx to contain the sub-folders in a nested way?
For example, when Main-Directory contains conf.py, index.rst, and moduleslist.rst along with the following folder structure:
    Folder1
        abc.m
        def.m
    Folder2
        Folder2.1
            ghi.m
        jkl.m

with this index.rst file:
.. toctree::
    :maxdepth: 1

    moduleslist

and this moduleslist.rst file:
.. toctree::
    :maxdepth: 2

Folder1
=========
.. automodule:: Folder1
:members:

Folder2
=========
.. automodule:: Folder2
    :members:

But this does not include the sub-folder Folder2.1 and files in it. I have tried adding Folder2/index in index.rst, with the Folder2/index.rst containing the automodule for Folder2.1, which didn't include documentation of ghi.m.
How can I get Sphinx to show nested sub-folders in it's TOC tree?
Comment: Related [`Access m-files in a subfolder without permanently adding it to the path`](http://stackoverflow.com/questions/22013875/access-m-files-in-a-subfolder-without-permanently-adding-it-to-the-path).
Comment: @IKavanagh and others - another common oversight I see is forgetting to set `matlab_src_dir = os.path.abspath(os,path.join('path','to','mfiles'))` without this in `conf.py` Sphinx won't know where to find your MATLAB files. You can **not** just set the Python `sys.path` because that uses `importlib` to find **only** _Python_ files.
Comment: I wonder if this is related to how the parameter are documented in the comments? I wonder if the OP's MATLAB classes, class-methods and functions are documented using Sphinx markup? See [Sphinx Domains](http://www.sphinx-doc.org/en/stable/domains.html) for examples. Typically parameter documentation is given in comments after the first line of the object definition as `:param type arg: the description of the argument`
Answer: I've started using Sphinx and have run into this problem on documentation in general (not specific to autodoc feature).  This is how I got it to work and have much better control over how the tree is built.
Treat each folder as a separate group.  So at the Sphinx root directory you'll have the index.rst file that will look like this:
.. toctree::
    :maxdepth: 1

    Folder1/index
    Folder2/index

I use the maxdepth: 1 so that it only list the major group name.
Under Folder1 and Folder2 you'll need to add additional index.rst files:
#Folder1/index.rst

.. toctree::
    :maxdepth: 2

    abc.m
    def.m

#Folder2/index.rst

.. toctree::
    :maxdepth: 2

    Folder2.1/index
    jkl.m

As a side note, I've setup my index pages so that they either have just group listings (maxdepth: 1) or detail page listings (maxdepth: 2) - I'm sure there is a way to make the folder/index at depth 1 and files at depth 2.
Then within Folder2.1 you'll need your third index:
#Folder2.1/index.rst

.. toctree::
    :maxdepth: 2

    ghi.m

Here is the Sphinx Docs on Nested toctree and it wasn't as clear.  Obviously you'll need the autodoc code for more complicated/deep tree structures.


Horizontal line test in graphs

Question: Given a function $f\colon X \to Y$
i. If a horizontal line test intersects at at most one point, it is injective.
ii. If it intersects at more than one point, it is surjective.
iii. If it intersects at exactly one point, it is bijective.
For example $f(x)=2^x$
Now, my problem is what if you chose $y=-5$, it doesn't intersect with the graph, is it still considered an injective function?
Also, if a graph is injective does it also mean it is automatically bijective?
Comment: It is not necessarily true that if a horizontal line intersects the graph of a function more than once, then the function is surjective.  For instance, the function $f: \mathbb{R} \to \mathbb{R}$ defined by $f(x) = \sin x$ is not surjective even though the $x$-axis intersects the graph infinitely many times.
Comment: Specifically, "intersects at one point" should be clarified to "intersects at at most one point" since "intersects at exactly one point" is for part iii.
Comment: See [Horizontal line test](https://en.wikipedia.org/wiki/Horizontal_line_test) : "we can decide if it is injective by looking at horizontal lines **that intersect the function's graph**."
Comment: Oh, I kinda skipped that part, thanks!
Comment: @MichaelBiro so can it have no intersections?
Answer: Definition.  A function is said to be injective if $f(x_1) = f(x_2) \implies x_1 = x_2$ or, equivalently, $x_1 \neq x_2 \implies f(x_1) \neq f(x_2)$.
Horizontal Line Test. A horizontal line intersects the graph of an injective function at most once.
Proof.  Suppose otherwise.  Then there exists a horizontal line $y = k$ and an injective function $f$ whose graph intersects the line $y = k$ at two points, $(x_1, k)$ and $(x_2, k)$, with $x_1 < x_2$.  Then $f(x_1) = f(x_2) = k$.  Since $f$ is injective, $f(x_1) = f(x_2) \implies x_1 = x_2$, which contradicts our assumption that $x_1 < x_2$.  Thus, a horizontal line can intersect the graph of an injective function at most once.$\blacksquare$
You observed that the line $y = -5$ does not intersect the graph of the function $f(x) = 2^x$.  Notice that this does not contradict the definition of an injective function since we do not have two different $x$-values that produce the same $y$-value.

The function $f: \mathbb{R} \to \mathbb{R}$ defined by $f(x) = 2^x$ is injective since for each $y$ in its range, there is exactly one value of $x$ such that $f(x) = y$, namely $x = \log_2 y$.
Definition.  A function $f: X \to Y$ is said to be surjective if for each $y \in Y$, there exists $x \in X$ such that $f(x) = y$, that is, if its range, $f(X) = \{f(x) \mid x \in X\}$, is equal to its codomain, $Y$.
The function $f: \mathbb{R} \to \mathbb{R}$ defined by $f(x) = 2^x$ is not surjective since its range, $\text{Ran}_f = (0, \infty)$, is not equal to its codomain, $\mathbb{R}$.
Definition.  A function is said to be bijective if it is both injective and surjective.
The example $f: \mathbb{R} \to \mathbb{R}$ defined by $f(x) = 2^x$ demonstrates that an injective function is not necessarily a bijective function.
We can transform an injective function into a bijective function by restricting the codomain to equal its range.  For instance, if we restrict the codomain of the function $f: \mathbb{R} \to \mathbb{R}$ defined by $f(x) = 2^x$ to $(0, \infty)$, we create a bijective function $g: \mathbb{R} \to (0, \infty)$ defined by $g(x) = 2^x$.  Since a function is specified by its domain, its codomain, and its graph (the set of ordered pairs that satisfy the function), $g \neq f$ since the functions $f$ and $g$ have different codomains.
It is not necessarily true that if a horizontal line crosses the graph of a function more than once that the function is surjective.  For instance, the $x$-axis crosses the graph of the function $f: \mathbb{R} \to \mathbb{R}$ defined by $f(x) = \sin x$ infinitely many times, but $f$ is not surjective since its range, $\text{Ran}_f = [-1, 1]$, does not equal its codomain, $\mathbb{R}$.

What we can say is that the function $f: \mathbb{R} \to \mathbb{R}$ defined by $f(x) = \sin x$ is not injective since it fails the Horizontal Line Test.
If a function $f: X \to Y$ is surjective, then for each $k \in Y$, the horizontal line $y = k$ must intersect the graph of $f$ at least once.  Otherwise, there would be no $x \in X$ such that $f(x) = k \in Y$.
If a function $f: X \to Y$ is bijective, then for each $k \in Y$, the horizontal line $y = k$ will intersect the graph of $f$ exactly once since it must intersect the graph of $f$ at least once for the function to be surjective and at most once for the function to be injective.

Horizontal line test in graphs


Given $x =\{1,2,3\}, y= \{4,5,6\}$ we see each member of y are greater than all members of x.

Question: Given one set x = {1,2,3} and another set y= {4,5,6}, we can safely say that all members of y are greater than all members of x.
What is the most efficient way to express this in notation (Latex)?
Comment: I think you man "greater than all members of $x$" not "greater than $x$".
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: I'm leaving my answer up *pro tem*, but I now agree with @Community that it is highly unclear what you are asking. What do you mean by "set notation"? You have multiple answers that clearly take very different readings on that.
Comment: Reworded my question to remove ambiguity. Thanks
Answer: Why not just define your own notation? $A>B$ should be unambiguous in most cases. If not, use $A\succ B$ or anything you like.
Answer: $\min(y)>\max(x)$
If you're dealing with infinite sets, $\min$ and $\max$ might technically be not defined (e.g. there is no minimum positive real number), so it gets more complicated. $(\inf(y)>\sup(x))\rightarrow $ (all of $y$ is greater than all of $x$), but the converse it not true. Going back to the example of positive real numbers, all of them are greater than every negative real number, but the $\inf$ of positive numbers and the $\sup$ of negative numbers are both $0$.
Comment: $\inf(y)>\sup(x)$ doesn't  cover all cases. It is possible for it to be true when $\inf(y)=\sup(x)$ and $x\cap y=\emptyset.$
Answer: $$\forall b \in y\forall a \in x(b > a)$$ Hold down Control and hover over the formula to get a menu that will let you see what the $\LaTeX$ looks like (or just click on Edit and then cancel when you've seen enough).
Answer: There is no standard notation to compare sets memberwise. In any case, it is clear that comparing sets member by member as you want gives a lattice, so you can *define_ that for sets $A, $$ you write $A \le B$ if the above relaton holds.
To define the relation, as I understand it (sort the elememnts of both sets, and compare the resulting vectors memberwise if they have the same number of elements), formally isn't easy.


Como enviar elemento select por email?

Question: Tenho um formulário de contato que utiliza JS para validar e PHP para enviar, funciona muito bem com inputs text e afins, gostaria de implementar o select nele. Vou passar meus códigos aqui, temo que fique muito extenso:
Formulário:
<form name="sentMessage" id="contactForm" novalidate>

                        Nome Completo*
                        <input type="text" class="form-control" id="name" required data-validation-required-message="Por favor, insira seu nome.">

                        Telefone*
                        <input type="tel" class="form-control" id="phone" required data-validation-required-message="Por favor, insira seu número de telefone." placeholder="(00) 0000-0000">

                        Email*
                        <input type="email" class="form-control" id="email" required data-validation-required-message="Por favor, insira seu email.">

                 Assunto:
                   <select class="form-control" id="sel1">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                   </select>

                        Mensagem
                        <textarea rows="10" cols="100" class="form-control" id="message" maxlength="999" style="resize:none"></textarea>

                <button type="submit" class="btn btn-success btn-lg">Enviar</button>

            </form>

Validador javascript:
$(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {

        },
        submitSuccess: function($form, event) {
            event.preventDefault();
            var name = $("input#name").val();
            var phone = $("input#phone").val();
            var email = $("input#email").val();
        var sel1 = $("input#sel1").val();
            var message = $("textarea#message").val();
            var firstName = name;
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "bin/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
            sel1: sel1,
            message: message
                },

php:
<?php if(empty($_POST['name'])          ||
   empty($_POST['phone'])       ||
   empty($_POST['email'])       ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
    echo "No arguments Provided!";
    return false;
   }
$name = $_POST['name'];
$phone = $_POST['phone'];
$email_address = $_POST['email'];
$sel1 = $_POST['sel1'];
$message = $_POST['message'];

$to = 'email@example.com';
$email_subject = "Formulário de contato, $name te enviou uma mensagem.";
$email_body = "Você recebeu uma nova mensagem do site.\n\n"."Aqui estão os detalhes:\n\nNome: $name\n\nTelefone: $phone\n\nAssunto: $sel1\n\nEmail: $email_address\n\nMensagem:\n$message";
$headers = "From: $email_address\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

O email chega corretamente para mim, com todos os inputs devidamente preenchidos, porém o "ASSUNTO" (select) fica vazio, alguém poderia me orientar?
Answer: O seu seletor input#sel1 pede um <input> ao invés de um <select>, basta você alterar isto:
        var name = $("input#name").val();
        var phone = $("input#phone").val();
        var email = $("input#email").val();
        var sel1 = $("input#sel1").val(); //Está linha

Pra isto:
        var name = $("input#name").val();
        var phone = $("input#phone").val();
        var email = $("input#email").val();
        var sel1 = $("select#sel1").val();

Ou melhor:
        var name = $("#name").val();
        var phone = $("#phone").val();
        var email = $("#email").val();
        var sel1 = $("#sel1").val();

# é usado para pegar elementos com id no html, lembre-se que ids nunca podem se repetir, por isto omiti no último exemplo o input e select e deixei apenas o #
Recomendo que estudo os selectore CSS para entender como eles funcionam, o próprio manual do jQuery da uma noção:

https://api.jquery.com/category/selectors/
http://www.w3.org/TR/CSS21/selector.html#id-selectors
http://www.w3.org/TR/css3-selectors/
Comment: Cara, primeiramente muito obrigado mesmo!! Nao sei como nao pensei nisso, brigadão!! Queria saber se vc pode me ajudar a fazer com que esse modelo consiga enviar arquivos anexados para meu email tambem, como imagens, etc. Se for algo mais complexo e vc puder me enviar tutoriais ou artigos seria ótimo também. Te agradeço novamente!! Abs

Como enviar elemento select por email?


Can Looping Through a Function "Too Fast" Break It (Node.js)

Question: I am trying to accumulate API responses on a server and return them to the client as a single object.  To do this I am looping through items in an array and mapping the responses back into the original object.  This is working fine for an array of length 1, but logs blanks when looping through larger arrays.
When looping through the array does Node create a new instance of the function or does it keep passing data into the same function even if it hasn't returned a value yet?
loopThroughArray(req, res) {
  for(let i=0; i<req.map.length; i++) {
    stack[i] = (callback) => {
      let data = getApi(req, res, req.map[i], callback)
    }
  }

  async.parallel(stack, (result) => {
      res.json(result)
  })
}

....
function getApi(req, res, num, cb) {
  request({
    url: 'https://example.com/api/' + num
  },
  (error, response, body) => {
    if(error) {
      // Log error
    } else {
      let i = {
        name: JSON.parse(body)['name'],
        age: '100'
      }
      console.log(body) // Returns empty value array.length > 1 (req.map[i])
      cb(i)
    }
  })

If Node is overloading the function, how can I ensure data has been received before running the function again?
Comment: You are not sending any callback.
Comment: I updated the question for more clarity.
Answer: The api calls are async.
When running the loop, the code is making many rest calls without waiting for the answer.
If the loop is not too big then you could synchronize the calls using recursion.
You could also synchronize the calls using nimble:
http://caolan.github.io/nimble/
Comment: Node is asynchronous by nature @matthew. You should avoid making synchronous calls whenever possible in Node
Comment: The function is not returning a json because is async. You could read the json value returned by the api call using a callback
Comment: I have a version of this code that is synchronous with recursion, but I am trying to speed it up by making it more parallel.
Comment: Won't the `console.log` in the `getApi` function body run synchronously?
Comment: @EvanBechtol Yes... I am trying to improve the code, but am not sure why the function isn't returning a JSON object as expected.
Comment: @MartínZaragoza The `console.log` inside the `getApi` block is not returning anything...
Comment: Oh i see... What is the response code? (is it 200 or 204 ... ?)
Comment: @MartínZaragoza For array of length 2 I get a `SyntaxError: Unexpected end of JSON input` logged out.  If I comment out the JSON parsing it will return only the second array items meta data with response code 200.
Answer: a loop waits for the method inside it to finish before it loop back. so there's really no such thing as a loop that moves really fast unless you're using "threading" which your obviously not.
Comment: this is wrong. Rest calls are async using node. The loop does not wait for the body to complete the call
Comment: in simple term its running two loops at the "exact" same time.


Performance problems with ItemizedOverlay.draw()

Question: I have a class:
public class WaypointOverlay extends ItemizedOverlay<OverlayItem>

It overrides the draw() method of the ItemizedOverlay.
In my Activity, I have a map with many overlay items as well as a list.  I noticed from traceviewer output and logcat that MapView.onDraw() was being called many times even when the map goes untouched. This resulted in a really unresponsive list and map (when I have my WaypointOverlay class simply return from these onDraw calls, everything performs well)
How can I have the onDraw calls happen less frequently - ideally only when the MapView changes span?  I tried, in onDraw, checking if the MapView has the same lat/lon span as it did in the last onDraw call, and only drawing if the two are different.  This caused the OverlayItems to only appear when the map was panning or zooming.
Any ideas on improving performance?
Comment: Sounds like there are allot of "invalidate()" invocations going on.  Is your code making that call?
Comment: I make no calls to MapView.invalidate().
Answer: I think I may have solved this problem (for my case, at least).  In my app, the user can navigate away from the map and then return to it, all in the same activity.  Every time the user returned to the map, I re-added all the overlays I had created.  This meant that way too many overlays were on the map - I couldn't see them because they overlapped.  Calling MapView.getOverlays().clear() has made the map and list perform substantially better.


Connection on a vector bundle in terms of sections

Question: Reference for this question is the book Geometry of Differential forms by Morita, page no 191.
In last but one paragraph it says the following,

Suppose we are given an arbitrary bundle $\pi:E\rightarrow M$  with a  connection $\nabla$. We think of $\nabla s$ as  a $1$ form on $M$ whose value on vector field $X$ on $M$  is the section $\nabla_Xs$.

Connection on a vector bundle $\pi:E\rightarrow M$ is a bilinear map $\nabla:X(M)\times \Gamma(E)\rightarrow\Gamma(E)$ satisfying certain conditions where $X(M)$ is the collection of vector fields on $M$ and $\Gamma(E)$ is collection of  sections of vector bundle.
I do not really understand the one that I have quoted above.
$1$ form on $M$  is a $\omega:M\rightarrow \Lambda(TM)$. They are saying $\nabla_s$ is a $1$ form on $M$. We need to say what is $\nabla_s:M\rightarrow \Lambda(TM)$.
Let $m\in M$ then, $\nabla_s(m):T_mM\rightarrow \mathbb{R}$. Let us fix some vector field $X$ on $M$. We need to define $\nabla_s(m)(X(m))$.
Suppose we are in trivial vector bundle, where sections are just smooth maps on $M$ we can define $\nabla_s(m)(X(m))$ as $\nabla_X(s)(m)\in \mathbb{R}$. I do not see how we can think of $\nabla_s$ as a $1$ form  for a bundle which is not trivial.
I see that they are trying to relate connection on a vector bundle to be something that takes a section on $E$ and gives a section on some bundle, definitely not a section on $M$ as they have written.
I fail to understand this.
A connection on a vector bundle is a map that takes a section on $M$ and gives a section on ..????
Answer: No. Morita is saying $\nabla s$ is an $E$-valued 1-form on $M$, i.e. a map $M\mapsto \wedge(TM)\otimes E$. The map $\nabla s$ takes $m\in M$ to the map $(\nabla s)_m: T_mM\rightarrow E_m$ (where $E_m$ is the fibre of $E$ at $m$), given by $(\nabla s)_m(X_m) := (\nabla_Xs)(m)$. Here $X\in\mathfrak{X}(M)$ is any vector field that agrees with $X_m$ at $m$. One can show from the properties of the connection that this quantity is independent of the choice of extension $X$.
Comment: I do not know very much about tensor product of vector bundles. I only know some basic definitions.... $E$ is a vector bundle over $M$ and $\Lambda T(M)$ is a vector bundle over $M$. So, we are taking its tensor product and get a vector bundle $E\otimes \Lambda(TM)$. And I believe $\nabla_s$ you have defined above is a section of this bundle. I do not see why would $\nabla_s(m)$ is in such form, I only know that $\nabla_s(m)$ is in fiber of $E\otimes \Lambda TM$ at $m$. I don't know why such an element is a map that you have defined above
Comment: Ok. So you accept $(\nabla s)(m)$ is in the fibre of $\wedge(TM)\otimes E$ at $m$, i.e. $\wedge(TM)_m\otimes E_m$. The first factor gives a linear map from $T_xM$ to $\mathbb{R}$ (in other words, a 1-form at $m$). The second factor gives an element of $E_m$. Overall, you get a linear map from $T_xM$ to $E_m$, that is, an $E$-valued 1-form.
Comment: I think I understand. Let $a\otimes b\in (T_mM)^*\otimes E_m$ be a basis element. We have $a:T_mM\rightarrow \mathbb{R}$ and $b\in E_m$. Combining these two we would get a map $T_mM\rightarrow E_m$ defined by $v\mapsto a(v)b$. This is well defined as $a(v)$ is a real number and $a(v)b\in E_m$ given $b\in E_m$ as $E_m$ is a real vectorspace
Comment: 6In general any element of $(T_mM)^*\otimes E_m$ is actually a map $T_mM\rightarrow E_m$.. can you give any refer nice for these concepts. We have to also see that if $Y$ is any other vector field whose value at $m$ is same as $X_m$ then $\nabla_Xs(m)=\nabla_Ys(m)$.
Comment: By linearity, the latter property is equivalent to showing that if $X$ vanishes at $m$, then $(\nabla_Xs)(m)=0$. To see this, pick a local coordinate system $(x^i)$, so $X=X^i\frac{\partial}{\partial x^i}$. $X$ vanishing at $m$ means that the functions $X^i$ all vanish at $m$. Then $\nabla_Xs = X^i\nabla_{\frac{\partial}{\partial x^i}}s$. Evaluating this at $m$ shows that $\nabla_Xs$ vanishes at $m$.
Comment: As for a good reference on this stuff, really most books on differential geometry. For example, [Tu has a discussion in his latest book](https://books.google.co.uk/books?id=bmsmDwAAQBAJ&pg=PA77&lpg=PA77&dq=tu+%22connections+at+a+point%22&source=bl&ots=QyK86BKgGG&sig=Uq2_1asZoqJAUflIgDJ0ZMWfdkw&hl=en&sa=X&ved=0ahUKEwi5qJ6H4-7YAhVkUd8KHRS9D2MQ6AEIKTAA#v=onepage&q=tu%20%22connections%20at%20a%20point%22&f=false). I haven't read this, but it's probably pretty good based on his previous books.


Qual a melhor maneira de criar métodos acessíveis a qualquer activity?

Question: Olá. Quando eu preciso criar um método para uma Activity eu simplesmente escrevo ele no código da minha Activity. Por exemplo:
package com.pcriot.maxsoft.testapplication;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private void MeuMetodo() {
        // Código aqui
    }
}

Mas agora, digamos que este método que eu criei precise ser chamado em todas as outras activities. Seria aconselhável criar uma classe para escrever os métodos que seriam utilizados pelas activities?
Uma classe como esta:
package com.pcriot.maxsoft.testapplication;

import android.content.Context;

public class Functions {
    private Context context = null;

    public Functions(Context context) {
        this.context = context;
    }

    public void MeuMetodo1() {
        // Código aqui
    }

    public void MeuMetodo2() {
        // Código aqui
    }

    public void MeuMetodo3() {
        // Código aqui
    }
}

Depois eu poderia chamar cada um deles assim:
package com.pcriot.maxsoft.testapplication;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {
    private Functions Functions = new Functions(MainActivity.this);

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Functions.MeuMetodo1();
    }
}

Então? A maneira que estou fazendo está correta? Ou existe algum outro jeito e que tenha alguma vantagem que eu ainda não saiba.
Comment: Acho que estás a fazer bem, não estou a ver outra forma de fazer isso.
Answer: As possíveis formas de fazer (que me ocorrem) são:
1) Criar uma SuperActivity que as outras Activities estendam e portanto herdem o método em questão:
Vantagem: Se colocar o método em uma SuperActivity for uma decisão de design que faça sentido, o método já estará imediatamente disponível para você em suas outras activities, sem precisar instanciar uma classe que contenha o dito método;
Desvantagem: Você será obrigado a ter SuperActivity como superclasse de todas as Activities que precisarem desse método, o que torna o código mais brittle (engessado). Por isso essa maneira de fornecer o método só deve ser utilizada quando fizer sentido em seu design de classes.
2) Tornar o método estático e chamá-lo sem precisar instanciar a classe:
SuaClasse.metodo();

Vantagem: Dispensa a instanciação da classe.
Desvantagem: A classe corre o risco de se tornar uma classe genérica Utilidades, meio "perdida" no meio do código e apresentando funcionalidades esparsas e sem relação uma com a outra.
3) Instanciar a classe e chamar o método em questão:
SuaClasse objeto = new SuaClasse(contexto);
objeto.metodo();

Desvantagens: As mesmas de uma classe com métodos estáticos, com a desvantagem adicional de correr o risco de memory leaks por vazar um contexto que não seja o contexto global (getApplicationContext()). Por isso procure sempre que possível passar o contexto global no construtor da classe.
Variações possíveis dessa última forma incluem criar um Singleton da classe em questão ou torná-la uma subclasse de Application, declarando-a no AndroidManifest.xml. Novamente, essas formas de implementar devem ser adotadas se fizerem sentido em seu design.
Não creio que tenha citado todas as vantagens e desvantagens, melhorias são bem-vindas.
Comment: Obrigado, está muito bem explicado.


Polar coordinates clarification why is the radians portion wrong despite right angle triangle? Converting $(x,y) = (-6, 2\sqrt{3})$

Question: Trying to plot polar coordinates and got all the right steps until the end where I need to evaluate $\arctan \frac{\sqrt{3}}{-3} = \frac{\pi}{-6}$, but that puts the point on the wrong quadrant. Where did I go wrong?
Comment: The formula $\theta=\arctan(y/x)$ doesn't hold in this case since $x<0$. See the function [ATan2](https://en.wikipedia.org/wiki/Atan2).
Comment: $\tan$ is not invertible in $[0,2\pi)$ (or $[-\pi,\pi)$ depending on your convention), therefore your formula doesn't always hold. You can still use your formula, but then you need to add a suitable integer multiple of $\pi$ (note the periodicity of $\tan$) to get the result to the correct quadrant. With this, you get that $\theta=-\pi/6+\pi=5\pi/6$.
Comment: What do you mean, doesn't arctan x resolve for all points of x including negative? (ie. arctan(-1) = $\frac{-\pi}{4}$?) (Graph: https://www.desmos.com/calculator/sfthrl6gn4)
Comment: Thanks @projectilemotion, but calculator(Ti-84) still evaluates them..? Why.
Also if arctan doesn't evaluate, are there other trig functions that don't evaluate while the calculator still does?
Comment: I think you misunderstood me: $\arctan(x)$ is also defined for negative $x$ (and hence should evaluate to a number on your TI-84). What I meant was that the formula for the angle is not always $\arctan(y/x)$. In particular, that formula only holds on the 1st and 4th quadrant (assuming you assume angles go from $-\pi$ to $\pi$). For the quadrant you are considering, the formula for the angle is $$\theta=\arctan(y/x)+\pi.$$
Comment: I see, so you mean y = arctan x is valid between $(\frac{\pi}{2}, \frac{-\pi}{2})$ ?
Comment: Why can't we use arctan? it seems like the value $\frac{\sqrt{3}}{-3}$ is between $\frac{-\pi}{2}$ and $ \frac{\pi}{2}$ ....? It falls in the 4th quadrant of the unit circle
Answer: I would do it solving a system of linear equations:
\begin{cases}
\cos\theta=-\dfrac{6}{4\sqrt 3}=-\dfrac{\sqrt 3}2 \iff \theta \equiv \pm \dfrac{5\pi} 6\pmod{2\pi},\\
\sin\theta=\dfrac{2\sqrt 3}{4\sqrt 3}=\dfrac12\iff \theta \equiv  \dfrac\pi 6,\dfrac{5\pi}6\pmod{2\pi}.
\end{cases}
So the solution is $\;\theta\equiv\dfrac{5\pi} 6\pmod{2\pi}$, and on the interval $[0,2\pi)$, it is $\;\dfrac{5\pi}6$.
Comment: That can't be right. $(-6,2\sqrt3)$ is in the second quadrant, so $\tfrac\pi2 \leq \theta \leq \pi$.
Comment: @kahen: You're right. I forgot the minus sign in front of $6$. I'll fix it within seconds
Comment: This seems very unintuitive and a scenic route to get there. Why can't we use arctan? it seems like the value $\frac{\sqrt{3}}{-3}$ is between $\frac{-\pi}{2}$ and $ \frac{\pi}{2}$ ....?
Comment: @nvs0000: First it is geometrically intuitive, with the trigonometric circle. Second,  one visualises instantly in which quadrant the solution is.
Answer: The inverse tangent function gives an angle $\theta$ satisfying $-\frac{\pi}{2} \leq \theta \leq \frac{\pi}{2}$ (the right half of the circle when we measure angles in standard position). Sure enough,
$$
\theta = \arctan \biggl( -\frac{\sqrt{3}}{3} \biggr)
= -\arctan \biggl( \frac{\sqrt{3}}{3} \biggr)
= -\frac{\pi}{6}
$$
lies on that interval and has the correct tangent value. However, there are many—infinitely many—angles that have that tangent value. In fact, there are two different angles every time you go around the circle! The upshot: you can add or subtract $\pi$ to $\theta$ as many times as you like without changing the value of its tangent.
Look at the $x$ and $y$ coordinates of the point: it's in the second quadrant, i.e. $\frac{\pi}{2} \leq \theta \leq \pi$.
With a little bit of effort you can see that
$$
\theta + \pi = \frac{5\pi}{6}
$$
gives an angle that lands in the second quadrant, so this is an appropriate angle coordinate for a positive radial coordinate.
Comment: thanks but doesn't $\frac{5\pi}{6}$ also have infinitely many angles with the tangent value..? ie. when ever $2\pi(n) + \frac{5\pi}{6}$ where n goes to infinity.
Comment: Yes, which is why the angle coordinate in polar coordinates is not unique unless we agree on some restriction such as $0 \leq \theta < 2\pi$.
Comment: ok so only going through the circle once. Why can't tangent by on the right side of the circle btw (ie. on the 2nd quadrant)? Wouldn't adding $\pi$ distort it's angle? ie. $\frac{-\pi}{6} = 150 ^{\circ} $ and $\frac{5\pi}{6} = 330 ^{\circ}$ and those aren't equivalent angles..?
Comment: In other words, $(r, \theta) = \bigl( 4\sqrt{3}, \tfrac{5\pi}{6} \bigr)$ and $(r, \theta) = \bigl( 4\sqrt{3}, \tfrac{17\pi}{6} \bigr)$ describe the same point. Even $(r, \theta) = \bigl( -4\sqrt{3}, -\tfrac{\pi}{6} \bigr)$ does!
Answer: Computed result is $-30^\circ$.
Note that $\tan (180^\circ + x) = \tan x$.
Note also that $\theta =\arctan \left(- \dfrac ab\right)$ is equal to $\arctan \left( \dfrac {-a}b\right)$ or $\arctan \left( \dfrac a{-b}\right)$ and we have to choose the right one, the one that matches the original given.


Probability that the square of a random integer ends in 1

Question: From my intro to probability theory book:
What is the probability that a randomly selected positive integer will give a number ending in 1 if it is squared?
Hint: It is enough to consider the 1 digit numbers.
Answer: 0.2
I do not understand why we only need to consider one digit numbers. I see that 1 & 9 are the one digit numbers that produces a square ending in 1, giving a probability of 2/10 of randomly selecting them, but how can we generalize this to all positive integers?
Comment: Hint: the final digit in the product of any two integers will always equal the product of the final digit in each of the two integers - let me know in the comments if you're still having trouble and I can come back and provide a more comprehensive answer.
Answer: In fact that answer is not sufficiently justified given the information in the question.
It depends on the distribution over the positive integers. The question says "randomly chosen", and the burning question is "what the heck does that mean"?
The positive integers can't all be chosen with equal probability*, so the answer therefore depends on how you assign probability to the original set of positive integers.
* (if they think it's possible, they're welcome to attempt to explain how one actually does that, which might be fun to watch)
Even the Hint doesn't pin it down.
Let's consider the 1-digit integers, and the last digit of their squares:
<code> 1  2  3  4  5  6  7  8  9  0
 1  4  9  6  5  6  9  4  1  0
</code>
No doubt they're saying "well, all those last digits have an equal chance of turning up, and so the chance that a square ends in 1 is 2/10. But there's no reasonable basis on which to assert that the last digits do have an equal chance of turning up.
For example, if we toss a coin until we observe a head, and count the number of tosses, that will give a distribution over the integers. With that distribution, the chance is a little over 0.5:
$$p = (\frac{1}{2}+(\frac{1}{2})^9)(1 + (\frac{1}{2})^{10} + (\frac{1}{2})^{20} +...)$$
$$ = \frac{1}{2}\frac{1+(\frac{1}{2})^{10}}{1 - (\frac{1}{2})^{10}}$$
Other answers are possible.
Now it's possible to find distributions for which 0.2 is the right answer, and it's even possible to come up with distributions for which you can immediately work it out from the above table of single digits and the knowledge of the distribution (most obviously, any distribution where the ratios on the single digits are preserved throughout the integers) - but the distributions for which it works are generally substantially less "obvious" or "natural" than say a geometric($\frac{1}{2}$) distribution, like the one I used above.
Comment: (+1) Although I have offered a different answer--on the premise it might indeed be "fun to watch"--there is much wisdom in this one; careful study of its points would be worthwhile.
Comment: Could you please explain in more detail how you got the first line of your equation? What do the exponents represent?
Answer: When a mathematician asks to pick a "random integer" or "random natural number," they usually have in mind a limiting process in which the numbers all "become equally probable."  The process can be quite general: I believe all that you need is that (a) the relative probabilities of any two sets should converge and (b) the relative probabilities of any two finite sets should converge to the ratio of their cardinalities.
One nice set of distributions with these properties is the geometric, where the chance of $k\ge 1$ is given by
$${\Pr}_x(k) = (1-x)x^{k-1}$$
for a parameter $0 \lt x \lt 1$ and values $k\in \{1,2,\ldots\}.$  The figure plots these distributions for $x=0.9, 0.99, 0.999$ and $1\le k\le 100$: as $x$ gets close to $1$, the distributions gets flatter and flatter: more and more uniform.

The advantage of this particular family of probability measures is that the probability of any set $A$ of positive integers, such as those whose squares end in "1", is the limiting value of
$${\Pr}_x(A) = (1-x)\sum_{k\in A} x^{k-1}$$
as $x\to 1.$  This limiting value, which appears to be the product of something going to $0$ (that is, $1-x$) and something that is growing infinitely large (the unnormalized chance of $A$ as given by the sum), often can easily be computed using L'Hopital's Rule.  Let's illustrate with the question in hand, where
$$A=\{1,9,11,19,21,\ldots\}=\{10i+1\ |\ i \ge 0\}\cup\{10i+9\ |\ i \ge 0\} = A_1\cup A_9.$$
Because $A_1$ and $A_9$ are disjoint, this breaks the probability calculation into two parts:
$${\Pr}_x(A) = {\Pr}_x(A_1) + {\Pr}_x(A_9) = (1-x)\left(\sum_{i=0}^\infty x^{10i+1} + \sum_{i=0}^\infty x^{10i+9}\right).$$
Both of these sums are geometric series with common ratios $x^{10},$ which reduces them to
$${\Pr}_x(A) = (1-x)\left(\frac{x}{1-x^{10}} + \frac{x^9}{1-x^{10}}\right) = \frac{(1-x)(x+x^9)}{1-x^{10}}.$$
Because both the numerator and the denominator of this fraction converge to $0$ as $x\to 1,$ L'Hopital's Rule says the limit can be found as the limiting ratio of the derivatives of the numerator and denominator:
$$\lim_{x\to 1}{\Pr}_x(A) = \lim_{x\to 1} \frac{1 - 2x + 9x^8 - 10x^9}{-10x^{9}} = \frac{-2}{-10}=\frac{2}{10}.$$
Clearly we did not just "consider only one-digit numbers" in the calculation--all the positive integers were involved--but because $A_1$ and $A_9$ are defined only in terms of the final digits ($1$ and $9$ respectively), in that sense we only have to be concerned about the final digits (in this particular problem).
Comment: +1 A very nice take on the question. While the limiting geometric is one of the cases where you can "work it out from the above table of single digits and the knowledge of the distribution" (as I mention in my answer), it is arguably a limiting case that would be 'natural' to consider.
Answer: I think the solution is simply as this: every number has only ten possible last digits, which is all that matters to tell if a number ends at 1. Thus, if you select a number at random, the last digit has only ten possibilities, and that's what makes your sample space: you only focus on the last digit. Every number has only ten possible last digits, all with equal probability of appearing: $\Omega=\{0,1,2,...,9\}$, for which the favorable elements for your problem are 1 and 9; thus $P = 2/10 = 0.2$.
Comment: I was afraid you would make that objection, so I need to introduce a more complicated counterexample. What is the chance that a randomly chosen *prime* integer will end in 1? Seemingly this question, too, depends only on the last digit. The answer--$1/4$--is fairly deep; it is an instance of Dirichlet's theorem on arithmetic progressions. Once again I have to insist on maintaining the crucial distinction between a sample space and the range of a random variable. By overlooking that distinction you obtained the correct answer purely by luck and intuition but not by objectively valid reasoning.
Comment: @whuber: almost a year has passed and my mind went back to this episode. After thinking a lot about it, I definetly believe that you are right and I was wrong about my solution. Your answer, BTW, is superb :).
Comment: This answer is invalid because it confuses the sample space with a random variable. The sample space is explicitly the set of "positive integers." The fact that the random variable only has ten possible values does not assure they are equally probable! As a counterexample, contemplate the similar random variable given by the last digit of $x^2+x$. Although the "last digit has ten possibilities," only three values actually arise: $0$, $2$, or $6$. What would you say their chances are: $1/10$ or $1/3$? Neither is plausible under most reasonable probability models for this question.
Comment: I'm not confusing the sample space; I just narrowed it down to ten which are the numbers that matter in the context of the problem (the last ten possible digits of any positive integer). I understand the need to try to go with a full theoretical answer, but the intuitive idea is what I just wrote.
Comment: That's exactly the confusion: the sample space does not change. The question concerns the *random variable* equal to $k^2\mod 10$ for $k\in\{1,2,\ldots\}$. It explicitly does *not* concern just the numbers $\{1,2,\ldots,9,0\}$. My counterexample shows what can go wrong when you ignore this crucial distinction.
Comment: AYD That is not the difference. Your question is about a sample space of positive integers and it concerns the random variable $X$ which assigns to any integer the last digit of its square. It asks for the probability that $X=1.$ No answer can be determined until a probability is given for the entire sample space: that is the point of @Glen_b's answer. Many errors in probability calculations originate with the unfounded assumption that when a random variable has $m$ distinct values ($m=5$ here), then all values must be equally likely. That is what Néstor assumes, without valid justification.
Comment: That is much more clear, I understand your point now. I have no way, with the information given in the question, of establishing that each possible final digit is equally likely for all positive integers. Glen_b's coin toss example is an algorithm to give a probability of selecting a given integer. Depending on how I choose to assign probability across the whole sample space, the answer will be different.
Comment: At the level I am studying, Nestor's and Colin T Bower's answers cover what I needed. The more general solutions are interesting, and I will try to understand them, but are simply beyond me at this point.
Comment: Moreover, @whuber, the sample space (I insist) is not composed by the final result of the square of the positive integer, but by the positive integers themselves, problem which I narrowed down to the last digits of them only. This is similar to the question of writing the sample space for the event :"the sum of two dice is 2". The sample space is $\Omega = \{(1,1), (1,2), ..., (6,6) \}$, and the favorable case is $(1,1)$ only. Note that in my answer I never mentioned what was the random variable, but only what the sample space (of the reduced problem, not of the original problem, I agree) was.
Comment: As for your "counterexample" the intuition is the same: again, what matters are the last digits only of all possible positive integers, whose sample space of the reduced problem (i.e., only to the last digits of the positive integers) is the same: $\Omega = \{0,1,2,3,4,5,6,7,8,9\}$. In this case, the probability of the final digit being, e.g., 2, is $P=4/10$ (only 4 favourable cases), but for the final digit of being 1 is $P=0$. Again: I understand the need for a full theoretical answer but, in this case, the intuition is just as good if you properly transform the problem.
Comment: Luck? You are being a little too harsh here ;-). The way in which I solved this problem is by all means objective, rational and also intuitive, although, it is not generalizable to all problems, as it can't solve the problem you just stated. Also: i DID make the distinction between the sample space (what I used in this problem) and the random variable (which I haven't even mentioned nor on the comments or my answer).
Comment: PS: I don't think we'll make it somewhere discussing this issue because, as I can see, we are both stubborn towards the way of solving this problem (which, I accept: yours is way more elegant and generalizable, but maybe impractical for the OP's current level). I'm afraid this also has to do with our backgrounds also (maths and physics, respectively). I just want to make clear that my answer has a clear logic too (your use of 'luck' is a little offensive, I must say: my answer is not generalizable only due to the assumption of using positive integers only, and will fail if you change that).
Comment: Would it be accurate to say that some of the disagreement here could be summarized, imprecisely but maybe helpfully, as the difference "what is the probability that a random square integer ends in 1" vs "what is the probability that a random positive integer, when squared, ends in 1." I was conceiving of the problem in the second way, and I believe that is what the book meant, and why they offer 0.2 as the answer. If I'm using the word correctly, then the sample space could be reduced to the single integers in the second case but not the first.


Multiple comparisons when examining the results of unrelated trials

Question: Imagine that you have a data set that is like the one below. (The data is all made up and is not specific to the problem.)
trial   n_control   n_intervention   n_control_responded   n_intervention_responded
1       497         1200             54                    91
2       307         908              22                    51
3       552         2042             150                   783
...     ...         ...              ...                   ...
100     2000        11303            713                   3308

Each row represents data about a trial that was conducted, in which an intervention was tried against a control group, and the response in each group was assessed. For the sake of the question, it can be assumed that each trial was done on a distinct sample (no overlap), that the trials were run at different times (not simultaneously), and tested distinct interventions (no duplication).
It is trivial to perform a statistical test on each of these rows and to return a p-value for each one. That p-value could be used to define a success or a failure of that intervention.
My question is: must the p-values which are returned be penalized in some fashion because of the multiple comparison problem? On the surface, the answer to this question is, of course, yes. If you do multiple tests, it is highly likely that one of them will come back as significant due to chance alone.
As is probably obvious, this format at least partially resembles the concept of a meta-analysis. It seems incorrect to say that we should operate on the assumption that, for instance, one out of every twenty papers published with a result of p < 0.05 is wrong. Similarly, it seems far-fetched to think that, as the literature expands, we should have increasingly stringent criteria for statistical significance, until ultimately, we have no ability at all to find anything. It fundamentally seems wrong to state that we should penalize the p-value of a set of unrelated studies in the name of controlling for multiple comparisons. But I have not found much guidance on the questions of how to determine when a set of tests are "different enough" to not require controlling for multiple comparisons.
If multiple comparisons corrects for random chance error, how applicable is it to cases where the multiple tests were performed in distinct experiments, on distinct samples, at distinct times? Put differently, what is the relationship between meta-analysis and multiple comparisons - are all meta-analyses automatically subject to the multiple comparison problem, or is there some standard which makes clear the difference between these two?
Answer: The focus of the methods is slightly different although they are of course not completely unconnected. The meta-analysis of significance values has as its mull hypothesis that all the $p_i$ are drawn from a uniform distribution on (0, 1). The alternative hypothesis is often not clearly stated but is usually that either (a) at least one of the $p_i$ has some other distribution, or (b) all of them have. People who adjust for multiple comparisons usually have a focus on which test has reached their corrected level of significance (or what the coverage of their adjusted confidence intervals is).
To put it another way meta-analysis here answers the question: taking the totality of the dataset together is there any evidence that all the $p_i$ are not uniform? The multiple comparisons approach answers the question: are these specific comparisons beyond the critical value allowing for the number of comparisons made.
Comment: How would you determine which method is more appropriate, though? It seems as though I could squint hard and justify either one.
Comment: @TARehman I have edited in some more explanation
Comment: So, in a sense, the question being answered is different. Meta-analysis asks whether the various experiments truly differ, but multiple comparison correction asks if the differences should be considered meaningful?
Comment: @TARehman that is not quite how I would have put it but I think I agree with you


How to pass jquery or javascript data to Ruby on Rails model?

Question: I'm working on a prototype in Rails 3 and ended up using some jquery (my first time and it's pretty sweet). Although, it appears that I am stuck when submitting the data from my view, which is from the Impromptu JQuery Survey, and into a my database (sqllite3). Let me explain how the page works:

When a drop down item is selected the survey pops up. Also, this is a modal form and there's about 7 questions.

That's pretty much it. My desired outcome is after the user submits the form by clicking finish, each of the answered questions needs to do into the database. Some of the input fields are checkboxes and dropdowns.
Here is a sample of the code, from the last question of the survey:
state7: {
                    html:'Personality Type
<select name="personality" id="rate_find"><option value="enfp">ENFP</option><option value="INTJ">INTJ</option><option value="ESTJ">ESTJ</option><option value="INTP">INTP</option></select>
',
                    buttons: { Back: -1, Cancel: 0, Finish: 1 },
                    focus: 2,
                    submit: function(v, m, f){
                        if (v == 0)
                            $.prompt.close()
                        else
                            if (v == 1)
                                return true; //we're done
                            else
                                if (v = -1)
                                    $.prompt.goToState('state6');//go back
                        return false;
                    }
                }
            }

            $.prompt(temp,{
                callback: function(v,m,f){
                    var str = "You can now process with this given information:
";
                    $.each(f,function(i,obj){
                        str += i + " - " + obj + "
";
                    });
                    $.prompt(str)
                }
            });
        }

Comment: Not sure what the question is (or what that code is for); if there's a form, it sends parameters--can't you access those? What's the data model look like?
Comment: So I can use params? I haven't created a model yet, only views and controllers. I guess I was confused as to how I would actually get the values from javascript and pass them.
Comment: And the code is from the survey modal form. State7 indicates question 7 and the last piece of code writes all the questions to a form at the end.
Comment: I thought you said you were submitting a form. If you are, there's params--that's where params go.
Answer: The key/value pairs containing the information you got through the impromptu popup need to be piled into a POST request like you might expect in a regular form. If you have an ActiveRecord model for the data going into your database, then you could make a form in the view that has the dropdown that triggers the popup, but just make the whole form hidden. Then at the end of your survey you can go through and assign values to the correct input (e.g.
$.each(f,function(i,obj){
     $('input#' + i).val(obj);
});

), and the final 'Finish' button can trigger the submit event on the form. You can look at this question to find out how to check checkboxes with jquery.
Hope that helps!


ChoiceField form is not valid and returns "too many values to unpack"

Question: So, I am having this form where I display a list of all my app models in a drop-down list and expect from the user to choose one so as to display its fields. Below is my form and the models() method, which creates the list of models to be passed as argument to my ChoiceField.
*forms.py*
class dbForm(forms.Form):
    model_classes_field = forms.ChoiceField(choices=models(), required=True,)

def models():
apps = get_app('Directories')
m_id = 0
for model in get_models(apps):
    m_id += 1
    model_classes.append({
        'model_name': model._meta.verbose_name,
        'model_id': m_id,
        'model_table': model._meta.db_table,
        'model_object': model.objects.all()
    })
return model_classes

In my views.py I tried handling the POST data but unfortunately for some reason the form was not valid and I couldn't manipulate any data. Furthermore form.errors does not display anything at all.
*views.py*
def index(request):
if request.method == 'POST': # If the form has been submitted...
    form = dbForm(request.POST) # A form bound to the POST data
    if form.is_valid(): # All validation rules pass
            model_classes_field = form.cleaned_data['model_classes_field']
            return HttpResponseRedirect('/list/') # Redirect after POST
    else:
            print "form: ", form.errors
else:
    form = dbForm() # An unbound form
    print "form: ", form.errors
    print "not valid form"

return render(request, 'Directories/index.html', {
            'form': form,
    })

Furthermore, in the template whenever i try to submit the form it returns an error message "too many values to unpack" and does not redirect me to the next template (list.html).
*index.html*
{% block content%}

 Welcome! this is Directories app!

    <form action="" method="post">{% csrf_token %}
{{ form.model_classes_field.errors }}
Choose from one of the existing tables:
<select id="id_model_classes_field" name="model_classes_field">
{% for choice in form.fields.model_classes_field.choices %}
        <option name="m_id" value="{{ choice.model_table }}">{{choice.model_id}}: {{choice.model_name}}</option>
{% endfor %}
</select>

<input type="submit" value="Change" name="_change" />
</form>

{% endblock %}

The only workaround i found on this is to fill the form action with the template to be redirected at (i.e. action = "list") instead of doing it in the views with return HttpResponseRedirect('/list/') . However, I believe that this does not solve the issue since still the form is not valid and i cannot process data with form.cleaned_data. It's peculiar though that the post data is sent even though the form is not valid.
*
EDIT: Solution
I changed my models() method as such:
def models():
    apps = get_app('Directories')
    for model in get_models(apps):
        model_classes.append( (model._meta.verbose_name, model._meta.db_table), )
    return model_classes

so I included a tuple as instructed by @Rohan and after making a slight alteration to my index.html:
...
{% for choice in form.fields.model_classes_field.choices %}
        <option name="m_id" value="{{choice.0}}">{{choice.0}}</option>
{% endfor %}
...

form is valid and can now process my data.
*
Answer: Value of choices should be list/tuple containing items with exactly 2 elements. But you are creating list of dicts which might be causing the issue.
for model in get_models(apps):
    m_id += 1
    model_classes.append({
        'model_name': model._meta.verbose_name,
        'model_id': m_id,
        'model_table': model._meta.db_table,
        'model_object': model.objects.all()
    })

So you may want to update models() method to return appropriate list/tuple.


Configuring DNS zone file

Question: I have created a DNS zone file called 'goodday.zone' and trying to resolve the domain name to an local IP address '10.25.232.142' . But this is not resolving as desired. Please tell me your suggestions .
Here is how the file looks like. Zone file name goodday.zone
<code>$TTL 3H
@       IN SOA  @ goodday (
                                        0       ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
        NS      goodday
        A       10.25.232.142
        AAAA    ::1
</code>
Comment: The best suggestion I can make is to stop what you're doing and learn about DNS.
Comment: What @JohnGardeniers said.  I strongly recommend you acquire and read [the cricket book](http://shop.oreilly.com/product/9780596100575.do)
Comment: What commands are you running to show that it is not resolving as desired?
Answer: Learn about DNS basics first,refer to http://linuxconfig.org/linux-dns-server-bind-configuration.
you need to set up NS and A record for your domain "goodday" after you set up these you need to restart bind.

Configuring DNS zone file


CasperJS: run multiple instances of script?

Question: I'm fairly new to Javascript programming, and am working on a web scraping script built using CasperJS.
The issue is that it's fairly slow, but it works. I'm trying to think of a way to make an overlaying script/program that starts this script I created, but I'm not sure the best way to do so. I have experimented with the GNU Parallel command, but I'd prefer something using JS, PHP or Python, as I'm more familiar with those languages.
I am also aware that the CasperJS instances will share the cookies and local storage, but that's not an issue on my use case.
If anyone more experienced with this kind of architecture and framework could assist me, I'd appreciate it.
Thanks!
Comment: Define "slow". Can you describe the bottlenecks you think you're experiencing? Could you use [`xargs` to run a bunch of instances in parallel](https://stackoverflow.com/questions/28357997/running-programs-in-parallel-using-xargs)?
Comment: Did you spend an hour walking through the tutorial for GNU Parallel? gnu.org/software/parallel/parallel_tutorial.html
Comment: @tadman the slowness I'm referencing is related to the site I'm scraping. To do all the actions I need, it takes about 3 minutes. Considering I'll need to run about 60 of these before restarting, you can see why I'd want to run simultaneous jobs :)
Comment: @OleTange I didn't go all in on it, but I did read some of the sections and did some testing on the terminal. I'd to look for other alternatives for now (specially in Node) as I'm not that familiar with Shell.
Answer: I ended up using NodeJS' child_process: https://nodejs.org/api/child_process.html
It was pretty much what I wanted and used the same language I already used in the CasperJS script.
Tutorial and example I used: https://era86.github.io/2012/10/11/quick-and-dirty-nodejs-exec-limit-queue.html


Error at removing column from pandas dataframe

Question: I've received an error after trying to remove a column from my dataframe.
KeyError: "['column name'] not found in axis"
Advice is to put axis=1, but I did that and I still receive the same error.
I don't know, what the problem is.
<code>
for i in range(1,len(file_list)):
    data = pd.read_table(file_list[i], encoding='unicode_escape')
    df = pd.DataFrame(data)
    main_dataframe = pd.concat([main_dataframe, df], axis = 1)

main_dataframe = main_dataframe.drop('column name',axis=1)

</code>
Comment: There are a couple of things wrong here that are not directly related to your question but might be helpful: (1) Python starts indexing at 0 not 1, so your code will not be reading the first file. (2) You can just iterate through the file list `for file_name in file_list:` (3) calling `pd.concat` in a loop is inefficient, try appending all dataframes to a list first after reading and then calling `pd.concat` once at the end.
Answer: "column name" is a placeholder for your actual column name.
For example, if you want to delete a column named "Surname", use:
<code>df = df.drop("Surname",axis=1)
</code>
The error you have here is clearly stating that there is no column named "column name" in your dataframe.
Comment: I was aware of that ^^
But thank you. I figuered it out, something else was wrong...


How to get UserDefaults data to Apple Watch even if iPhone is not active

Question: I need to get a number from userDefaults to use in an Apple Watch app to make some calculations, I'm using the WatchConnectivity framework to get this piece of information but what I don't like about the way I have it right now is that the Phone only sends the data to the Watch when the iPhone app is loaded (viewDidLoad), in other words is I launch the Watch app I need to open the iPhone app in order to get the data to the Apple Watch.
Is it possible to get data from iPhone when it is not active?
Here is the code I'm using:
iOS View Controller
class ViewController: UIViewController, WCSessionDelegate {
    var session: WCSession!

    override func viewDidLoad() {
        super.viewDidLoad()

        if WCSession.isSupported() {
            session = WCSession.default()
            session.delegate = self
            session.activate()
        }
    }

    func session(_ session: WCSession, activationDidCompleteWith activationState:WCSessionActivationState, error: Error?) {}
    func sessionDidDeactivate(_ session: WCSession) { }
    func sessionDidBecomeInactive(_ session: WCSession) { }

    func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
        // Reply to watch with data from user defaults
        replyHandler(["dataFromiPhone": readDoubleFromUserDefaults()])
    }
}

WatchOS InterfaceController
class InterfaceController: WKInterfaceController, WCSessionDelegate{

    var session: WCSession!

    var myNumber:Double = 0

    override func willActivate() {
        super.willActivate()

        if (WCSession.isSupported()) {
            session = WCSession.default()
            session.delegate = self
            session.activate()
        }
        getDataFromiPhone()
    }

    override func didDeactivate() {
        super.didDeactivate()
    }
    /// Delegate required method
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {}

    func getDataFromiPhone(){
        //Send Message to phone - I'm not sure if I need this message
        let messageToSend = ["askiPhone":"Hi Phone, send me data from userDefaults."]
        session.sendMessage(messageToSend, replyHandler: { replyMessage in
            /// handle the reply
            let dataFromPhone = replyMessage["dataFromiPhone"] as? String
            DispatchQueue.main.async {
                self.myNumber = Double(dataFromPhone!)!
            }
        }, errorHandler: {error in
            /// catch any errors here
            print("ERROR: \(error)")
        })
    }
}

Answer: I would recommend using App Groups for this. Add an App Group under "Capabilities" for your app's target and the watch extension's target:

And then set your UserDefaults using that App Group:
let appGroupName = "group.mobilemind.SpeedDial"
let appGroupUserDefaults = UserDefaults(suiteName: appGroupName)!

appGroupUserDefaults.set(NSNumber(value: newValue), forKey: "hasRated")
appGroupUserDefaults.synchronize()

Use UserDefaults this way on the app and the watch extension and both will be able to get and set the UserDefaults for the app group.
Edit
This approach does not work on WatchOS 2.0+. However, this approach still works on other types of app extensions.
Comment: I thought this method has been obsoleted and no longer works in iOS9+/WathOS2+. Are you using this method, does it work for you?
Comment: I did some more research and you are correct: http://stackoverflow.com/questions/27007288/watchkit-sdk-not-retrieving-data-from-nsuserdefaults


How to pass argument in ctools_modal_form_wrapper?

Question: A very strange issue come across while using ctools_modal_form_wrapper and ctools-use-modal. I have written a menu item and passed two arguments in it.
$items['a/b/c/d/e/%/edit/%ctools_js'] = array(
    'page callback' => 'generate_tpls_callback',
    'page arguments' => array(5,7),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'file' => 'tpl_popup_create.inc'
  );

Now in this callback I am getting both 5th and 7th argument. But when I pass it to $form_state, form is unable to get this 5th argument. I will explain you more with the help of code.
function generate_tpls_callback($cid, $ajax) {
    if ($ajax) {
        ctools_include('ajax');
        ctools_include('modal');

        $form_state = array(
            'ajax' => TRUE,
            'title' => t('Display box to change title'),
            'cid' => $cid,
        );
        $output = ctools_modal_form_wrapper('myform', $form_state);
        if (!empty($form_state['ajax_commands'])) {
            $output = $form_state['ajax_commands'];
        }
        print ajax_render($output);
        drupal_exit();
    } else {
        print_r("helloooo");
//
    }

}

So, the issue is, when I click a link say "generate tpl" a popup appears that contains form items. I want the above 5th argument appears in this form. i.e. $cid. How can I do this. Please help.
Answer: You must use $form_state to do it.
$form_state['build_info']['args'] = array($node);
function generate_tpls_callback($cid, $ajax) {
    if ($ajax) {
        ctools_include('ajax');
        ctools_include('modal');

        $form_state = array(
            'ajax' => TRUE,
            'title' => t('Display box to change title'),
            'cid' => $cid,
        );
        $form_state['build_info']['args'] = array($myvar);  //Check form below
        $output = ctools_modal_form_wrapper('myform', $form_state);
        if (!empty($form_state['ajax_commands'])) {
            $output = $form_state['ajax_commands'];
        }
        print ajax_render($output);
        drupal_exit();
    } else {
    }

}

function myform($form, &$form_state, $myvar) {
...
}


Why IEqualityComparer has GetHashCode() method?

Question: IEqualityComparer in the namespace System.Collections.Generic has following methods:
bool Equals(T x, T y);
int GetHashCode(T obj);

Since this inteface is used to check equality of objects, the first method Equals makes sense. But why do we need to implement GetHashCode also? Why does it exist in the interface in the first place? When is it needed and why?
I'm using it with Enumerable.Distinct() method in the namespace System.Linq, and I'm surprised to see that even GetHashCode() is getting called, along with Equals(). Why? How does Distinct work?
Answer: For details on how Distinct works (or at least a simple example implementation) see my Edulinq blog post on it (old - 404).
To put it simply, a hash code which corresponds to the appropriate equality comparison makes it cheaper to create a set of items. That's useful in a lot of situations - such as Distinct, Except, Intersect, Union, Join, GroupJoin, GroupBy, ToLookup and so on.
Answer: GetHashCode is used in HashTables, Dictionaries and others to optimize the search. Have a look here: http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx
Comment: I didn't answer that part. Is that really a reason to downvote my post? It's not wrong, because I only answered part of the question.
Comment: @Daniel: I didn't downvote it. :|... +1 from me for partially answering my question. :)
Comment: @Nawaz: Think about how you'd implement Distinct... think about how similar a set is to the keys in a dictionary...
Comment: @Nawaz: I am sorry. Someone did and I interpreted your comment as the explanation, why you did it.
Comment: @Jon Skeet : I'm reading your blog. It looks good. Have you explained such thing in your book? Actually, I want to learn such thing in detail. Kindly suggest me where should I start from.
Comment: @Nawaz: I don't go into that aspect in particular detail in the book. You may want to read through the whole of Edulinq though - the last post in the series has a table of contents. http://msmvps.com/blogs/jon_skeet/archive/2011/02/23/reimplementing-linq-to-objects-part-45-conclusion-and-list-of-posts.aspx
Comment: @Jon Skeet: Thanks. I also ordered your book, this edition :  http://www.flipkart.com/depth-2nd-ed-jon-skeet-book-9350040607
Comment: @Nawaz: Cool - hope you enjoy it :)
Comment: For those looking, Skeet's Edulinq series & Table of Contents is available here: http://codeblog.jonskeet.uk/2011/02/23/reimplementing-linq-to-objects-part-45-conclusion-and-list-of-posts/
Answer: Because the Guidelines for Overriding Equals() and Operator == (C# Programming Guide) says:

It is recommended that any class that overrides Equals also override Object.GetHashCode.

This is because Hashtables etc expects that two objects that are equal have the same hashcode.
Answer: The purpose of IEqualityComparer(Of T) is to allow the use of a comparison method which is semantically different from the default Object.Equals--one which may cause two objects to be considered equal even if Object.Equals would consider them different.  Because equal objects must have equal hash codes, and because things which the EqualityComparer's Equals method considers equal but Object.Equals considers unequal might have different hash codes, it is necessary for the the EqualityComparer to use a different hash-coding method.
A more interesting situation exists with IEquatable(Of T).  That is expected never to report two objects as equal if Object.Equals reports them unequal.  For any unsealed class to implement IEquatable(Of T) is dangerous; too bad there's no generic constraint which would forbid the use of unsealed classes.


custom "register" button on a form - problem with redirection

Question: How to make a custom register button in the user login form (block) so that it redirects to 'user/register' ?
Currently, when I click my custom "Register" button, the code in _mymodule_register is executed (I debugged), but the page just reloads, it does not go to user/register. I tried both drupal_goto and form redirect, but nothing works.
function mymodule_form_user_login_block_alter(&$form, $form_state, $form_id) {
  $form['actions']['register'] = array(
    '#type' => 'submit',
    '#value' => t('Register'),
    '#submit' => array('_mymodule_register'),
    '#limit_validation_errors' => array(),
  );
}

function _mymodule_register($form, $form_state) {
  $form_state['redirect'] = 'user/register';
  //drupal_goto('user/register');
}

Answer: Use below code to achieve the same functionality.
function mymodule_form_user_login_block_alter(&$form, $form_state, $form_id) {
  $form['actions']['register'] = array(
    '#markup' => l('Register', 'user/register'),
  );
}

Theme it using css to look like a button. Done !
Comment: Thanks, that's a good tip! In order to achieve exactly the same look between the true "Login" button and the "Register" link, I had to style also the standard "Login" button (with exactly the same class as "Register" link). This required adding the class to the input submit form element, by adding this line of code at the bottom of the above function: `$form['actions']['submit']['#attributes']['class'][] = 'mybutton';` - now the button and the link look the same


In NHL hockey games decided in regulation time, in which period are the most winning goals scored?

Question: This is an old question, in my mind. I have always believed the answer is the third period, but others disagree.
Comment: A related older question: [In which part of ice hockey game most goals are scored?](https://sports.stackexchange.com/q/13567)
Answer: This is not a full answer, but an answer that may lead to the full answer.
To avoid confusion, I interpret "winning goal" as "the most recent goal that put the team ahead with no further lead changes." For example, if the winning team shuts out their opponent and scored the first goal during the first period, the "winning goal" was scored during the first period.
Using the following query on Pro Hockey Reference:

For all games, from 1979-80 to 2018-19, in the regular season, team won game, for games that ended in regulation, for goals that put the team ahead, sorted by descending Game Date.

One can determine "the most recent goal that put the team ahead with no further lead changes," though it would take removing all go-ahead goals for each game in the query except the most recent goal that put the team ahead during the respective game.
Comment: Yes, in each decided (not tied) game there is only one winning goal.


shutdown -m \\crashbox -r -t 03 windows7

Question: As a server administrator i can shutdown the system on network with
shutdown -m \crashbox -r -t 03
i have one PC on network with windows7 and this pc is also not part of domain but i also have its IP and name.
when i try to execute this command i got message
Access denied
Thanks
Answer: Make sure the "My Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\forceguest" key is set to "0" on the Windows 7 machine.
You may want to look into the PSTools utlity called PSShutdown which is more powerful and gives you more options.


Why is (ana)cron not running any of my jobs and giving no error output?

Question: I have one cron job installed but not running. I installed it with crontab -e and entered the following.
0 12 * * * /var/www/drupal/scripts/dump_sites
* * * * * wall /tmp/test

I put the second command for testing purposes. There is indeed a file /tmp/test, it simply has "this is a test" in it.
When I exit crontab -e I receive no error messages. There are no log files for cron in /var/log/. I stopped cron with service cron stop and tried starting it with cron -L 2 to get better debug output, but there are still no logs.
I've ran /var/www/drupal/scripts/dump_sites manually and I get the expected behavior, i.e. output files appear where I want them to. When I try with cron, I do not get the expected behavior.
When I do ps aux | grep cron I can see it with an associated process ID.
I gave up on cron momentarily and tried anacron. ps aux | grep cron now yields the following. However; my dump_sites script still doesn't run.
devcampus :: /var/www/drupal » ps aux | grep cron
root     15635  0.0  0.1  12440   928 ?        Ss   11:59   0:00 anacron -f
root     15816  0.0  0.1   4092   608 ?        S    12:04   0:00 /bin/sh -c nice run-parts --report /etc/cron.daily
root     15818  0.0  0.1   3996   620 ?        SN   12:04   0:00 run-parts --report /etc/cron.daily
root     15825  0.0  0.1   4092   680 ?        SN   12:04   0:00 /bin/sh /etc/cron.daily/apt

My /etc/anacrontab file looks like this.
# /etc/anacrontab: configuration file for anacron

# See anacron(8) and anacrontab(5) for details.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# These replace cron's entries
1       5       cron.daily       nice run-parts --report /etc/cron.daily
7       10      cron.weekly      nice run-parts --report /etc/cron.weekly
@monthly        15      cron.monthly nice run-parts --report /etc/cron.monthly

# period  delay  job-identifier  command
@daily    14     backup          /var/www/drupal/scripts/dump_sites

I'm running Ubuntu 10.04, and I believe this box is running on a Xen virtualization server.
devcampus :: /var/www/drup
2.6.32-23-server

Update: apparently it's working with anacron.

As per request, here's dump_sites:
#!/usr/bin/env ruby

DRUPAL_ROOT = File.expand_path(File.dirname(__FILE__) + '/../')
SITES_ROOT = File.join(DRUPAL_ROOT, 'sites')
CONFIG_FILES = Dir.glob(File.join(SITES_ROOT, "*", "dbconfig.php"))

databases = CONFIG_FILES.map do |cf|
  contents = File.read(cf)
  contents =~ /dbname='(.*)'/ ? $1 : nil
end

databases.uniq!
databases.sort!

databases.each do |db|
  file_name = File.join(DRUPAL_ROOT, "db_dumps", "#{db}_#{Time.now.strftime("%Y-%m-%d-%H-%M-%S")}.sql")
  `mysqldump -uusername -ppassword #{db} > #{file_name}`
end

Just a plain old ruby script.
Comment: Does your `wall` work from `cron`?
Comment: I'm not familiar with drupal CMS could you post the content of dump_sites ? depending of it is content the problem could be the cron not having the set of env you have as a user resulting on the script not being executed.
Comment: It's just a plain old Ruby script, but I've added there anyway. Perhaps cron isn't able to see `mysqldump` or something.
Answer: Your cron runs should be logged in /var/log/syslog. You should be getting email if there are errors.
Usually when a script runs from the command line and won't from cron it's because of a difference in environment. It's a good idea to set the PATH variable explicitly and/or use full paths to all files and executables. I see that you've done that in your crontab entry, but you should check the script itself.
In addition to PATH there may be other environment dependencies that your script has. Without see it, I can't guess what they might be.
Answer: Remember that cron scripts don't run with your full user environment (PATH, etc.), so it's quite possible that cron is running your script, but that the script isn't working.
Answer: cron errors usually go to mail. Have you tried checking that? Just type in mail at your command line and it you might just see a list of messages from cron.
Comment: Actually all CRON output goes to mail.  But if the job doesn't generate output there is no mail.
Comment: Oh ok. Thanks! I guess I didn't notice because, usually, my std output goes to a file or something.