Parametrizing Walks on Sphere and Torus

Question:
This question is very underdeveloped, but I was wondering if there was a map from the sphere to the torus which preserves length of closed curves? I was just thinking about taking a walk on a sphere and coming back to my starting point. Could I possibly parametrize a similar walk on the torus having the same length. I tried to get a better understanding of this question by making deforming the sphere until it was almost identical to the torus, topologically of course, but since the torus in genus-1 there is only but so much I can do.
Answer: It is quite amazing but such maps do exist!
Call a map between two metric spaces (say, Riemannian manifolds) $f: M\to N$ a path-isometry if it preserves lengths of all paths. Recall that if $p: [a,b]\to M$ is a path (say, Lipschitz-continuous), then its length is defined as
$$
\int_a^b |p'(t)|dt.
$$
Example. $f: R\to R$, $f(x)=|x|$.
This map is not a homeomorphism even locally, but it preserves lengths of paths (since the derivative of $f$ has absolute value $1$ a.e.). Of course, $f$ is not $C^1$ but merely Lipschitz, but that's the natural regularity condition since all path-isometries are 1-Lipschitz.
M.Gromov in his book "Partial Differential Relations" proved the following amazing theorem (see 2.4.11 in the book):
Theorem. For every Riemannian surface $M$ there exists a path-isometry $f: M\to R^2$ (where $R^2$ is equipped with the standard flat metric).
Gromov proved much more, but the above theorem is enough for us.
Therefore, take Gromov's path-isometry $g: S^2\to R^2$; its image is contained in a disk $D$. Now, the torus admits a flat metric and $D$ admits an isometric map $i$ to such flat torus $T^2$.  Lastly, the composition
$$
f=i\circ g: S^2\to T^2
$$
is the required path-isometry.
Edit. Suppose you want to impose an extra regularity assumption on your maps, namely, $f\in C^1$ (continuously differentiable). Then one can verify that all $C^1$-smooth path-isometries are actually Riemannian isometries in the sense that the derivative $df: TM\to TN$ preserves lengths of tangent vectors. In particular, such $f$ is an immersion: $df_m: T_mM\to T_{f(m)}N$ is injective for all $m\in M$.
Then one observes that an immersion $f: S^2\to T^2$ do not exist. One can either prove it by verifying that such $f$ would have to be a covering map (and the sphere does not cover the torus) or simply take a nowhere vanishing vector field $X$ on $T^2$ and take its pull-back $Y=f^*(X)$ under $f$:
$Y(m)\in T_mS^2$ is the unique vector such that $df(Y(m))=X(f(m))$.
Then $Y$ would be a nowhere vanishing vector field on $S^2$, which contradicts the Hairy Ball theorem.
Comment: That's amazing indeed-I'm glad you saw this.

Parametrizing Walks on Sphere and Torus


Parâmetro $_FILES indefinido

Question: Bom dia, estou tendo um problema há algum tempo em um sistema que estou desenvolvendo, todo o CRUD está funcionando perfeitamente, porém quando coloquei um campo File para adicionar foto ao cadastro, por algum motivo acaba mostrando alerta na persistência que a variável foi indefinida, quando ela deveria estar.
HTML:
<form method="post" class="form-horizontal form-persistencia" id="form-usuario" action="dao/persistencia.php" enctype="multipart/form-data">
    <? if ($modo == 'edicao') {
        echo '<input type="hidden" name="id" value="<? echo $id; ?>">';
    }?>

        Nível:(*)
        <input type="radio" name="nivel" value="admin" id="admin" <? if($modo == 'edicao') { if ($nivel == 'admin') {echo 'checked';} ;} ?>>admin
        <input type="radio" name="nivel" value="usuario" id="usuario" <? if($modo == 'edicao') { if ($nivel == 'usuario') {echo 'checked';} ;} ?>>usuario

        Nome:(*)
        <input type="text" class="form-control" name="nome" id="nome" autofocus value="<? if($modo == 'edicao') {echo $nome;} ?>">

        Login:(*)
        <input type="text" class="form-control" name="login" id="login" value="<? if($modo == 'edicao') {echo $login;} ?>">

        Senha:(*)
        <input type="password" class="form-control" name="senha" id="senha" value="">

        E-Mail:(*)
        <input type="text" class="form-control" name="email" id="email" value="<? if($modo == 'edicao') {echo $email;} ?>">

        Foto:
        <input type="file"  name="foto" id="foto" value="">

                     Fechar

                <button disabled type="button" name="submit" id="submit" class="btn btn-lg btn-warning" onclick="verificaFormulario()">
                     Salvar
                </button>

    <input type="hidden" name="id" value="<? if($modo == 'edicao') {echo $id;} ?>">
    <input type="hidden" name="modo" value="<? if($modo == 'edicao') {echo 'edicao';} else if($modo == 'insercao') {echo 'insercao';} ?>">
    <input type="hidden" name="tabela" value="usuario">
</form>

AJAX:
function submeter() {
    $("#form-usuario").ajaxSubmit().data('jqxhr').done(function(data,status,xhr){
      $('#submeter').html(data);
   }).fail(function(err,status,xhr){
      console.log(err);
   });
    $.ajax({
        url: 'dao/persistencia.php',
        type: 'POST',
        data: $('#form-usuario').serialize(),
        mimeType: "multipart/form-data",
        cache: false,
        // contentType: false,
        processData: false,
        success: function(data) {
            $('#submeter').html(data);
            $tabela.bootstrapTable('refresh');
            alert("Usuário cadastrado com sucesso!");
            $formulario[0].reset();
        }
    });
};

PHP
if ($_POST['modo'] == 'insercao') {
       $img = $_FILES;
       var_dump($img);
      // pegar o nome do arquivo, name é um atributo de vetor que está salvo
      $imgName = $_FILES['foto']['name'];
      $imgTmpName = $_FILES['foto']['tmp_name'];
      $imgSize = $_FILES['foto']['size'];
      $imgError = $_FILES['foto']['error'];
      $imgType = $_FILES['foto']['type'];

      $imgExt = explode('.', $imgName);
      $imgActualExt = strtolower(end($imgExt));

      // informação das extensões permitidas de arquivo
      $permitido = array('jpg', 'jpeg', 'png', 'pdf');

      // se o tipo da imagem está dentro do permitido
      if (in_array($imgActualExt, $permitido)) {
        // verificar se não tem erros na imagem
        if ($imgError === 0) {
          // se o tamanho do arquivo for menor que 50mb
          if ($imgSize < 50000) {
            $imgNameNew = str_replace(" ", "", strtolower($_POST['nome'])).".".$imgActualExt;
            $imgDestination = '../imagens/imagens_usuario/' . $imgNameNew;
            // Move o arquivo enviado dos arquivos temporarios para o destinatario abaixo
            move_uploaded_file($imgTmpName, $imgDestination);
          } else {
            echo "Tamanho da imagem é maior do que o permitido";
          }
        } else {
          echo "Ocorreu um erro ao fazer upload da imagem!";
        }
      } else {
        echo "Extensão não permitida!";
      }

      $sql = sprintf("INSERT INTO usuario (user_nivel, user_nome, user_login, user_senha, user_email, user_foto)
                                        VALUES (%s, %s, %s, %s, %s, %s)",
                                    GetSQLValueString($_POST['nivel'], "text"),
                                    GetSQLValueString($_POST['nome'], "text"),
                                    GetSQLValueString($_POST['login'], "text"),
                                    GetSQLValueString(md5($_POST['senha']), "text"),
                                    GetSQLValueString($_POST['email'], "text"),
                                    GetSQLValueString($imgNameNew, "text"));

O erro da diretamente na linha em que você declara o $img como o arquivo de "foto".
Comment: Me parece tudo em ordem. Mas tive uma dúvida. Voce nao tem botao submit. Como está enviando as informções?
Comment: Você está enviando o formulário por ajax?
Comment: Sim, o botão não tem submit porque a submissão do formulário está sendo feita por AJAX.
Comment: Tem [várias perguntas](https://pt.stackoverflow.com/search?tab=votes&q=%5bphp%5d%20ajax%20upload) sobre isso no site caso ainda fique com dúvidas.
Answer: @aleque_b, o envio de FILE por ajax não funciona igual o envio de um formulário comum.
Antes do fechamento do body e após o include do jquery, inclua o script:

Verifique a biblioteca jqueryForm:
https://github.com/jquery-form/form
Comment: Colei este script em uma função Ready mas mesmo assim a persistência não reconhece o campo img.
Comment: você colocou o parâmetro **action** no formulário?
Comment: Por que colocar quando você faz o envio do formulário via AJAX?
Comment: @aleque_b é como funciona a biblioteca. Você também pode passar a URL destino como parâmetro na função ajaxSubmit(), além de outras opções. Mais info -> http://jquery.malsup.com/form/#ajaxSubmit
Comment: Ok, com o action setado para minha persistencia eu consegui enviar o cadastro com sucesso, porém são inseridos duas colunas no banco de dados, uma com a imagem e outra não. Acredito que esteja mandando 1 como submissão do formulário com HTML puro e outro por AJAX.
Comment: atualize o seu código na pergunta, por favor
Comment: Atualizado o código @gabriel-carvalho
Comment: @aleque_b você está enviando o ajaxSubmit() e depois o $.ajax novamente, remova o segundo por favor!
Comment: Funcionou! Me poupou muito do meu tempo do trabalho, muito obrigado!
Comment: @aleque_b por favor sinalize a resposta como correta.

Parâmetro $_FILES indefinido


Manipular duas listas de um componente Drag and Drop em diferentes ManagedBeans

Question: Estou utilizando o componente DataTable Drag And Drop. Contextualizando é o seguinte:
Tenho um cadastro baseado em passos. Onde no primeiro passo insiro as informações de um Edital X, o que é manipulado pelo editalBean, já no segundo passo eu tenho o componente Drag and Drop com as Disciplinas a serem escolhidas, até ai tudo bem. Se eu fizer que nem sugere a documentação eu consigo fazer funcionar numa boa. Mas eis que vem o problema: O método do meu disciplinasBean precisa que seja passado um centro (entidade) como parâmetro e esse centro está no editalBean. A minha solução foi colocar a lista de disciplinas selecionadas no disciplinasBean e a lista completa de disciplinas no editalBean (que é onde eu posso passar o parâmetro).
O método que manipula essas duas listas é esse (quando estão na mesmo bean):
public void onDisciplinaDrop(DragDropEvent ddEvent) {
        Disciplina disciplina = ((Disciplina) ddEvent.getData());

        listaSelecionadoss.add(disciplina);
        listaCompleta.remove(disciplina);
    }

Então a disciplina é adicionada em uma tabela e removida de outra. Mas como eu coloquei a lista completa de disciplinas em outro bean, eu não sei como removê-la.
O meu método onDisciplinaDrop está no disciplinaBean e a minha listaCompleta está no editalBean. Como posso fazer para fazer a remoção correta?
Meus códigos:
EditalBean.java
@ManagedBean(name="editalBean")
@SessionScoped
public class EditalBean {

    private Edital edital;
    private EditalDAO editalDAO = new EditalDAO();
    private Centro centro;
    private CentroDAO centroDAO = new CentroDAO();
    private DisciplinaDAO disciplinaDAO = new DisciplinaDAO();

    private List<Disciplina> listaPorCentro;

    public List<Disciplina> getListaPorCentro() {
        listaPorCentro = disciplinaDAO.getListaDisciplinaPorCentro(edital.getAno(), edital.getPeriodo(), centro);
        return listaPorCentro;
    }

    public void setListaPorCentro(List<Disciplina> listaPorCentro) {
        this.listaPorCentro = listaPorCentro;
    }

DisciplinaBean.java
@ManagedBean(name="disciplinaBean")
@SessionScoped
public class DisciplinaBean {

    private Disciplina disciplina;
    private Disciplina disciplinaSelecionada;
    private List<Disciplina> droppedDisciplinas = new ArrayList<Disciplina>();
    private DisciplinaDAO disciplinaDAO = new DisciplinaDAO();

    public void onDisciplinaDrop(DragDropEvent ddEvent) {
        if(droppedDisciplinas != null){
            droppedDisciplinas.add(d);
        }else {
            System.out.println("droppedDisciplinas é nulo.");
        }
    }

Se precisarem de mais detalhes tento explicar melhor. Obrigado.
Comment: A necessidade geral eu entendi mas o problema específico não ficou claro pra mim. Imagino que sua dificuldade esteja em usar em um Bean os objetos que foram instanciados em outro Bean. É isso? Duas sugestões: considere usar um único bean para recursos de uma mesma página que interagem tanto entre si; e considere usar ViewScoped pois SessionScoped pode prejudicar bastante a experiência do usuário.
Comment: Bom dia @Caffé, o meu problema é exatamente esse, através do DisciplinaBean conseguir manipular um objeto que está no EditalBean, então o melhor seria eu criar um Bean tipo: formCadastroBean (já que é um form de cadastro) e dentro dele eu trabalhar com os dois beans? É mais ou menos isso? E qual a diferença entre Session Scoped e View Scoped, eles interferem nisso?
Answer: Então sua dificuldade é acessar em um Bean os objetos que foram instanciados em outro Bean
Para atender às requisições do usuário em recursos tão interligados em uma mesma página, não há problema em utilizar o mesmo bean e recomendo que o faça, assim você elimina a necessidade de injetar objetos de um bean em outro, o que gera um código bastante esquisito.
Entretanto, se você quer utilizar dois beans, uma maneira de injetar a instância de um bean em outro bean é:
@ManagedBean
@SessionScoped
public class DisciplinaBean {

    //...

    @ManagedProperty(value="#{editalBean}")
    private EditalBean editalBean;

    // É esquisito, mas este set é necessário
    public void setEditalBean(EditalBean editalBean) {
        this.editalBean = editalBean;
    }

    private void metodoQualquerUsandoOBeanIntegado() {
        Centro centro = editalBean.getCentro();
    }

    //...

}
Observação: você não precisa passar name="editalBean" para anotação @ManagedBean da classe EditalBean, pois por convenção o nome da instância deste bean já será de fato editalBean, de modo que você está se repetindo.
Outra observação: procure utilizar beans ViewScoped em vez de SessionScoped. A vantagem é que um ViewScoped é criado na requisição da página e seu escopo limita-se a um tab do navegador, enquanto o SessionScoped dura por toda a sessão e além de os objetos não serem recolhidos da memória o usuário pode ter uma experiência ruim ao tentar trabalhar em duas tabs ao mesmo tempo.
SessionScoped deve ser usado apenas para dados da sessão de fato, como para as preferências do usuário e suas credenciais.
Lembrando que para o meu código acima funcionar, ele precisa que o EditalBean seja de fato de um escopo abrangente, tal qual o SessionScoped que você está utilizando. Então, recaptulando minha sugestão geral:
Conclusão:
Utilize um único bean para tratar interações do usuário com recursos muito integrados de uma mesma página, assim você evita de precisar injetar um bean no outro (que resultaria em um código ruim) e evita de ter que usar SessionScoped, podendo usar ViewScoped que facilita melhor utilização da memória disponível e favorece uma melhor experiência do usuário.
Comment: Deu certinho. Muito obrigado @Caffé, excelente resposta!


Classes, Member Functions & Separate compilation

Question: Anyone knows how to implement a function to use Classes and move functionality into the classes. How can i add appropriate member functions (or methods) to each class so as to implement the functionality of the function .. maybe possibly adding parametized constructors?? For example, how would i do so for a function initially like this:
//constant definitions
const int MAX_NUM_ACCOUNTS = 50;

BankAccount account[MAX_NUM_ACCOUNTS];

int findacct(const BankAccount account[], int num_accts, int requested_account);

{int main()}

// Function findacct:
int findacct(const BankAccount account[], int num_accts, int requested_account)
{
    for (int index = 0; index < num_accts; index++)
        if (account[index].acct_num == requested_account)
            return index;
    return -1;
}

Comment: Kudos for getting '{int main()}' to compile
Answer: I'm not sure what programming language you're using, thus I have written brief sudo-code of it, hope it'll help
Class BankAccount{
    //first you need to list its properties e.g.
    int accountNumber;
    string name;

    //and then you can either construct a constructor or just use the default constructor

    //then you declare your method within the related class
    int findacc(BankAccount account[], int num_acc, int req_acc){
        for(int i=0; i < num_acc; i++){
            if...
                return...
        }
        return 1;
    }
}

on your main()
BankAccount bank = new BankAccount(); //calling the constructor
bank.findacc(pass the parameter)

Answer: findacct is a bad example of a function to be moved inside a class because doesn't do anything on a specific account and just searches among several accounts.
You can move this kind of function inside the BankAccount class as a static member function, but static member functions are really not that different from global functions with fancy names.
Much more interesting for the OOP approach would be moving some function that acts on a specific bank account inside the BankAccount class e.g. something like changing from
bool withdraw(int account_id, int amount)

to
bool BankAccount::withdraw(int amount)

In the following example code I've stored all accounts in a private vector. To create a new account you must call a static class function providing the ID number. Note that this code contains many subtleties and can be dangerous to use as a basis unless you understand it fully... this is unfortunately a characteristic of C++ where apparently logical statements may act logically or can just make your computer to act strangely. My suggestion is to grab a good C++ book and read it cover to cover before or while experimenting with the language.
C++ is just too complex and sometimes illogical (for historical reasons) to learn it just with experimentation.
#include <vector>
#include <algorithm>
#include <stdlib.h>
#include <stdio.h>

class BankAccount
{
private:
    int id;        // Unique identifier for this account
    int balance;   // How much money is present on this account

    static std::vector<BankAccount*> accounts; // Global list of valid accounts

    // Constructor - private!
    BankAccount(int id) : id(id), balance(0)
    {
        // Add to global accounts list
        accounts.push_back(this);
    }

    // Destructor - also private
    ~BankAccount()
    {
        // Remove from global accounts list
        accounts.erase(std::find(accounts.begin(), accounts.end(),
                                 this));
    }

public:
    // Public global function to create a new account
    static bool createAccount(int id)
    {
        if (find(id) != NULL)
        {
            return false;
        }
        else
        {
            new BankAccount(id);
            return true;
        }
    }

    // This is a global function that given the unique identifiers
    // returns a pointer to the account or NULL if non-existent
    static BankAccount *find(int id)
    {
        for (int i=0,n=accounts.size(); i<n; i++)
            if (accounts[i]->getId() == id)
                return accounts[i];
        return NULL;
    }

    // This is a global function that transfers money from one
    // account to another and returns true if the operation is
    // successful (i.e. if the source account has enough money)
    static bool transfer(int from_id, int to_id, int amount)
    {
        BankAccount *from = find(from_id);
        BankAccount *to = find(to_id);
        if (from != NULL &&         // Is first account valid?
            to != NULL &&           // Is second account valid?
            from->withdraw(amount)) // Is there enough money?
        {
            to->deposit(amount);    // move the withdrawn money
            return true;
        }
        else
        {
            // Operation did not succeed
            return false;
        }
    }

    // Returns the id of the account
    int getId()
    {
        return id;
    }

    // Returns the current balance for the account
    int getBalance()
    {
        return balance;
    }

    // Deposit a sum on the bank account
    void deposit(int amount)
    {
        balance += amount;
    }

    // Tries to withdraw the specified amount from the account
    bool withdraw(int amount)
    {
        if (amount <= balance)
        {
            balance -= amount;
            return true;
        }
        else
        {
            return false;
        }
    }
};

// This is also needed; the declaration of accounts inside
// the class (.h) doesn't actually allocate the vector... simply
// tells that the following line will be present in a .cpp
std::vector<BankAccount*> BankAccount::accounts;

///////////////////////////////////////////////////////////////////////////////////

// Do some test...

#define check(x) \
    do { printf("check: %s\n", #x); if (!(x)) {                        \
            printf("*** Fatal error (line %i)", __LINE__);             \
            exit(1); }}while(0)

int main(int argc, const char *argv[])
{
    check(BankAccount::createAccount(6502) == true);
    check(BankAccount::createAccount(386) == true);

    // duplicate account!
    check(BankAccount::createAccount(6502) == false);

    // Not enough founds
    check(BankAccount::transfer(386, 6502, 1000) == false);

    // Deposit
    BankAccount *p386 = BankAccount::find(386);
    check(p386 != NULL);
    p386->deposit(1000);

    // Valid and invalid transfers...
    check(BankAccount::transfer(386, 6502, 1000) == true);  // ok
    check(BankAccount::transfer(386, 6502, 1000) == false); // No more funds
    check(BankAccount::transfer(6502, 386, 500) == true);   // Give some back
    check(BankAccount::transfer(386, 6502, 1000) == false); // Not enough funds
    check(BankAccount::transfer(386, 6502, 400) == true);   // ok
    check(BankAccount::find(386)->getBalance() == 100);
    check(BankAccount::find(6502)->getBalance() == 900);
    return 0;
}

Comment: Ok I see what you mean. For a function like withdrawal.. i do have a function like that but it is composing the constructor that is puzzling me. As to what to put in the parameters and in the {} themselves. For example my withdrawal function : void withdrawal(BankAccount account[], int num_accts, ofstream &out4)
Comment: I've added a full example. Note that you shouldn't use it unless you full understand every bit of it; making changes that would seem syntactically logical and that compile even with zero warnings still could actually do very bad things. This is unfortunately a characteristic of C++... you should first learn it by reading a good book. Learning C++ by experimenting with a compiler is more or less a suicide (C++ is too complex and illogical for that).
Answer: I'm not sure what you're asking exactly, but here are some observations:

Don't use arrays of constant size. You'll either waste space or overflow them. Use vectors.
Don't use abbreviations like num_accts or acct_num, use readable names. I would replace the former with number_of_accounts and the latter with number, since it is part of a structure.
Don't write linear search algorithms yourself, they are already implemented in the STL. All you have to do is provide a predicate that compares the account numbers.

And here is some example code based on these observations:
#include <algorithm>
#include <vector>

std::vector<BankAccount> accounts;

class AccountNumberComparer
{
    int account_number;

public:

    AccountNumberComparer(int account_number)
    : account_number(account_number) {}

    bool operator()(const BankAccount& account) const
    {
        return account.number() == account_number;
    }
};

int main()
{
    // ...

    std::vector<BankAccount>::iterator it =
    std::find_if(accounts.begin(), accounts.end(), AccountNumberComparer(123));

    if (it != accounts.end())
    {
        // use *it
    }
    else
    {
        // no such account
    }
}

If you have trouble understanding this code, I suggest you get a good C++ book.

The need of writing things like AccountNumberComparer is what makes <algorithm> in my opinion almost useless in C++.

Well, you don't have to write specific code for every find_if call, you can go generic instead:
template <class Class, typename Result, Result (Class::*MemFun)() const>
class Comparer
{
    const Result& value;

public:

    Comparer(const Result& value) : value(value) {}

    bool operator()(const Class& x) const
    {
        return (x.*MemFun)() == value;
    }
};

// ...

std::vector<BankAccount>::iterator it =
std::find_if(accounts.begin(), accounts.end(),
             Comparer<BankAccount, int, &BankAccount::number>(123));

And of course, Boost already provides a better solution:
std::vector<BankAccount>::iterator it =
std::find_if(accounts.begin(), accounts.end(),
             boost::bind(&BankAccount::number, _1) == 123);

Comment: The need of writing things like `AccountNumberCompare` is what makes `` in my opinion almost useless in C++. The declarative approach is nice only when what you get is actually more concise and readable than explicit code. Unfortunately C++ syntax is just too cumbersome for that (may be C++0X lambdas will fix at least partially this problem).


Is this holistic approach, focusing on the relation between speaking and singing, uncommon? If so, why?

Question: I have taken singing lessons from different teachers . Only one, my current teacher, focuses a lot on my speaking voice. This has helped me a lot. She says that she has learned a lot from actors. The holistic approach: focusing on how speaking and singing are related has helped me a lot.
Is this holistic approach uncommon? If so, why?
Comment: My vocal instructor does the same.  She says my singing voice should be "conversational".  She is classically trained.
Comment: Yes, conversational.  As opposed to belting it out.  Even when singing opera the vocalist should not be pushing hard and the quality of the vocals should be easy, like having a conversation.
Comment: conversational?
Answer: "Speech level singing" has enough of a practitioner and fan base that a web search for "SLS" turns up, well, not a lot unless you put in a few more search keywords.
However, in singers' circles it is a reasonably well-known method, though it does not as much describe a general technique but a particular voice teacher's method and what some perceive as a well-curated and advertised cult around it.
Now of course talking and singing are related: lyrics are words, after all.  And a number of techniques particularly regarding breath and vocal control for efficient and healthy vocalisation apply to either.  However, singing seriously transcends what speaking does with voice, and vocalisation techniques differ significantly with singing styles: a speech-oriented approach is better targeted to things like broadway singing than operatic singing.
So a sensible vocal education should of course exploit commonalities as well as possible (of course we train speaking from early childhood on, but probably not doing it in the most efficient, healthy, and pleasing manner) while not getting stuck on them where they stop making sense.  For example, coloratura sopranos (and also high tenors) need to concern themselves with vowel modification for best effect, something that just does not apply to normal speaking voice.  Also the natural "speech melody" is supplanted when singing.
Comment: You wrote ". Also the natural "speech melody" is supplanted when singing."
Desn't that depend on the melody you sing? Wouldn't at least the accents in speach and singing be the same most of the time?


Como selecionar o maior valor da seguinte consulta?

Question: SELECT SUM(DISCIPLINA.VALOR) + MATRICULA.VALOR
    FROM ALUNO, MATRICULA, MATDISCIPLINA, DISCIPLINA, SEMESTRE
    WHERE ALUNO.CDALUNO = MATRICULA.CDALUNO
        AND MATRICULA.CDSEMESTRE = SEMESTRE.CDSEMESTRE
        AND MATRICULA.CDMATRICULA = MATDISCIPLINA.CDMATRICULA
        AND MATDISCIPLINA.CDDISCIPLINA = DISCIPLINA.CDDISCIPLINA
        AND SEMESTRE.ANO = '2018.1'
    GROUP BY ALUNO.NOME

Comment: Já tentou colocar os valores do SELECT entre o ```max()``` ?

Mais ou menos assim: ```SELECT max(SUM(DISCIPLINA.VALOR) + MATRICULA.VALOR)``` ?
Comment: Ja tentei o mysql retorna esse erro: ERROR 1111 (HY000): Invalid use of group function
Comment: Utilize: SUM(DISCIPLINA.VALOR) + SUM(MATRICULA.VALOR)
Answer: Basta utilizar a consulta acima como subquery:
SELECT MAX(x.total)
  FROM (
  SELECT SUM(DISCIPLINA.VALOR) + MATRICULA.VALOR AS total
    FROM ALUNO, MATRICULA, MATDISCIPLINA, DISCIPLINA, SEMESTRE
   WHERE ALUNO.CDALUNO = MATRICULA.CDALUNO
     AND MATRICULA.CDSEMESTRE = SEMESTRE.CDSEMESTRE
     AND MATRICULA.CDMATRICULA = MATDISCIPLINA.CDMATRICULA
     AND MATDISCIPLINA.CDDISCIPLINA = DISCIPLINA.CDDISCIPLINA
     AND SEMESTRE.ANO = '2018.1'
   GROUP BY ALUNO.NOME
) x

Comment: Obrigado colega.
Comment: @HiagoPais se a resposta lhe atendeu não esqueça de aceitá-la


UILocalNotification Scheduling with Repeat for 10AM GMT Issue

Question: I'm sorry if this is an absolute noob question, but I can't figure this one out from the documentation or other stack questions -
How can I set an NSDate object to 10:00AM GMT? The reason I ask is this - I want to set a localnotification to occur at 10:00AM GMT every day.
I think the following is on the right track:
<code>    NSDateComponents *comps = [[NSDateComponents alloc]init];
[comps setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

[comps setYear:2011];
[comps setMonth:1];
[comps setWeek:1];
[comps setDay:1];
[comps setHour:10];
[comps setMinute:52];
[comps setSecond:0];

NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];

NSDate *date = [gregorian dateFromComponents:comps];
[comps release];

UILocalNotification *notif = [[UILocalNotification alloc]init];

notif.fireDate = date;
notif.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
notif.alertBody = @"New Challenges are available in Halo: Reach.\n\n Give them a look over with Halo Reach Challenges!";
notif.alertAction = @"Show Me";
notif.applicationIconBadgeNumber = 5;
notif.repeatInterval = NSDayCalendarUnit;

[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
</code>
Unfortunately, this doesn't fire. Any help would be greatly appreciated :)
Answer: As long as your app is running, the notification is sent directly to your app. You'll need to set up a handler (in appDelegate) and the display the message yourself. When the app is not running, the notification should be shown.
Comment: Ok. I'm assuming there'll be a protocol reference linked in the UILocalNotification documentation. All I have to do is show a UIAlertView with the intended message, right?
Comment: Ok, and if I set it to a date in the past, with the repeat on... It fires instantly but then the replay interval should still work, right? Or will I have to get today's date, split it and add a day?
Comment: the former (the fact that it fires instantly on dates in the past) is explicitly mentioned in the documentation. There is, however, no notice what happens on the repetitions. I would expect them to function normally (that means, independent from the original being in the past or in the future), but that should be easy to check.
Comment: Yeha, it works as expected. I tested it out with NSMinuteTimeInterval. Thanks for all your help. I decided not to show a UILocalNotification though - the app is very, very... focused, and I know that my users are very focused as well. They wouldn't have the app open if they didn't want to check the data.


Normality Assumptions of the Linear Model

Question: I have some trouble understanding the normality assumptions of the linear model. I have found a wealth of information already, but some of it is contradictory and I couldn't find a definite answer to my questions, unfortunately.
1) I found that the residuals need to be normally distributed in order for the OLS to yield optimal results. Does this apply to the residuals in the population (according to Andy Field in his book "Discovering Statistics using SPSS", for example) or to the sampling distribution of the residuals?
2) Given a sufficiently large sample, am I right that we could only assume approximate normality in the sampling distribution of the residuals (CLT) and not the population? That is what confuses me about question 1): If it were the residuals in the population that were relevant, the CLT wouldn't provide an answer (I think).
3) Again in Andy Field's book, it is said that the parameter estimates must have a normal sampling distribution in order to allow significance testing and calculating CIs. In many other sources I looked at, the normality of the residuals is mentioned. Which one is right? I think that the statements might be equivalent concerning deterministic predictors, but couldn't the distribution of the parameter estimates be different than the distribution of the residuals if the predictors were stochastic?
Comment: all these topics were covered multiple times on this forum. also, normality is about errors, not residuals.
Comment: I think there would be a little improvement if we could agree not to talk about _assumptions_ but about _ideal conditions_.
Comment: The book you mention twice is often discussed here on CV  with some despair. For example, https://stats.stackexchange.com/questions/157217/transforming-data-all-variables-or-just-the-non-normal-ones It's not authoritative. It may sell well and have bizarre humour and anecdotes, but those are uncorrelated.
Answer:
The residuals of the sample are fixed; they have no random properties. When we refer to "population residuals" what we actually mean is residuals found from doing the experiment again a large number of times. It is these population residuals that are normally distributed. Introductory texts are usually misleading in how they describe "populations".
The central limit theorem (CLT) does not apply to the residuals themselves. The mean of the residuals is 0 by definition. If the population residuals are, say, exponentially distributed, then as $n \rightarrow \infty$, you will just find more and more exponentially distributed residuals that have a mean of 0. It is the regression parameter estimates that have an approximating normal distribution in large samples when regularity conditions are met. That condition, the Lindeberg condition, I paraphrase as: you can't keep sampling outliers.
If the population residuals are normally distributed, then the parameter estimates are exactly normally distributed: tests are exact for every $n$. This is a consequence of the regression parameter being an unbiased linear estimator. An unbiased linear estimator means it can be expressed as a linear combination of the $Y$s or the residuals. It's also true that any weighted combination of normal random variables is also normal. If you put those pieces together, you see that an exact normal distribution is obtained at any non-singular sample size. If the residuals aren't normal, you need a modest $n$ to ensure approximate normality of the regression parameter. Andy is right that exact or approximate normality is needed to calculate CIs and tests in the usual way.
Comment: In (3) you seem to have systematically switched the meanings of "error" and "residual."
Comment: @whuber I relaxed the term "population residuals" to just "residuals" from the definition in 1). I am focusing on a statistical rather than probabilistic interpretation of a regression model. Do you see a contradiction there? Expressing the $Y$ as a fixed part and a random part is rigorous since the OLS model consistently estimates $E[Y|X]$. (I guess I reintroduce the idea of "errors" halfway through)
Comment: The apparent switch in meanings looks like it has considerable potential to lead to confusion rather than clarity.  It might help to explain at the outset what you mean by each term and to use it consistently.
Comment: @whuber good suggestion. I suppose my line of reasoning is correct, if the terminology is unclear. I think the edits are more consistent.
Comment: Thank you.  This raises a very interesting point: your term "population residuals" could mean two distinctly different things.  Let's imagine a finite bivariate population $(x_i,y_i)$ and a model of that population in which $y_i=f(x_i)+\epsilon_i.$ The $\epsilon_i$ are the *errors.* However, we could also apply some regression procedure, such as OLS, to *the entire population,* thereby producing a "population fit" of the form $y_i = \hat f(x_i) + \delta_i.$ It is reasonable to call the $\delta_i$ the "population residuals."  But which of these concepts are you actually referring to?
Comment: @whuber Let's assume the $f$ is linear so that this question isn't about mean model specification. As I alluded to earlier, I think textbooks are imprecise about what a "population" is. Here, what you are calling a "population" I would rather call a sampling frame. But I am referring to counterfactual, frequentist probability distributions that are obtained from replication: it is in that sense that I have defined "population" residuals in keeping with the OP's conventions. To answer your question: I am referring to neither form. You must replicate the design: I mean *those* residuals.
Comment: The interesting point is that even when $f$ is linear and you apply OLS, $\hat f$ differs from $f$!  It's unclear what you might mean by residuals deriving from "replicating the design."
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/76240/discussion-between-adamo-and-whuber).
Answer: This whole normality business come up mainly in relation to the variance of parameter estimates $\hat \beta$ in a model such as this:
$$y_i=\beta_0+x_i\beta_x+\varepsilon_i$$
or in vector form $$y=X\beta+\varepsilon$$
Note, that here $\varepsilon_i$ is the errors, not the residuals $\hat\varepsilon_i$. The latter is the estimate of errors. Normality assumptions are stated in terms of errors, not residuals.
Once you got your estimates of parameters $\hat\beta$ conditioned on the sample $(y,X)$, we realize that these parameter estimates are themselves random values. So, they must come from some probability distribution. This is where normality of errors comes handy. It turns out that when the errors are normal, it's easy to derive this distribution of parameter estimates. We can study its properties, and establish that they're optimal in some sense etc.
The problem is that in practice it is often difficult to claim that the errors are normal. So, it is helpful to relax this assumption, and instead maybe just ask that the error variance is finite, for instance. In the latter case plus some other conditions such as no autocorrelation, it can be shown that the variance of parameter estimates is:
$$\widehat{\operatorname{s.\!e.}}(\hat{\beta}_j) = \sqrt{s^2 (X ^T X)^{-1}_{jj}}$$
where $s^2$ is the sample variance estimator of residuals, it's an estimator of error variance. We do not need normality for this result.
Now, it turns out that under reasonable conditions, in large samples, the distribution of the parameter estimates is normal. Note, that this is different from how you interpreted the application of CLT. Here, the model errors $\varepsilon_i$ don't suddenly become normal when you increase the sample size. What happens here is that the variance of the parameter estimate $\hat\beta$, because it is a linear combination of data, is the function of the sum of variances of residuals.
Summarizing, yes, normality of errors leads to normality of parameter estimates, and otherwise makes our lives easier. However, asymptotically, the parameter estimates become normal even when errors are not normal under a set of reasonable conditions, such as Gauss Markov theorem assumtptions.


How to get results from threads as they complete?

Question: The following code starts a few threads and prints the result after they are all done:
import threading

results = [None] * 5
threads = [None] * 5

def worker(i):
    results[i] = i

for i in range(5):
    threads[i] = threading.Thread(target=worker, args=(i,))
    threads[i].start()

# here I would like to use the results of the threads which are finished
# while others still run

for i in range(5):
    threads[i].join()

# here I have the results but only when all threads are done
print(results)

As mentioned in the code, I would like to use the results of the threads which are finished while others are still running. What is the correct way to do that?
Should I simply start a new thread which would have a while True: loop and continuously check for a new entry in results or is there a buil-in mechanism for such operations (as part of the threading.Thread call which would point to a callback when the thread is done)?
Comment: `from multiprocessing.pool import ThreadPool` and you can take it from there.
Comment: Might you enumerate upon that?
Comment: 'https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python' may be your answer is here
Comment: @cᴏʟᴅsᴘᴇᴇᴅ: thanks, I will try that way. I was hoping that there would be a direct callback mechanism (which I did not find in the docs)
Comment: @Kallz: I know how to get the result of a thread (my code is adapted from the second answer to the link you point to). As mentioned before, I was looking for a callback mechanism, if such one exists.
Comment: use  "isAlive()" method for check thread is running or completed ,first you want to use result of completed result so check result which 'isAlive()' is false and in second condition you want to check result when all thread completed so check result when 'isAlive()' for all thread is false
Answer: Since you're using Python 3, concurrent.futures is a better fit than threading:
import concurrent.futures

results = [None] * 5

def worker(i):
    results[i] = i

with concurrent.futures.ThreadPoolExecutor(5) as pool:
    futmap = {pool.submit(worker, i): i for i in range(len(results))}
    for fut in concurrent.futures.as_completed(futmap):
        print("doing more stuff with", futmap[fut])

Comment: *The concurrent.futures module provides a high-level interface for asynchronously executing callables* - excellent, this is exactly what I was looking for, thank you!


Windows Server 2016 or Cisco 1900 router as vpn device for a connection with active directory authentification?

Question: I am relatively new to vpns, so please excuse me if my question is a little bit off.
In my test scenario i have a small company network with a client to site vpn. This network contains a DC, Fileserver, Sharepoints and so on...
Users of the vpn connection should only authenticate with their AD accounts.
The vpn server is the last thing that has to be implemented but i do not know which solution i should use. I did some research an came across two solutions.
- Windows Server 2016 with RRAS
- Cisco Router
Question 1:
Can someone please explain me the differences between these two solutions in case of performance, security and scalability?
Question 2:
How do you implement AD authentication on an Cisco 1900 Router?
Comment: Question 1, its opinion based imo, question 2 search radius, and come back if you got problem to implement it.
Comment: What solution would you prefer? Windows/Linux server or Cisco router? @yagmoth555
Answer: For your first question: My preference is to have the VPN terminate at the router.  Then you are controlling access at the boundary of your network.
For your second question: AD authentication can be done either with a radius server or LDAP server.  LDAP is slightly easier because you just need the right LDAP configuration.  Radius would require deployment of NAP role on a server along with some policy configuration.
See AAA LDAP Configuration Guide


The probability of an account being chosen

Question: Current: $140$
1-30 days past due: $80$
31-60 days past due: $40$
61-90 days past due: $25$
Sent for collection: $15$
What is the probability that $2$ current accounts and $2$ 1-30 days past due accounts will be chosen?
Using multiplication rule:
$$\frac{140}{300}\frac{139}{299}\frac{80}{298}\frac{79}{297} = 0.0155$$
Using combination method:
$$\frac{\binom{80}{2}\binom{140}{2}}{\binom{300}{4}} = 0.093$$
Although the two methods is similar in meaning, the results are not the same. What is wrong and which one is the correct one?
Comment: I thank you very much for your edited my friend. I am very dumb at computer hehe...
Answer: What's wrong is, you're requiring the first two accounts to be the current ones, and the last two to be the past due ones. Make sure you allow for all the permutations.
Answer: When using the multiplicative rule, you've done it in order of current, current, 1-30 days past due, 1-30 days past due but we don't actually care about the order. There are six orderings we could have had for these choices AABB BBAA ABBA BAAB BABA ABAB hence the value should be multiplied by six which then agrees with your other method.
Comment: AAA I UNDERSTAND NOW. I THANK YOU VERY MUCH MY FRIEND !!!
Comment: No problem at all.


Javascript executar com certa resolução

Question: Tenho um javascript, e preciso que ele seja executado apenas com resoluções menores de 700px.
Segue abaixo meu código:
$(document).ready(function(){
$('.menu').hide();

/* menu */
$('.menu').click(function(){
    $('.menu').slideToggle(200);
});

});
Answer: Você pode usar o objeto window.screen para pegar o tamanho da tela. Nele você pode usar as propriedades width e height para pegar o tamanho da tela.
Exemplo:

document.getElementById("width").innerHTML = "Width: " + screen.width + "px";

document.getElementById("height").innerHTML = "Height: " + screen.height + "px";

if (screen.width > 700) {
  document.getElementById("resultado").innerHTML = "Width é maior que 700px.";
} else {
  document.getElementById("resultado").innerHTML = "Width é menor que 700px.";
}

Answer: Amigão, tenta pegar a resolucao dele e fazer um if simples.
$(document).ready(function(){
var screenH = window.screen.availHeight;
var screenW = window.screen.availWidth;

if(screenW<700){
    alert('run code here');
}
});

Javascript executar com certa resolução


Homology groups of $\mathbb{R}^3\setminus \ S^1$ and $\mathbb{R}^3\setminus E^1_+$

Question: Here is a problem and my attempt at the solution. If my conclusion or the proof is incorrect I would appreciate a pointer in the right direction. Thanks in advance.
Let $S^1$ be the unit circle in the xy plane in $\mathbb{R^3}$ and let $E^1_+$ and $E^1_-$ be two of its semicircles. Find the homology groups (with integer coefficients) of a) $\mathbb{R^3}\setminus E^1_+$ and b) $\mathbb{R^3}\setminus \ S^1$.
Attempt of solution:
a) $H_n(\mathbb{R^3},S^1)\cong H_n(\mathbb{R^3}\setminus E^1_+, E^1_-)$, by excision. Then $H_n(\mathbb{R^3}\setminus E^1_+, E^1_-) \cong H_n(\mathbb{R^3}\setminus E^1_+, {pt})$, since $E^1_-$ is contractible. Then we know $H_n(\mathbb{R^3}\setminus E^1_+, {pt}) \cong \tilde{H_n}(\mathbb{R^3}\setminus E^1_+)\cong H_n(\mathbb{R^3}\setminus E^1_+)$ for $n>0$. So we get $H_n(\mathbb{R^3}\setminus E^1_+) \cong H_n(\mathbb{R^3},S^1)$. From the long exact sequence of relative homology we know that $H_n(\mathbb{R^3},S^1) \cong H_{n-1}(S^1)$, so $H_n(\mathbb{R^3}\setminus E^1_+)\cong \mathbb{Z}$ for $n=1,2$.  For $n=0$ we also get $\mathbb{Z}$ since $\mathbb{R^3}\setminus E^1_+$ is arcwise connected.
b) the same reasoning but starting with $H_n(\mathbb{R}^3,E^2_+)$, where $E^2_+$ is the upper hemisphere of $S^2$, gives $H_n(\mathbb{R}^3 \setminus S^1) \cong H_{n-1}(E^2_+)$, but  $E^2_+$ is contractible so $H_n(\mathbb{R}^3 \setminus S^1)\cong \mathbb{Z}$ for $n=1$ and for $n=0$ it is also $\mathbb{Z}$ since $\mathbb{R}^3 \setminus S^1$ is arcwise connected. For $n>1$, $H_n(\mathbb{R}^3 \setminus S^1)=0$.
EDIT
@msteve pointed out that b) is wrong. Excision can't be used like in a) since $S^1$ isn't in the interior of $E^2_+$. So a different approach is needed here.
Comment: $\Bbb R^3 - S^1$ deformation retracts onto $S^2 \vee S^1$. Use the homotopy equivalence of homology to conclude the proof. You don't need to use this much machinery at all.
Comment: I think $H_2(\mathbb{R}^3 - S^1) = \mathbb{Z}$? You have at least one free generator by taking a sphere enclosing the removed unit circle, so the second homology is nonzero.
Comment: @msteve you're right. Excision can't be used in b) like in a) since $S^1$ isn't in the interior of $E^2_+$. So a different approach is needed here. Thanks for catching that.
Comment: I don't see how you used excision in A)
Comment: (the circle has empty interior as a subset of R^3)
Comment: @BalarkaSen how do you prove that it does retract to that? I don't see that.
Comment: @MarianoSuárez-Alvarez I see. I was wrong. Could you suggest another approach?
Comment: @user198182 Have a look at page 46 of Hatcher.
Comment: @BalarkaSen, that is, provided you can actually prove that retraction does exist! :-) (And a picture does not count..)
Comment: @MarianoSuárez-Alvarez Well, if you want to explicitly write up the retract, be my guest :P. Some deformation retracts are extremely hard to algebraically derive. For example, can you show that $\Bbb R^3 - \{0, 1\}$ deformation retracts onto the wedge of two circles? It's impossible to write down a formula, but it's easy to "see" it :)
Comment: Well, it was you who suggested to use the existence of that retract. Notice that the first homology is also $\mathbb Z$ if the $S^1$ is knotted in $\mathbb R^3$. Can you also "see" a retraction in that case?
Comment: I assumed $S^1$ is not knotted inside $\Bbb R^3$? At least, the question makes it clear. It's the unit circle on the xy-plane. For general knots, there is no such retract (or at least, it's not apparent that there is).
Comment: @BalarkaSen I see the deformation retraction now.
Answer: Ok, here we go:
a) Set $U_1 := \mathbb{R}^3 \setminus S^1$. Let $1/5 > \varepsilon > 0$ and consider $S^1 \times D_{\varepsilon}$  a solid torus. (The product of $S^1$ with the disc of radius $\varepsilon$) If $S^1$ were knotted, we could still find a small enough $\varepsilon$ and our proof would be exactly the same. In particular, the homology of $\Bbb R^3 \setminus K$ is the same for every knot.
Set $U_2 := int(S^1 \times D_\varepsilon)$. We have the following facts:

$\mathbb{R}^3$ is covered by the open sets $U_1$ and $U_2$.
$U_2 \simeq S^1$, where $\simeq$ means homotopy equivalence.
$U_1 \cap U_2 \simeq T^2$, where $T^2$ is the torus.

So applying the Mayer-Vietoris sequence, we get
$$\dots \to H_{n+1}(\Bbb R^3) \to H_n(U_1 \cap U_2) \to H_n(U_1) \oplus H_n(U_2) \to {H}_{n}(\Bbb R^3 ) \to  H_{n-1}(U_1 \cap U_2) \to \dots$$
and using our facts, we get
$$\dots \to H_{n+1}(\Bbb R^3)  \to H_n(T^2) \to H_n(U_1) \oplus H_n(S^1) \to {H}_{n}(\Bbb R^3 ) \to  H_{n-1}(T^2) \to \dots$$
Now $\Bbb R^3$ is contractible, so for $n>0$ we have the isomorphisms $H_n (T^2) \simeq H_n(U_1) \oplus H_n(S^1)$. Therefore $H_n(U_1) =0$ for $n>2$, $H_2(U_1) \simeq H_1(U_1) \simeq \Bbb Z$ and since $U_1$ is path-connected, $H_0(U_1) \simeq \Bbb Z$. This completes the proof of a).
b) Clearly $\Bbb R^3 \setminus E^1_+ \simeq \Bbb R^3 \setminus {x}$, where $x \in E^1_+$ is just a point. Now $\Bbb R^3$ retracts onto $S^2$ and we know its homology, so we are done.
Comment: This is a very clear solution. Thank you.


Topics for an undergraduate exposition in number theory

Question: I have to give a 90~ minute exposition as a final assignment for my undergraduate number theory course and I'm looking for ideas on what to talk about.
I've taken abstract algebra and complex analysis courses so it'd be great to use some machinery to prove a nice result. I was thinking something along the lines of the Gelfond-Schneider theorem but its proof is somewhat dry.
Any ideas?
Comment: The prime number theorem.
Comment: Fermat's claims on what primes can be written in the form $x^2+2y^2$ or $x^2+3y^2$ (and subsequent work).
Comment: The continued fraction of $\sqrt n$, the parity of its period.
Comment: You could justify the RSA cryptosystem, assuming that hasn't already been covered in class.  If it has been covered, maybe elliptic curve cryptography would be fun?  You have plenty of rich examples there.  I did a similar presentation where I divided my audience into teams, each of which had just enough information to decrypt a secret, and then they raced.  Just make it fun.
Comment: If you decide to heed Andres' comment-- which I think is a most marvelous idea-- Cox's primes of the form x^2+ny^2 is a most excellent, accessible read.
Answer: I think you can get a great exposition out of the general subject of continued fractions. It is ideal for undergraduate number theory, fairly easy to pick up, absolutely fascinating, deep, and useful. It is not trivial.
While you can find some good writing and proofs on the subject toward the end of any undergraduate textbook on number theory, you might want to pick up a book written by C. D. Olds titled "Continued Fractions" It is an old book from the Mathematical Association of America in the New Mathematical Library, but you will find it to be a great armchair read (nearby pencil and paper being handy).
I have several ideas on such an exposition. My thesis advisor actually listend to an exposition involving this book at an AMS meeting in San Francisco 1991 as evidenced by the copy he graciously gave me with that data inscribed inside the cover. The day I finally got around to reading it, I could not put it down till I hit the end, and I have been fascinated by the subject ever since. I have no question in my mind that you could easily entertain/amaze an undergraduate (or even post graduate) audience with an exposition on continued fractions.
Comment: For some recent references on current work, see [here](http://andrescaicedo.wordpress.com/2011/10/10/596-continued-fractions/).
Comment: I have to second that great reference by and from Andres Caicedo. Any time I start reading something and the first theorem is titled "Lagrange's theorem" I get so excited (to excess). We are either about to count cosets or we are about to discuss the eventual periodicity of continued fractions for quadratic surds. This is very good research.
Answer: Not well known, the 1983 result of Jean-Louis Nicolas that RH is true if and only if $$ \frac{\phi(N) e^\gamma \log \log N}{N} < 1 $$ for all primorials $N.$ Primorial means $N = 2 \cdot 3 \cdot 5 \cdot 7 \cdot 11 \cdots p_r,$ the product of the consecutive primes starting with 2. For all known $N,$ the quantity $ \frac{\phi(N) e^\gamma \log \log N}{N} < 1. $ For that matter, in all known cases, the quantity increases slightly with multiplication of $N$ by each new prime, and gets pretty close to $1;$ for $n= 2 \cdots 211$ the ratio depicted is about $0.97008.$
On the other hand, if the ratio increases forever (to the limit $1$ ) then Cramer's conjecture on prime gaps is violated.
Cute, and very easy to compose a computer output, as opposed to Robin's Criterion which became better known.
See PLANAT  and NICOLAS PDF
Oh, or Lagrange's method for quadratic irrationals, which means the same thing as continued fractions but requires no computer accuracy and no computer memory.
SAMPLE:
<code>jagy@phobeusjunior:~/old drive/home/jagy/Cplusplus$ ./Pell
Input n for Pell
1013

0  form   1 62 -52   delta  -1
1  form   -52 42 11   delta  4
2  form   11 46 -44   delta  -1
3  form   -44 42 13   delta  4
4  form   13 62 -4   delta  -15
5  form   -4 58 43   delta  1
6  form   43 28 -19   delta  -2
7  form   -19 48 23   delta  2
8  form   23 44 -23   delta  -2
9  form   -23 48 19   delta  2
10  form   19 28 -43   delta  -1
11  form   -43 58 4   delta  15
12  form   4 62 -13   delta  -4
13  form   -13 42 44   delta  1
14  form   44 46 -11   delta  -4
15  form   -11 42 52   delta  1
16  form   52 62 -1   delta  -62
17  form   -1 62 52   delta  1
18  form   52 42 -11   delta  -4
19  form   -11 46 44   delta  1
20  form   44 42 -13   delta  -4
21  form   -13 62 4   delta  15
22  form   4 58 -43   delta  -1
23  form   -43 28 19   delta  2
24  form   19 48 -23   delta  -2
25  form   -23 44 23   delta  2
26  form   23 48 -19   delta  -2
27  form   -19 28 43   delta  1
28  form   43 58 -4   delta  -15
29  form   -4 62 13   delta  4
30  form   13 42 -44   delta  -1
31  form   -44 46 11   delta  4
32  form   11 42 -52   delta  -1
33  form   -52 62 1   delta  62
34  form   1 62 -52

 disc   4052
Automorph, written on right of Gram matrix:
-8039536270522589  -505105258804091920
-9713562669309460  -610280421767709109

 Pell automorph
-309159979019115849  -9839838984010482980
-9713562669309460  -309159979019115849

Pell unit
309159979019115849^2 - 1013 * 9713562669309460^2 = 1

=========================================

Pell NEGATIVE
393166618^2 - 1013 * 12352985^2 = -1

=========================================

  4 PRIMITIVE
851931^2 - 1013 * 26767^2 = 4

=========================================

1013       1013

jagy@phobeusjunior:~/old drive/home/jagy/Cplusplus$
</code>


Page 404 through Python Requests but loads fine through browser

Question: Getting page 404 with Python Requests but I can access the page no problem through my browser. I can access other pages that are formatted exactly the same as this page and they load no problem.
Have already tried changing headers with no luck.
My Code:
<code>string_page = str(page)
with requests.Session() as s:

    resp = s.get('https://bscscan.com/token/generic-tokentxns2?m=normal&contractAddress=0x470862af0cf8d27ebfe0ff77b0649779c29186db&a=&sid=f58c1cdefacc680b799412c7645ed7f7&p='+string_page)

    page_info = str(resp.text)

print(page_info)
</code>
I have also tried with urllib and the same thing happens
Comment: Have you tried [sending an "user-agent" using Requests library in Python](https://stackoverflow.com/questions/10606133/sending-user-agent-using-requests-library-in-python)? Maybe "the user-agent should be specified as a field in the header."
Comment: You probably need to be signed in to get to the page in the URL. When you use Python, it's accessing the page as a "guest".
Comment: tried the header solutions. no luck.
Comment: im not logged in on my browser and it still works
Comment: You perhaps logged in earlier and the browser remembered cookies and which is why it works for you. However, you should share the url to get more accurate suggestion, not like the broken one in your post.
Comment: i dont have an account on the website, so have never logged in.

This is the direct link to the page:
https://bscscan.com/token/generic-tokentxns2?m=normal&contractAddress=0x470862af0cf8d27ebfe0ff77b0649779c29186db&a=&sid=f58c1cdefacc680b799412c7645ed7f7&p=1
Answer: I'm not sure if this will fix it, but try adding this in the header maybe it might work
<code>'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
</code>
Comment: yeah tried that already. no luck unfortunately


upstart CentOS vs upstart Ubuntu is there any difference between them?

Question: I'm moving some server configurations from Ubuntu Server 12.04 to CentOS 6.6. Now I'm working on /etc/init script that should be handled by upstart at both OS as far as I know. The files on both server are the same and I mean the same at content level and also at path level and permissions level, is the exactly copy from Ubuntu to CentOS. I'm having some issues with upstart at CentOS since scripts doesn't start and I can't find why (the cause). This is the output from initctl list at Ubuntu server:
# Ubuntu 12.04
root@qa:/etc/init# initctl list
// rest of processes goes here
pdoneVendorBroker start/running, process 854
repToolBroker start/running, process 3705
emailBroker start/running, process 3738
cmeBroker start/running, process 3760
messageBroker start/running, process 3727
shareEventHandler start/running, process 3686
edetailBroker start/running, process 3749
pdoneLoginProctor start/running, process 3716

All the processes has been started at OS boot, that's fine.
This is the output from CentOS server:
# CentOS 6.6
root@staging:/etc/init# initctl list
// rest of processes goes here
pdoneVendorBroker stop/waiting
repToolBroker stop/waiting
emailBroker stop/waiting
cmeBroker stop/waiting
messageBroker stop/waiting
shareEventHandler stop/waiting
edetailBroker stop/waiting
pdoneLoginProctor stop/waiting

None processes has been started after OS boot, and that's wrong. Why? What I'm missing here? Can any give me some advice?
At CentOS I've tried also to start the process manually by running this:
initctl start cmeBroker.conf

But I got this error:

initctl: Unknown job: cmeBroker.conf

This is the content for the file / etc/initcmbBroker.conf`:
description "cmeBroker"

start on runlevel [234]
stop on runlevel [0156]

respawn
exec php /usr/local/bin/cmeBroker/cmeBroker.php
post-start script
    PID=`status cmeBroker | egrep -oi '([0-9]+)$' | head -n1`
    echo $PID > /var/run/cmeBroker.pid
end script

post-stop script
    rm -f /var/run/cmeBroker.pid
end script

It's wrong?
Answer: Open the messages system log tail /var/log/messages you will see an error log telling you the problem and the line number.
Looks like this:
Sep 21 16:34:28 0 init: /etc/init/uwsgi.conf:9: Unknown stanza


Como uso o @media para bloquear padding-top em resoluções menores?

Question: Como eu faço  bloquear o 'padding'  dessa função

 no @media ?

O objetivo e bloquear o 'padding' em resoluções menores.
Answer: Utilize class junto com @media:

.minha-div {
  padding-top: 68px;
  width: 300px;
  float: left;
}
@media (max-width: 300px) {
  .minha-div {
    padding-top: 0px !important;
  }
}

Nesse link tem um tutorial de como utilizar as medias queries do CSS.
Comment: funcionou Vlw cara
Comment: Quando a resposta solucionar o problema, marque-a como correta. xD
Comment: Foi mal pela nubagem, marcado.
Answer: No CSS as regras são aplicadas na ordem... no seu caso provavelmente carrega antes do html.
Tente colocar !important na sua regra dentro @media
@media... {
   .classeDaDiv {
       padding-top: 0 !important;

Comment: Vlw por responder


A unexpected output with if condition

Question: I want to wirte a program to calculate the sum of first n natural numbers
The code that i have tried:
    #include<stdio.h>
    void main()
    {
        int sum=0,i=1,n;
        printf("Enter the number upto where you want to print add  : ");
        scanf("%d",&n);
        printf("\nSUM = ");
        while(i<=n)

        {
          if(i<n)
          {
              printf("%d+",i);
          }
          if(i=n)
          {
              printf("%d",i);
          }
          sum=sum+i;
          i++;
        }
        printf("\nThe sum of the first %d numbers is : %d",n,sum);
        return 0;
    }

And the expected output is if n=5
Enter the number upto where you wnat to print add :

sum =1+2+3+4+5

The sum of the first %d numbers is : 5

But what I'm getting is
sum=1+5

and the value is 5

But when I'm using if else instead of two if's its working
Comment: Please enable or turn up your warnings in the compiler. The compiler should raise a warning about suspicious use of `=` in a condition.
Answer: The problem is your if statement :
if(i=n)

A single = is an assignment;  what you want is the comparison with ==, so :
if(i==n)

Answer: You have used i=n instead of i==n in if statement.
Answer: You are using the assignment operator = instead of the comparison operator == in the expression in this if statement
      if(i=n)
      {
          printf("%d",i);
      }

You need to write
      if( i == n)
      {
          printf("%d",i);
      }

Also it is better to use for loop instead of the while loop.
For example
for ( int i = 0; i < n;  )
{
    printf( ++i == n ? "%d" : "%d+", i );
    sum += i;
}

The variable i is used only in the loop. So it should be declared in the scope where it is used.
Always try to declare variables in minimum scopes where they are used. This will make your programs more readable.
Pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )

A unexpected output with if condition


Demonstrate that $x(t)$ and $\hat{x}(t)$ are orthogonal

Question: I have to demonstrate that a function $x(t)$ and his Hilbert's transform are orthogonal, it is said:
$$\int^{\infty}_{-\infty} x(t) \cdot \hat{x}(t) dt = 0$$
where:
$$\hat{x}(t) = x(t) \ast \frac{1}{\pi t} =\frac{1}{\pi} \int^{\infty}_{-\infty} \frac{x(s)}{t-s} ds$$
or, in the frequency domain:
$$\hat{x}(t) = \mathcal{F}^{-1} \lbrace -jX(f)sgn(f)\rbrace$$
with $\mathcal{F}^{-1}$ is the inverse Fourier transform and $sgn(f)$ is the sign of $f$
I have tried the exercise using Parseval's theorem:
$$\int^{\infty}_{-\infty} x^2(t) \cdot \hat{x}^2(t) dt = \int^{\infty}_{-\infty} |X(f) \ast \hat{X}(f)|^2 df = \int^{\infty}_{-\infty} |X(f) \ast (-jsgn(f)X(f))|^2 df =$$
$$= \int^{0}_{-\infty} |X(f) \ast jX(f)|^2 df + \int^{\infty}_{0} |X(f) \ast (-jX(f))|^2 df$$
Using properties of convoution ($ax(t) \ast y(t) = a(x(t) \ast y(t)$):
$$\int^{\infty}_{-\infty} x^2(t) \cdot \hat{x}^2(t) dt = \int^{0}_{-\infty} | j(X(f) \ast X(f))|^2 df + \int^{\infty}_{0} |-j(X(f) \ast X(f))|^2 df =$$ $$=\int^{0}_{-\infty} |X(f) \ast X(f)|^2 df + \int^{\infty}_{0} |X(f) \ast X(f)|^2 df = $$
$$= -\int^{\infty}_{0} |X(f) \ast X(f)|^2 df + \int^{\infty}_{0} |X(f) \ast X(f)|^2 df = 0$$
But I don't know how to relationate both integrals. Maybe that isn't the way to demonstrate the exercise.
Thanks for your help.
Answer: $$<x, \hat{x}> = \int^{\infty}_{-\infty} x(t) \cdot \hat{x}(t) dt = \int_{-\infty}^{\infty} x(t) \int_{-\infty}^{\infty} \frac{x(s)}{t-s} ds dt = \\
\int_{-\infty}^{\infty} x(s) \int_{-\infty}^{\infty} -\frac{x(t)}{s-t} dt ds = - \int_{-\infty}^{\infty} x(s) \hat{x}(s) ds  = - <x,\hat{x}>
$$
So what must $<x,\hat{x}>$ be?
Comment: Thank you so much!


Como corrigir o erro Impossible to generate condition with empty list of values for field (Tags.title)

Question: Estou brincando com o cakephp 3 fazendo o tutorial do bookmarker do CookBook. Estou implementando a action  no controller bookmarks/tags, mas ao tentar acessar aparecer o erro do titulo da pergunta:
Impossible to generate condition with empty list of values for field (Tags.title)
Segue o código do controller
<?php namespace App\Controller;
 use App\Controller\AppController;

class BookmarksController extends AppController
{

public function index()
{
    $this->paginate = [
        'contain' => ['Users']
    ];
    $bookmarks = $this->paginate($this->Bookmarks);

    $this->set(compact('bookmarks'));
    $this->set('_serialize', ['bookmarks']);
}

public function view($id = null)
{
    $bookmark = $this->Bookmarks->get($id, [
        'contain' => ['Users', 'Tags']
    ]);

    $this->set('bookmark', $bookmark);
    $this->set('_serialize', ['bookmark']);
}

public function add()
{
    $bookmark = $this->Bookmarks->newEntity();
    if ($this->request->is('post')) {
        $bookmark = $this->Bookmarks->patchEntity($bookmark, $this->request->data);
        if ($this->Bookmarks->save($bookmark)) {
            $this->Flash->success(__('The bookmark has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The bookmark could not be saved. Please, try again.'));
        }
    }
    $users = $this->Bookmarks->Users->find('list', ['limit' => 200]);
    $tags = $this->Bookmarks->Tags->find('list', ['limit' => 200]);
    $this->set(compact('bookmark', 'users', 'tags'));
    $this->set('_serialize', ['bookmark']);
}

public function edit($id = null)
{
    $bookmark = $this->Bookmarks->get($id, [
        'contain' => ['Tags']
    ]);
    if ($this->request->is(['patch', 'post', 'put'])) {
        $bookmark = $this->Bookmarks->patchEntity($bookmark, $this->request->data);
        if ($this->Bookmarks->save($bookmark)) {
            $this->Flash->success(__('The bookmark has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The bookmark could not be saved. Please, try again.'));
        }
    }
    $users = $this->Bookmarks->Users->find('list', ['limit' => 200]);
    $tags = $this->Bookmarks->Tags->find('list', ['limit' => 200]);
    $this->set(compact('bookmark', 'users', 'tags'));
    $this->set('_serialize', ['bookmark']);
}

public function delete($id = null)
{
    $this->request->allowMethod(['post', 'delete']);
    $bookmark = $this->Bookmarks->get($id);
    if ($this->Bookmarks->delete($bookmark)) {
        $this->Flash->success(__('The bookmark has been deleted.'));
    } else {
        $this->Flash->error(__('The bookmark could not be deleted. Please, try again.'));
    }
    return $this->redirect(['action' => 'index']);
}

public function tags(){

    $tags= $this->request->params['pass'];
    $bookmarks= $this->Bookmarks->find('tagged',[
        'tags'=>$tags
    ]);
    $this->set(compact('bookmarks','tags'));
}
}

Segue o código da rota arquivo routes.php
Router:: scope(
'/bookmarks',
['controller'=>'Bookmarks'],
function ($routes){
    $routes->connect('/tagged/*',['action'=>'tags']);

}
 );

Segue o Código da model table BookmarksTable.php
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class BookmarksTable extends Table
{
  public function initialize(array $config)
     {
        parent::initialize($config);

         $this->table('bookmarks');
         $this->displayField('title');
         $this->primaryKey('id');
         $this->addBehavior('Timestamp');
         $this->belongsTo('Users', ['foreignKey' => 'user_id',
        'joinType' => 'INNER'
         ]);
         $this->belongsToMany('Tags', [
        'foreignKey' => 'bookmark_id',
        'targetForeignKey' => 'tag_id',
        'joinTable' => 'bookmarks_tags'
       ]);
      }

    public function validationDefault(Validator $validator)
    {
        $validator
         ->integer('id')
         ->allowEmpty('id', 'create');
           $validator
          ->allowEmpty('title');
          $validator
        ->allowEmpty('description');

    $validator
        ->allowEmpty('url');

    return $validator;
 }
public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->existsIn(['user_id'], 'Users'));
    return $rules;
}

public function findTagged(Query $query ,array $options){

    $fields=[
        'Bookmarks.id',
        'Bookmarks.title',
        'Bookmarks.url',
    ];

    return $this->find()
        ->distinct($fields)
        ->matching('Tags',function ($q) use ($options){
            return $q->where(['Tags.title IN'=> $options['tags']]);
        });

      }
      }

Agora o código da View tags.ctp

 Bookmarks tagged with
    <?= $this->Text->toList($tags) ?>

    <?php foreach ($bookmarks as $bookmark): ?>

           <?= $this->Html->link($bookmark->title, $bookmark->url) ?>

            <?= h($bookmark->url) ?>

          <?= $this->Text->autoParagraph($bookmark->description) ?>

 <?php endforeach; ?>

Queria saber onde estou errando, sei que é básico, mas não consegui identificar o erro ainda.
Comment: Espero que o código, esteja fácil de visualizar, qualquer coisa me fala para eu ajustar!
Comment: A ideia é deixar o mais explicado possível. Porque caso alguém tenha esse mesmo problema no futuro esteja simples para ajudar!
Answer: Então pessoal acho que estava muito ansioso lendo o CookBook e não prestei a tenção,o erro é muito básico.
Seguinte no método do BookmarksController
public function tags(){

$tags= $this->request->params['pass'];
$bookmarks= $this->Bookmarks->find('tagged',[
    'tags'=>$tags
]);
$this->set(compact('bookmarks','tags'));
}

Na parte  $tags= $this->request->params['pass'] está pedindo um parâmetro, ou seja, na url é só colocar um texto de uma tags que já está no banco, pois o crud da tags já estava implementado.
Como eu não coloquei nada na url ele apresentava a mensagem de exceção que não conseguia gerar a condição necessária.
Agora coloquei um valor que já estava cadastrado no banco e pronto apareceu a View lindona com os dados.
Pronto resolvido!


Git commit --amend alias hangs

Question: I have this alias in my ~/.gitconfig:
[alias]
    am = commit -a --amend -C HEAD

Yet, when I run git am, it hangs, and I get (master|AM/REBASE) at the prompt, and I have to run git am --abort.
Answer: There already is a git am command. Your alias is invalid (since there already is such a command), and when you run git am, you're actually executing this command. If you chose a different alias, such as ca (short for "commit amend"), it should work:
[alias]
    ca = commit -a --amend -C HEAD

As a side note, git commit has a --no-edit flag you can use instead of -C HEAD:
[alias]
    ca = commit -a --amend --no-edit

Answer: There is a standard git am command that Applies (patches from) Mailbox. In git aliases cannot override standard commands, so even if you have an alias git am runs the standard command and the command awaits input at the standard input. So it doesn't hang, it's just waiting.
Rename the alias to something not already among standard git commands.

Git commit --amend alias hangs


Problem understanding the following probability problem

Question:
I have 120 blocks. Each block is one of two different materials, 3
  different colors, 4 different sizes and 5 different shapes. No two
  blocks are exactly the same of all four properties. I take two blocks
  at random. What is the probability the two blocks have exactly two of
  the four properties the same?

I try with R to replicate this:
<code>library(matrixStats)
replicateExperiment<-function(i,stateSpace) length(which(colDiffs(stateSpace[sample(1:120,2),])==0))==2
stateSpace<-data.matrix(expand.grid(M=1:2,C=1:3,Si=1:4,Sh=1:5))
mean(c(lapply(1:100000,replicateExperiment,stateSpace=stateSpace),recursive=TRUE))
</code>
I get something more like $P(\text{2 out of 4 characteristics are the same)}\approx .3$.
My question is, how can we compute the number of blocks that have exactly 2 characteristics in common out of all 120 boxes.
What I have done so far:
Let's start with having three in common out of 4 characteristics (4 out of 4 is not possible). There are 4 possible ways to share 3 out of 4 characteristics.
I will denote the characteristics as $\{M,C,Si,Sh\}$ so $P(B_2=\{1,1,1,0\}|B_1=\{1,1,1,0\})$ is the probability that box 2 shares its first three characteristics with box 1 given that box one has characteristics $\{1,1,1,*.*\}$.
Then we have
$$P(B_2 \text{ has 3 elements in common with } B_1)=P(B_2=\{1,1,1,0\}|B_1=\{1,1,1,0\})*P(B_1=\{1,1,1,0\})+P(B_2=\{1,1,0,1\}|B_1=\{1,1,0,1\})*P(B_1=\{1,1,0,1\})+P(B_2=\{1,0,1,1\}|B_1=\{1,0,1,1\})*P(B_1=\{1,0,1,1\})+P(B_2=\{0,1,1,1\}|B_1=\{0,1,1,1\})*P(B_1=\{0,1,1,1\})$$
$$P(B_2 \text{ has 3 elements in common with } B_1)=(4*5*24+3*4*30+2*3*40+1*2*60)\frac{1}{120*119}\approx0.084$$ which is close enough to the value from the simulation code (modified to count the number of 3-ties).
The problem:
Now, I use the same reasoning to compute:
$$P(B_2 \text{ has 2 or more elements in common with } B_1)=(19*20*6+11*12*10+9*10*12+14*15*8+7*8*15+5*6*20)\frac{1}{120*119}\approx0.54$$
This is not close at all to the value from the simulation code (modified to count all $2^+$ ties).
Answer: Here's an ultra kludgy explanation: you need to generate vectors of the form (x4, x3, x2, x1) (where xi = characteristic) and each is drawn from its own domain.
Consider that you want exactly 2 characteristics to match, so given one box, the other one should have 2 characteristics that match (so there's only one way to set those values) and 2 characteristics that don't. (so xi's domain's size minus one ways). And, happily, these are all mutually exclusive.
Vary the characteristics in pairs (and forsaking all elegance):
(2-1)((3-1)+(4-1)+(5-1)) + (2)((3)+(4)) + (12) = 35 (second boxes for each first box);
5/17 is about .29.
Comment: This is so elegant, I need to take a breath!
Answer: Suppose I draw two boxes with the same color, size, and shape (but different material). That pair of boxes is counted in the term for the same {color, size}, but also in the term for the same {color, shape}, and in the term for the same {size, shape}....
Comment: Ok, I understand the problem, but how to compute the total number of doubly counted boxes? Or what formula to use to avoid double counting them in the first place?
Comment: Same basic way that you count the singly counted boxes, just subtract them instead of adding. :)


Select rows per N and do a SUM

Question: I have a table in my SQL Server database with the following contents in it:
Date        | Amount
------------|----------
2012-12-17  | 9.00
2012-12-18  | 8.00
2012-12-19  | 0.00
2012-12-20  | 1.50
2012-12-21  | 2.50
2012-12-22  | 0.00
2012-12-23  | 0.00
2012-12-24  | 0.00
2012-12-25  | 0.00
2012-12-26  | 4.00
2012-12-27  | 2.00
2012-12-28  | 7.00

What I want to do is take 3 rows per select and SUM the Amount. If the total of the SUM is 0, then it should delete those 3 records. Otherwise it should just leave them alone and take the next 3 records and do the same checks.
So in this case only the following three records should get deleted from the table, since they are the only ones where the SUM would result in 0.
2012-12-23  | 0.00
2012-12-24  | 0.00
2012-12-25  | 0.00

How can I do his in SQL Server?
Answer: You can use ROW_NUMBER to make 3 element groups and calucalte sum.
WITH cte AS
(
  SELECT *, rn = (ROW_NUMBER() OVER(ORDER BY [Date]) - 1) / 3
  FROM #tab
), cte2 AS
(
  SELECT *, [sum] = SUM(Amount) OVER (PARTITION BY rn ORDER BY [Date])
  FROM cte
)
SELECT *
FROM cte2
WHERE [sum] = 0;

LiveDemo
And with DELETE:
WITH cte AS
(
   SELECT *, rn = (ROW_NUMBER() OVER(ORDER BY [Date]) - 1) / 3
   FROM #tab
), cte2 AS
(
   SELECT *, [sum] = SUM(Amount) OVER (PARTITION BY rn ORDER BY [Date])
   FROM cte
)
DELETE t
FROM #tab t
JOIN cte2 c
  ON t.[Date] = c.[Date]
WHERE [sum] = 0;

SELECT *
FROM #tab;

LiveDemo2
EDIT:
If your data can contain negative values you can use:
WITH cte AS
(
  SELECT *, rn = (ROW_NUMBER() OVER(ORDER BY [Date]) - 1) / 3
  FROM #tab
), cte2 AS
(
  SELECT rn, [sum] = SUM(Amount)
  FROM cte
  GROUP BY rn
)
SELECT c.*
FROM cte c
JOIN cte2 c2
  ON c.rn = c2.rn
WHERE [sum] = 0;

LiveDemo3
Comment: This only works if it happens that the 3 contiguous Amounts=0 fall into one partitioning group,assuming I understand the question

Select rows per N and do a SUM


Efficient point inside rectangle boundaries search

Question: I'm working on a vector map editor and I have a set of elements, each of which specifies its bounding box within the view. As the mouse moves I want to highlight the first element whose bounding box contains the current mouse location. Right now I use a simple list and go through it, but as the number of elements is likely to increase, the O(n) complexity of the current search algorithm will be problematic for an interactive application.
What would be a better algorithm/data structure for this?
Some additional constraints/requirements:

The filling of the bounding boxes data structure would have to be relatively quick (since I need to do that each time the map moves or the zoom or projection changes).
The algorithm would have to be able to find all of the matching elements (not just the first one). The reason is that some map elements can have irregular shape, so the simple bounding box match is not strict enough. I would then go through the list of matches and do some precise matching.
The order in which the boxes were added to the set needs to be maintained somehow - a map element which is drawn above another element should have a priority when matching their bounding boxes.
Comment: I deliberately didn't mention memory constraints because I wanted to hear several ideas and then make a judgement about speed/memory tradeoff. Can you be more specific about lookup tables in this scenario?
Comment: are there memory constraints? if no: you might want to use lookup table..
Answer: After browsing through books, I've found one answer in Computational Geometry book (p. 237 in 3rd edition; 2008). This type of search is often referred to as stabbing query and is usually implemented using segment trees.
Complexities:

The query: O(log2n + k), where k is the number of reported bounding boxes
The data structure uses O(n*log n) storage
The structure can be built in O(n*log n) time
Answer: If you sort your elements by lower x-location, you can skip all elements before a certain point. If you have a second list with upper x-location, you know when you're done.
Another idea: Create a grid maybe splitting the whole area into 100x100 parts. Now find once out, in which parts of your grid a figure is overlapping:
<code>5
4
3    xx
2  xxxx
1  xx
0
 0 1 2 3 4 5
</code>
For this figure it would be (1,1),(1,2)(2,2)(2,3)
A map of x*y Lists would now contain this shape s for the 4 locations (1,1)->s, (1,2)->s, ...
If you have seldom insertions/deletions, but often comparisions, this would speed your searches up. You would only visit the shapes, associated to a certain cell, and investigate the exact coordinates for these.
Comment: Interesting idea about x*y lists. It would certainly speed up things (depending on how fine the grid is), although I guess the O(n) complexity is still there.
Answer: lookup table: users tend to go back to the same areas on the screen (so margins visit rate is usually low, and center visit rate is usually high). so we can use this knowledge to improve our performance.
after finding a point once (could be any other method of finding) you can cache the results as a list, and next time the user visits the same place, lookup would be O(1). of course you will need to dump the cache once a new shape was added.
 another possibility is using Observer Pattern, each new shape will register itself in the needed points (this could be expensive, depending on how much shape insert is frequent...) and once the mouse is on this point, all it has to do is call whoever registered to this point.
third possibility is of course cutting down your search area like @user unknown suggested. this possibility can be combined with lookup table.
Comment: By "visiting the same place" I assume you mean the same X,Y location? Given the large resolutions of screens nowadays and the mouse sensitivity, how likely would it be for the user to catch the same coordinates? Although I have to admit it is an interesting idea - but probably in combination with some other method, as you suggest.
Comment: @Igor: if you worry about this, you can cut it into frames as @user unkown suggested. if you do this, the only difference between this solution to his, is how you update the look-up table. I would suggest taking a close look at the Observer Pattern as well, this will simplify the coding by using known solutions.
Comment: @Igor: p.s. notice that mouse movements are continuous, the mouse moves in lines, and not from a point to point randomly, increasing Significantly the chances that a point will be selected more then once.
Comment: the problem is that the map view is not fixed, the user can zoom in and out, pan and rotate the map (and she usually does, since this is the nature of the application). So any cached lookup values would quickly become invalidated before they got to be used.


Calling an undefined array element is showing a value of another defined element

Question: When calling an undefined element of an array, it is showing me a value of another defined element.
Example of array structure:
  $array = array(
    'a' => array(
      'b' => 'c'
    )
  );

When using echo command on $array['a']['b']['x'] it is showing me value of 'c'. Why this happens I really don't understand since $array['a']['b']['x'] is not defined.
And then when I try to add another value by using command $array['a']['b']['x'] = 'y';
It is rewriting the value of $array['a']['b'] to 'y'
Somehow I really don't understand this behaviour, can someone explain how is that possible? And how then I will be able to create a new string value at $array['a']['b']['x'] = 'xyz' to not override $array['a']['b']?
Comment: you are defining a 2d array, but trying to use it as a 3d array. how do you expect that to work?
Answer: It is actually not related to arrays at all. This is a string problem.
In PHP you can access and modify characters of a string with array notation. Consider this string:
$a = 'foo';

$a[0] gives you the first character (f), $a[1] the second and so forth.
Assigning a string this way will replace the existing character with the first character of the new string, thus:
$a[0] = 'b';

results in $a being 'boo'.
Now what you do is passing a character 'x' as index. PHP resolves to the index 0 (passing a number in a string, like '1', would work as expected though (i.e. accessing the second character)).
In your case the string only consists of one character (c). So calling $array['a']['b']['x'] = 'y'; is the same as $array['a']['b'][0] = 'y'; which just changes the character from c to y.
If you had a longer string, like 'foo', $array['a']['b']['x'] = 'y'; would result in the value of $array['a']['b'] being 'yoo'.

You cannot assign a new value to $array['a']['b'] without overwriting it. A variable can only store one value. What you can do is to assign an array to $array['a']['b'] and capture the previous value. E.g. you could do:
$array['a']['b'] = array($array['a']['b'], 'x' => 'xyz');

which will result in:
$array = array(
  'a' => array(
     'b' => array(
        0 => 'c',
       'x' => 'xyz'
     )
  )
);

Further reading:

Arrays
Strings
Comment: Very nice and very well written explanation! Thank you a lot! Definitely helped me to get out of the sort of problem I was facing now.


Brachistochrone - Solution of a Cycloid - Parametric Equations

Question: I am trying to understand the math behind the Brachistochrone.
I could understand all the technical intricacies of the mathematical treatment of the topic found at Wolfram-Mathworld|Brachistochrone Problem.
At the last part, they say,
$$
\boxed{\left[1+\left(\frac{\mathrm{d}y}{\mathrm{d}x}\right)^2\right]y = \frac{1}{2gC^2} = k^2} \tag*{(1)}
$$
and then they just say, This equation is solved by the parametric equations and write two equations,
$$
x = \frac{1}{2}k^2(\theta-\sin \theta)\\ \tag*{(2)}
y=\frac{1}{2}k^2(1-\cos \theta)
$$
How did this come?
I plotted them on Desmos and I could clearly see a cycloid (Can be see here).
Note:

I have not shown my steps here because, I am just studying the problem straight from Wolfram. If you wish to have a look at the steps, I have mentioned the link above.
Learning Calculus of Variations on my own. I will be grateful if you could direct me towards some good resources.
I know how to derive the parametric equation of a cycloid, I learnt it from Math.Stackexchange|How to find the parametric equation of a cycloid?. I just don't know how to solve $(1)$ using the two equations in $(2)$.

Thank you.
Answer: I suppose that this is probably the simplest parametrization.
If we consider the differential equation $$1+\left(\frac{dy}{dx}\right)^2=\frac{k^2} y$$ I suppose that we cannot find $y$ as a function of $x$. However, using the positive solution, the equation can write $$\frac{dx}{dy}=\sqrt{\frac y {k^2-y}}$$ which leads to $$x=-\sqrt{y(k^2-y)}+k^2 \tan^{-1}\left(\sqrt{\frac y {k^2-y}} \right)$$ In a first step, use $y=k^2 z$ to get $$x=-k^2\sqrt{z(1-z)}+k^2 \tan^{-1}\left(\sqrt{\frac z {1-z}} \right)$$ and now, just play with trigonometric identities. To get rid of the $\tan^{-1}(.)$, let $$\sqrt{\frac z {1-z}}=\tan(\theta)\implies z=\sin^2(\theta)$$
Comment: Thank you! You gave me a whole new way of looking into the problem. However, this doesn't my question. How does $(2)$ come from $(1)$? Please bear with me, I am just a beginner.
Answer: Note that we can use the trigonometric identities, $\sin(\theta)=2\sin(\theta/2)\cos(\theta/2)$ and $\frac12(1-\cos(\theta))=\sin^2(\theta/2)$, to write $x(\theta)$ and $y(\theta)$ as
$$\begin{align}
&x(\theta)=k^2(\theta/2 -\sin(\theta/2)\cos(\theta/2))\tag1\\\\
&y(\theta)=k^2 \sin^2(\theta/2)\tag2
\end{align}$$
Then, it is easy to see that we have
$$\frac{dy}{dx}=\cot(\theta/2) \tag3$$
Finally, using $(2)$ and $(3)$ it is straightforward to show that
$$\left(1+\left(\frac{dy}{dx}\right)^2\right)y=k^2$$
as was to be shown!
Comment: Crystal Clear. Thank you very much. :) Can you suggest me some good resources to study Calculus of Variations?
Comment: Pleased to hear!  And you're welcome;  my pleasure.  The classical text is Gelfand's and Fomin's "[Calculus of Variations](https://www.amazon.com/Calculus-Variations-Dover-Books-Mathematics/dp/0486414485)."
Comment: Thank you. Once again.
Comment: That probably happened by mistake!
Answer: This is an old post, but there will still be people wanting to know how the parametric equations of the cycloid were obtained from the solution to the DE. Historically, the people who solved this problem already knew that the answer was the cycloid, so they knew the parametric equations, so they just had to show that they satisfied the DE.
You can obtain the parametric equations by using the method demonstrated above by Claude (Though I think there is an error in what he has written above). Once you have ArcTan in the solution, the natural thing to do is to let its argument equal Tan(theta), then go on to obtain Sin and Cos, which requires a substitution, again demonstrated by Claude.  From there, with the double angle formulae, the parametric equations fall out fairly easily.
I can show full working if anyone is interested.


O que é proxy reverso?

Question: Quando eu estava configurando o PHP FPM (modulo do PHP que permite o uso de FastCGI), esbarrei no termo Reverse Proxy quando eu andava pesquisando alguns tutoriais sobre como configurá-lo no Apache 2.
Exemplo tirado desse site, onde é ensinado a instalar o módulo mod_proxy_fcgi:
ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/mysite/$1

Mas o que seria um Proxy Reverso? Eu já ouvi esse termo outras vezes, mas não entendi do que se trata.
Answer: Resposta rápida:
Proxy reverso seria um serviço ou servidor que encaminha  as requisições para outro serviço/servidor de forma transparente.  O cliente (navegador por exemplo) não sabe a existência desse segundo serviço.
No seu caso o serviço httpd(apache) estaria encaminhado o processamento de qualquer requisição contendo .php (é mais ou menos o que a expressão regular ^/(.*\.php(/.*)?) quer dizer ) para o serviço fcgi://127.0.0.1:9000 (servidor local porta 9000).
Esse serviço por sua vez trata a requisição e a resposta usando o apache como um "proxy" para o cliente -- PROXY REVERSO.
Outra possível origem do nome é que normalmente o proxy é usado do lado dos clientes, então o "reverso" dá a ideia que está no outro lado, diferente do "normal".
Answer: Para explicar o que é um Proxy Reverso, acho importante explicar também como ele difere do Proxy.
O Proxy Reverso (Reverse Proxy) é um proxy que podemos dizer que atua do lado do servidor, diferente do Proxy (Forward Proxy) que atua do lado do cliente.
O Proxy preocupa-se em esconder as identidades das máquinas que estão atrás dele, fornecendo mecanismos tais como cache, autenticação, restringir acessos para alguns sites, etc. Assim, quando algum computador dentro da uma rede fazer alguma requisição para Internet através do Proxy, este será encarregado de fazer a requisição, aguardar a resposta e encaminhá-la para o computador que a solicitou.
Já o Proxy Reverso faz o mesmo, mas para os servidores. Quando a requisição chega, o Proxy Reverso obtém aquela informação e a repassa para um dos servidores disponíveis, podendo ser capaz de fazer Load Balance. Ele também pode fazer compressão dos dados, cache de conteúdo frequentemente requisitado, proteger as identidades dos servidores, permitir que eles sejam acessados sob uma única URL, etc.
Veja uma imagem ilustrando ambos:

Em sua essência, ambos são muito parecidos, tendo as mesmas características.
Não sei dizer se isto vale para todos os casos, mas de fato um mesmo proxy pode ser forward e reverse ao mesmo tempo, atendendo populações distintas. Ou seja, de diferente mesmo é só o papel que o proxy vai exercer conforme a necessidade: atender clientes ou servidores.
Answer: Primeiro é interessante entender o conceito do Proxy.
O Proxy é uma camada (middleware, server, qualquer implementação que crie essa camada) entre dois pontos.
Esse é um conceito mais amplo, pode ser aplicado em programas e outras coisas. Para o conceito da pergunta, um Proxy está intermediando dois dispositivos conectados na Internet, que podem ser dois computadores, dispositivo (impressora, gadget, etc), etc.
Qual a razão para usar esse intermediário entre as conexões? Os motivos são diversos:

proteger os dispositivos e suas identidades;
proteger a rede a qual eles fazem parte;
restringir/bloquear acessos indevidos, etc;

Então um Proxy Forward (de encaminhamento) ou simplesmente Proxy, é um middleware, que pode ser um software ou um hardware que está a frente da conexão de um computador ou dispositivo com outro.
A figura abaixo, tirada do Cloudfire, demostra isso:

Veja que, vários computadores numa rede tem à sua frente um Proxy, que faz o intermédio entre eles e um recurso da internet, um servidor por exemplo. As razões podem ser diversas, como as mencionadas acima, como proteger a identidade do computador de origem, ou ainda filtrar o que pode "sair" para a internet, bloqueando acesso a sites adultos ou upload de arquivos por exemplo. Então vamos imaginar o Proxy como

"A camada que está a frente do computador origem e o destino que esse
  quer acessar."

Já essa outra imagem mostra o diagrama de um Proxy Reverso:

Veja que é basicamente o mesmo, os propósitos também podem ser, mas nesse caso o Proxy está a frente do recurso de destino, ou seja,

"A camada que está a frente do computador de destino, e a origem que precisa acessá-lo."

Dai o conceito de "inverso", um está logo após a origem, o outro antes de destino, de uma maneira bem simples é isso que significa.
Answer: Um proxy reverso é um servidor de rede geralmente instalado para ficar na frente de um servidor Web. Todas as conexões originadas externamente são endereçadas para um dos servidores Web através de um roteamento feito pelo servidor proxy, que pode tratar ele mesmo a requisição ou encaminhar a requisição toda ou parcialmente a um servidor Web, que tratará dela
Uma das maiores caracteristicas dos proxy reverso é a sua segurança que faz com que seja mais dificil penetrar no servidor, criptografia em SSL
Espero que te tenha tirado as duvidas

O que é proxy reverso?