Permission forbidden on localhost with apache2

Question: Here is what I am trying to do.
I tried to add another folder to apache and I get the following error when trying to acces testing/index.html.
The idea is that I would like to have for every customer a folder like /home/neagoe/Work/InterWebs/Projects/[PROJECT NAME]/CustomerProjects/website/dist.
Forbidden

You don't have permission to access /index.html on this server.
Apache/2.2.22 (Ubuntu) Server at testing Port 80

Here are the steps that I followed:
Step1:
sudo chmod a+x /home/neagoe/Work/InterWebs/Projects/testing/CustomerProjects/website/dist

Step2:
sudo chown -R www-data:www-data /home/neagoe/Work/InterWebs/Projects/testing/CustomerProjects/website/dist

sudo chmod -R 775 /home/neagoe/Work/InterWebs/Projects/testing/CustomerProjects/website/dist

Step3:
sudo adduser $USER www-data

Step4:
sudo a2enmod userdir

Step5:
sudo cp /etc/apache/sites-available/default /etc/apache/sites-available/testing

I edited the file /etc/apache/sites-available/testing so it looks like this:
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName testing
    DocumentRoot /home/neagoe/Work/InterWebs/Projects/testing/CustomerProjects/website/dist

    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /home/neagoe/Work/InterWebs/Projects/testing/CustomerProjects/website/dist/ >
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Step6:
I edited hosts ("/etc/hosts") so it looks like this:
127.0.0.1       localhost
127.0.0.1       testing

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Step7:
sudo a2ensite testing
sudo service apache2 restart

I searched for about 2 hours on the internet but I can't figure out what went wrong.
All the pages that I found following the same steps as described above.
I know there are similar questions here on the internet, but the answer is to change permission to the directory which I did on Step2.
I am sorry if this is really a duplicate but I could't find the right answer.
Thank you!
PS. I asked this also on AskUbuntu but didn't get any answers so I'm trying my luck here.
Edit:
There isn't much on the error log or the access log.
On the access.log:
::1 - - [10/Aug/2013:11:23:28 +0300] "OPTIONS * HTTP/1.0" 200 126 "-" "Apache/2.2.22   (Ubuntu) (internal dummy connection)"
::1 - - [10/Aug/2013:11:23:29 +0300] "OPTIONS * HTTP/1.0" 200 126 "-" "Apache/2.2.22 (Ubuntu) (internal dummy connection)"
::1 - - [10/Aug/2013:11:23:31 +0300] "OPTIONS * HTTP/1.0" 200 126 "-" "Apache/2.2.22 (Ubuntu) (internal dummy connection)"
::1 - - [10/Aug/2013:11:23:32 +0300] "OPTIONS * HTTP/1.0" 200 126 "-" "Apache/2.2.22 (Ubuntu) (internal dummy connection)"
::1 - - [10/Aug/2013:11:23:33 +0300] "OPTIONS * HTTP/1.0" 200 126 "-" "Apache/2.2.22 (Ubuntu) (internal dummy connection)"
::1 - - [10/Aug/2013:11:23:34 +0300] "OPTIONS * HTTP/1.0" 200 126 "-" "Apache/2.2.22 (Ubuntu) (internal dummy connection)"
::1 - - [10/Aug/2013:11:23:35 +0300] "OPTIONS * HTTP/1.0" 200 126 "-" "Apache/2.2.22 (Ubuntu) (internal dummy connection)"
127.0.0.1 - - [10/Aug/2013:11:23:23 +0300] "POST /wordpress-testing/wp-cron.php?doing_wp_cron=1376123003.7026669979095458984375 HTTP/1.0" 200 705 "-" "WordPress/3.6; http://localhost/wordpress-testing"
::1 - - [10/Aug/2013:11:23:36 +0300] "OPTIONS * HTTP/1.0" 200 126 "-" "Apache/2.2.22 (Ubuntu) (internal dummy connection)"
::1 - - [10/Aug/2013:11:23:37 +0300] "OPTIONS * HTTP/1.0" 200 126 "-" "Apache/2.2.22 (Ubuntu) (internal dummy connection)"
::1 - - [10/Aug/2013:11:23:38 +0300] "OPTIONS * HTTP/1.0" 200 126 "-" "Apache/2.2.22 (Ubuntu) (internal dummy connection)"
127.0.0.1 - - [10/Aug/2013:11:31:32 +0300] "GET /index.html HTTP/1.1" 200 485 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0) Gecko/20100101 Firefox/23.0"

And the last line repeats for about 200 rows.
On the error.log:
1. This lines repeat from time to time.
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20100525   /msql.so' - /usr/lib/php5/20100525/msql.so: cannot open shared object file: No such file or directory in Unknown on line 0
[Sat Aug 10 13:06:42 2013] [notice] Apache/2.2.22 (Ubuntu) PHP/5.4.9-4ubuntu2.2 configured -- resuming normal operations
[Sat Aug 10 13:07:36 2013] [notice] caught SIGTERM, shutting down
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20100525/msql.so' - /usr/lib/php5/20100525/msql.so: cannot open shared object file: No such file or directory in Unknown on line 0
[Sat Aug 10 13:07:37 2013] [notice] Apache/2.2.22 (Ubuntu) PHP/5.4.9-4ubuntu2.2 configured -- resuming normal operations

2. And this is the predominant error. (hundreds of lines)
[Sat Aug 10 13:07:40 2013] [error] [client 127.0.0.1] (13)Permission denied: access to /index.html denied

Comment: Can you include the relevant items from your apache accesslog and errorlog?
Comment: I included them.
Answer: There are directories above /home/neagoe/Work/InterWebs/Projects/testing/CustomerProjects/website/dist/
that are overidding the permissions. Try modifying the root directory to
<Directory />
        Options FollowSymLinks
        AllowOverride All
</Directory>

While not a desirable solution that can help weed out where you're getting blocked. I would then try a mixture of Allow and Deny statements in the root directory until you get an acceptable blend of security and functionality.
Comment: Actually I am going to downvote myself, since I've lead you astray. The error-log infers this http://wiki.apache.org/httpd/13PermissionDenied so a file level permissions error. Although not recommending this for production, chmod 777 if you're willing to try anything to get it working
Comment: I tried this, but still not working.
Comment: throw in an `allow from all` in the `/` then maybe? The basic idea is too loosen the permissions within apache to identify the configuration directive that's got you blocked. Is there a httpd.conf anywhere in the apache ServerRoot that might have be tripping you up?
Comment: or chmod 644 just the file /index.html for starters
Comment: I tried both of your suggestions and still not workig. There was a httpd.conf but it had nothing to block me, anyway  I even commented everything on there. Also I tried to move everything to Work1 and ran chmod 777 for Work1 and still nothing.
Comment: As inetplumber said, the error log specifies the problem lies in file permissions, not Apache config.

If one of the higher folders has `neagoe` as owner and 700 permissions (for example), the file higher up in the file tree will always be denied access. Could you run a `chmod 777 /home/neagoe/Work -R`?
Answer: You need to verify that all directories leading to the final directory are accessible by Apache.
/home/neagoe/Work/InterWebs/Projects/testing/CustomerProjects/website/dist

Most commonly, the home directory (/home/neagoe) will have 750 or 700 permission to prevent other users from accessing it. That will be a problem for Apache.
If that's the case, you can chmod 755 it (consider if there are any security risks in doing so in your environment first) or chmod 750 (remember to add Apache to the group that owns the directories in this case).


Como mudar a mensagem de um commit enviado para o repositório remoto

Question: Fiz 3 commits no repositório local e enviei para o repositório remoto utilizando o push.
Reparei que a mensagem de um dos commits estava errada. Como faço para mudar a mensagem nas seguintes condições:

O commit já foi enviado para o repositório remoto;
Um programador atualizou o repositório local com o commit errado.
Outro programador atualizou o repositório local e logo a seguir fez um novo commit atualizando o repositório remoto.
Outro programador também atualizou o repositório local, fez um novo commit mas não atualizou o repositório remoto.

Ou seja:
1. Repositóro remoto
       o--->A--->B--->C

2. Programador X
       o--->A--->B--->C

3. Programador Y
       o--->A--->B--->C--->D
   Repositóro remoto
       o--->A--->B--->C--->D

4. Programador Z
       o--->A--->B--->C--->E
   Repositóro remoto
       o--->A--->B--->C--->D

Supondo que o commit com a mensagem errada é o B, como corrigir a mensagem?
Comment: Não tem como você corrigir, a única alternativa seria se ninguém tivesse feito o `pull`, você poderia corrigir localmente e fazer um `push force`, o que não é legal porque muda totalmente a história do repositório e os outros usuários teriam problemas
Comment: @Gerep Então o que é recomendado fazer? Um commit com uma mensagem errada também pode ser problemática.
Comment: Você pode tentar usar o comando `git revert`: https://git-scm.com/docs/git-revert

Você não vai conseguir fazer esse commit desaparecer, só corrigir o que foi feito, o histórico vai fica aí =(
Answer: Como foi colocado nos comentários, a solução drástica seria você fazer o reset para o commit imediatamente anterior, com o comando:
git reset --hard <commit>
git push --force

Mas lembre-se: TODO o histórico após esse commit será perdido para sempre.
Caso você queira, também pode fazer o comando revert, que elimina o commit sem desfazer o histório. Para isso, basta usar o comando
git revert <commit>
git push

Mas esse comando perderá o conteúdo do teu commit, mas não afetará o histórico depois dele.
Comment: Mas se o revert elimina o conteúdo do commit, como fica então as alterações que foram realizadas nesse commit? Tenho que refazê-las? Não há maneira no Git de inserir uma nota, por exemplo, deixando a mensagem original, porém com uma nota de correção, ou algo do gênero?
Comment: Como foi dito nos outros comentários. Não há maneira de você alterar só a mensagem do commit ou alterar o conteúdo de um só arquivo desse mesmo commit ou mesmo o horário do commit. Essas operações são atômicas. Você poderia refazer a alteração que constava nesse commit em outro, com a mensagem correta.


When $ax+by+cz+d=0$ is a plane, $a^2 + b^2 + c^2 \neq 0$

Question: I'm reading a book about equation of planes and an way to determinate the equation is to suppose a point $P = (x, y, z)$ And suppose also that $A=(x_0, y_0, z_0)$ is in the plane. $P$ is in the plane if the vector $\vec {AP}$ and the direction vectors $\vec {v_1} = (r,s,t) $ and $\vec {v_2} = (m,n,p)$ are linearly dependent. This is the same as saying that the determinant of a matrix that contais these vectors as its lines, is $0$.
$$\begin{vmatrix} x-x_0 & y-y_0 & z-z_0\\r & s & t\\m & n & p \\\end{vmatrix} = 0$$
Solving this, we get the equation of the plane:
$$x\underbrace{(sp-nt)}_{a} + y\underbrace{(tm-pr)}_{b} + \underbrace{z(rn-ms)}_{c} + \underbrace{-x_0(sp-nt) -y_0(tm-pr) - z_0(rn-ms)}_{d}$$
$$ax + by + cz + d = 0$$
Then, he says that $$a^2 + b^2 + c^2 \neq 0$$
wich is the same as saying that $a$,$b$, anc $c$ are not simulteneosly $0$. He says that if they were, then $\vec{v_1}$ and $\vec{v_2}$ would be L.D., thus, would not define a plane. I have no idea how to verify that hey would be linearly dependent. Could yous guys help me? Thanks!
Answer: if $a=0, b=0$ and $c=0$, then $sp=nt$, $tm=pr$ and $rn=ms$ and therefore (if $m,n,p$ are distinct from $0$):
$(r,s,t)=(r/m)(m,n,p)=(s/n)(m,n,p)=(t/p)(m,n,p)$
Now, if some of them is zero, we have to do some cases, but it is more annoying than difficult.
(I wanted to post this as a comment, but I have not enough reputation).
Answer: Two vectors are linearly dependent if one is a scalar constant times the other. The idea here is that if you place two vectors having different directions with their tails together, there's a unique plane that they both lie in. But if they end up lying on top of each other (that is, they're collinear), then there are infinitely many planes that contain both.
Comment: I know this, but how would this prove that $a$,$b$ anc $c$ are not simulteneosly $0$?
Comment: Not sure exactly what you're asking. Conceptually, $a$, $b$ and $c$ are the $x,y,z$-components of the cross-product of $\vec v_1$ and $\vec v_2$. The magnitude of that cross-product vector is the magnitude of $\vec v_1$ times the magnitude of $\vec v_2$ times the sine of the angle between them. If $v_1$ and $v_2$ have nonzero magnitudes and the angle between them is nonzero (and less than 180 degrees), then the cross-product vector won't come out as $(0, 0, 0)$.
Comment: it's because I'm only allowed to use cross product in an orthogonal coordinate system, but this method works in every coordinate system. So I need to prove it in another way.
Comment: So you're saying that the book gave you a problem and asked you to solve it within certain constraints? You didn't say that before! You are supposed to prove that $(a,b,c) \neq (0,0,0)$ and do it without the cross product. OK, I guess Devilathor was smarter than I at divining your meaning, because he gave the answer, using contraposition: if $(a,b,c)=(0,0,0)$, then $(r,s,t)$ equals $(m,n,p)$ times a constant.


Validar formulário e Enviar email

Question: Eu tenho um código onde faço a validação dos campos em brancos, porém eu queria saber como faço para que quando os campos estejam preenchidos ele execute o submit para a página send.php
Form:
 <form method="post" action="send.php">

            Nome
            <input type="text" class="form-control" id="nome" name="nome" placeholder="Insira seu Nome">

            E-mail
            <input type="fqemail" class="form-control" id="email" name="email" placeholder="Insira seu E-mail">

            Celular
            <input type="text" class="form-control" id="celular" name="telefone">

        <select id="pais" hidden></select>

            Estado
            <select class="form-control" id="estado" name="estado">
            </select>

            Cidade
            <select type="text" class="form-control" id="cidade" name="cidade" placeholder="Insira sua Cidade">
            </select>

            Mensagem
            <textarea class="form-control" id="mensagem" name="mensagem" rows="3"></textarea>

<button type="button" class="btn btn-primary valida" id="send">Enviar</button>

Validação:
$(".valida").click(function(){

    // remove as mensagens de erro
    $(".erromsg").remove();

    // verificar se os campos foram preenchidos
    var nome = $("#nome");
    var email = $("#email");
    var celular = $("#celular");
    var estado = $("#estado");
    var cidade = $("#cidade");

    // Mensagem de erro padrão a ser inserida após o campo
    var erromsg = '
Por favor, preencha o campo
';

    if(!nome.val() || nome.val().length < 5){
       nome.after(erromsg);
       $(".erromsg span").text("Nome*");
       return;
    }

    if(!email.val()){
       email.after(erromsg);
       $(".erromsg span").text("E-mail*");
       return;
    }

    if(!celular.val()){
       celular.after(erromsg);
       $(".erromsg span").text("Celular*");
       return;
    }

    if(!estado.val()){
       estado.after(erromsg);
       $(".erromsg span").text("Capital*");
       return;
    }

    if(!cidade.val()){
       cidade.after(erromsg);
       $(".erromsg span").text("Estado*");
       return;
    }
});

Comment: eu não entendi bem você quer que ele só envie caso todos os campos forem preenchidos ? e porque os outros campos estão hidden ?
Comment: eu to ocultando com hidden, para mostrar o próximo campo após o primeiro ser preenchido, então como eu to usando o type="button" quando termino de preencher o formulário, não executa o submit e eu não sei fazer essa parte funcionar rs
Comment: vocÊ pode usar um button e usar o type="submit" não resolveria seu caso ?
Comment: quando eu uso o type="submit", ele não valida os campos, ele executa direto o send.php, como eu to usando o botão de Enviar para validar toda vez que é clicado nele, por isso esotu com esse problema
Answer: Montei uma base pra ajudar a resolver o seu problema, você pode usar o submit(); e usar uma lógica básica de verificação de retorno false, quando ocorrer um return false; ele não irá submeter o formulário, caso não nenhum return false ele submete o formulário.

//  Bind the event handler to the "submit" JavaScript event
$('form').submit(function () {

    // Get the Login Name value and trim it
    var name = $.trim($('#nome').val());

    // Check if empty of not
    if (name === '') {
        alert('O Campo Nome está vazio.');
        return false;
    }
});

  <form method="post" action="send.php">

                  Nome
                  <input type="text" class="form-control" id="nome" name="nome" placeholder="Insira seu Nome">

      <button type="submit" class="btn btn-primary valida" id="send">Enviar</button>
  </form>

A validação realizada, remove os espaços entre a primeira e ultima letra, e verifica se existe algum texto, e caso sim retorna um alert. no seu caso você coloque a atualização do campo demarcado.
Testa ai e vÊ se funciona para seu caso.
Answer: Coloque no final da função do evento click um trigger de submit:
$(this).closest("form").submit();

Como você está usando return em todas as validações, essa linha acima só será executada se passar por todos os if's.
O $(this) é o elemento que disparou o evento (no caso o botão). O .closest("form") irá buscar a tag form onde está o botão e o .submit() envia o formulário.
Ficará assim:
$(".valida").click(function(){

   // códigos das validações

   $(this).closest("form").submit(); // última linha da função

});

Comment: Funcionou, muito obrigado!
Answer: Pode dar um id ao seu formulário
e depois fazer submit por jQuery
$('#id').submit();

Validar formulário e Enviar email


Returning different components in different scopes with Autofac

Question: I have two scopes, one nested inside the other. When I resolve a particular service, I would like one component to be resolved in one root scope and a different one in the child scope. Is there an easy way of doing this?
I have managed to get something working using a factory class that determines what the current scope is and then returning the appropriate instance:
IContainer BuildContainer()
{
    var builder = new ContainerBuilder();

    // ...
    builder.RegisterType<FooInParentScope>().AsSelf();
    builder.RegisterType<FooInChildScope>().AsSelf();
    builder.RegisterType<FooFactory>().AsImplementedInterfaces();
    builder.Register<IFoo>(c => c.Resolve<IFooFactory>().GetFoo()).InstancePerLifetimeScope();
    // ...
}

class FooFactory : IFooFactory
{
    private readonly ILifetimeScope m_scope;

    public FooFactory(ILifetimeScope scope)
    {
        m_scope = scope;
    }

    public IFoo GetFoo()
    {
        if (m_scope.Tag == "ParentScope")
            return m_scope.Resolve<FooInParentScope>();
        else
            return m_scope.Resolve<FooInChildScope>();
    }
}

class FooInParentScope : IFoo
{
}

class FooInChildScope : IFoo
{
}

There are a number of issues with this approach:

I have to add an extra class (or 2 - not sure if the IFooFactory is really necessary)
The code above does not cope with other scopes that are nested in ParentScope. I can fix this by casting the scope to Autofac.Core.Lifetime.LifetimeScope and examining the ParentLifetimeScope property, but that is probably not a particularly safe thing to do.
Answer: You may register FooInParentScope in root container as SingleInstance. And when creating inner lifetimescope add registration for FooInChildScope as SingleInstance (override registration).
builder.RegisterType<FooInParentScope>().As<IFoo>.SingleInstance();
var container = builder.Build();

var childScope = container.BeginLifetimeScope(innerBuilder =>
    {
        // override registration for IFoo in child lifetime scope:
        innerBuilder.RegisterType<FooInChildScope>().As<IFoo>().SingleInstance();
    });

FooInParentScope fooInParentScope = (FooInParentScope) container.Resolve<IFoo>();
FooInChildScope fooInChildScope = (FooInChildScope) childScope.Resolve<IFoo>();

Comment: That's a way of handling it that I had not thought of. The downside is that you have to do some additional registration at the point of creating the scope, rather than having it all in one place.


Finding a real function using boundary conditions

Question: If I have a region $R=\{z\in \mathbb{C}:1<|z|<2\}$. I want to find a real valued function $f$ which takes values $x$, $y$ where $f$ has boundary conditions: $1$ when $|z| = 1$ and $2$ when $|z| = 2$. We also have that $f$ is harmonic.
To start this I know $f$ has to be real, the real part of a complex logarithm is constant if $|z|$ is constant, so using the $\operatorname{Log}(z)=\ln|z|+i\operatorname{Arg}(z)$ the only way this can be real is if we consider $\ln|z|$. We also know that $f$ is harmonic so $f_{xx}+f_{yy}=0$. I think I need to find a branch cut for $\ln|z|$ but I am unsure actually how this helps? Could someone help me out I don't really know how branch cuts come into this?
Answer: $\ln |z|$ is harmonic in $\Bbb C \setminus \{ 0 \}$ because it is locally the real part of any complex logarithm. Therefore
$$
 f(z) = 1 + \frac{\ln |z|}{\ln 2}
$$
is harmonic in $R$ and satisfies the given boundary conditions.
Comment: Thank you, do you think you could add some detail on how you got this?
Comment: @LoliEvans: Which part is unclear? You essentially suggested in your question to consider $\ln |z|$ as a harmonic function. Then an affine transform $a + b \ln |z|$ is harmonic as well. Finally determine $a$ and $b$ such that the boundary conditions are satisfied. – This works because $R$ and the given boundary conditions are radially symmetric.


Composing chord progressions for samba

Question: I know that there are questions on samba chords, samba rhythm, samba shapes and samba melody but, as far as I am aware, this site does not have a question about the tonality and harmony of samba music.
More specifically, my question is aimed at bossa nova style guitar (I am composing this for my GCSE music coursework).
I understand what sort of chords I should be using and how to use those chords rhythmically, but I could use a hand with learning how to piece these together.
I know that samba is based around major II-V-I progressions, but that's about it. I can't just make a song out of a repeated pattern like that.
I don't want to plagiarise other artists by using their progressions. I want something original, but I am not sure how to do so.
Suggestions would be greatly appreciated. I need a 3-4 minute piece, so I need plenty of ideas!
Comment: Everyone plagiarises chord progressions, even the greats.
Answer: To expand on my comment - don't be afraid to plagiarising chord progressions. Most of the blues canon is based on the same three chords in the same order. There are hundreds of classics we just wouldn't have, if people had been unwilling to duplicate chord progressions.
A great deal of Samba is just as formulaic.
You said: "Samba is based around major II-V-I progressions, but that's about it. I can't just make a song out of a repeated pattern like that."
People have written successful songs with only one chord (e.g. The Beatles' Tomorrow Never Knows). There are loads of great songs with only two chords (Paperback Writer; Memphis Tennessee, ...).
It's tempting to think that you must do more than loop through three chords over and over again -- Amy Winehouse's Back To Black proves that it can be enough. Or, to drag us back to Latin America - La Bamba.
My suggestion is to try writing a Samba based on a II-V-I progression. It's OK if it's a bad song -- writing a bad song is better than writing no song. You can expect to write lots of bad songs for every good song you come up with.
Then see if you can improve it by adding some different chord progressions. Maybe the same chords in a different order, for a chorus; maybe introduce one more chord. Decide whether what you've done is an improvement, or not. La Bamba wouldn't be improved by the addition of another chord.
Answer: You want samba or bossa nova? These styles are quite different, almost as distinct genres. I assume you are talking about some "ready-to-export" samba music made throughout the 1970-80s (which culminated into some crappy lounge music for couples making out). That said, I suggest you listening to some samba music more extensively (in historical order, if you can; the following are subgenres of samba): Samba de Roda, Samba de Barracão, Samba-Enredo, Partido Alto, Samba-Canção (this last one is where Bossa Nova comes from). Then you will see that samba goes far beyond "II-V-I" (a rather simplistic way for analyzing it), and has rather approached such proggression very sparsely.
That said, samba has been deeply developed, explored, exploited and abused. The worst way to start at it is by trying to be original. You learn by mimicking the greats, unless you are an utter genius ahead of your time (I am not saying you are not one).
Side note: lyrics are a great part of the construction of samba. Such genre was born as song-oriented, and has a distinct prosody, vocabulary and phraseology. That's why samba appears to be so plastic-ish and snubbish when translated/versioned to anglo-saxonic languages.
Good luck. You are diving into very deep waters!

Composing chord progressions for samba


How to provide Dockerfile for mlflow models build-docker

Question: I have created a Model using pyfunc file with mlflow which usage a conda_env to install packages required for model.
pip_env = {
    'pip': [
        'pandas==0.24.1',
        'python-dateutil==2.8.1',
        'fuzzywuzzy==0.7.0'
    ]
}
conda_env = {
    'channels': ['defaults'],
    'dependencies': [
        'python=3.7.0',
        'pip=20.2.3',
        pip_env
    ]
}
mlflow.pyfunc.save_model(path=model_path, python_model=gfeCleanPrediction(), artifacts=artifacts, conda_env=conda_env,code_path=code_path)

I need to use my own Dockerfile which will build some packages from source and install, Is there a way I can provide it while running below command :
mlflow  models build-docker -m MODEL_FOLDER_V-1-0-1 -n my_model --install-mlflow

I can see mlflow provide a custom_setup_steps_hook parameter in /python3.7/site-packages/mlflow/models/docker_utils.py
def _build_image(image_name, entrypoint, mlflow_home=None, custom_setup_steps_hook=None):
    """
    :param custom_setup_steps_hook: (Optional) Single-argument function that takes the string path
           of a dockerfile context directory and returns a string containing Dockerfile commands to
           run during the image build step.
    """
    mlflow_home = os.path.abspath(mlflow_home) if mlflow_home else None
    with TempDir() as tmp:
        cwd = tmp.path()
        install_mlflow = _get_mlflow_install_step(cwd, mlflow_home)
        custom_setup_steps = custom_setup_steps_hook(cwd) if custom_setup_steps_hook else ""
        with open(os.path.join(cwd, "Dockerfile"), "w") as f:
            f.write(
                _DOCKERFILE_TEMPLATE.format(
                    install_mlflow=install_mlflow,
                    custom_setup_steps=custom_setup_steps,
                    entrypoint=entrypoint,
                )
            )

How to use custom_setup_steps_hook OR use my own Dockerfile in mlflow  models build-docker??
Answer: What you could do is build an image the way mlflow wants you to (lets call it base-mlflow-image) and then use that as the base image in your custom dockerfile so start it with:
FROM base-mlflow-image

... install your custom packages

then use that image to deploy your model
Comment: do you have an example image?


Como setar uma valor no select que é montado com ng-options

Question: Meu HTML é assim:
<select ng-model="cliente" ng-options="t.value as t.displayName for t in clientes"></select>

No Controlador do meu JS tenho:
$scope.clientes // objeto onde tem todos os clientes para alimentar o select
$scope.cliente // esse é o meu ng-model

Meu select está funcionando perfeitamente, consigo obter os dados e salvar eles. Minha duvida é a seguinte, como faço para preencher esse select via javascript? Eu pensei que quando eu coloca-se um valor no $scope.cliente ele iria funcionar, mas não funcionou!
Alguém sabe como fazer isso? Obrigado
Answer: Continuei testando aqui e descobri a solução.
No meu $scope.cliente eu estava setando um valor do tipo number e tem que ser do tipo string.
Ex:
Eu troquei isso:
$scope.cliente = 1;

Por isso:
$scope.cliente = '1';

E funcionou!
Abraços


Can we do a regression for statistically insignificant data?

Question: I'm testing the sensitivity of different factors on the benefits of precision irrigation. The change in the inputs is changing the output but not significantly.
How is it possible to do a regression for these factors?
Comment: Of course. How would you for instance find out that a variable is not 'statistically significant' if not by regression?
Comment: If this means your inputs and outputs are not correlated, you can not perform a regression.
Comment: What do you mean by 'significantly'?  If you mean changes in the input change the output 'by a small amount' then you can certainly run the regression.  You may get a larger standard error than you would like (and hence a larger p-value) depending on how much data you have and how much noise there is, but you can definitely do it.  There is a difference between 'statistically significant' and 'significant' as in a large regression coefficient.  Hope that helps...
Comment: what if the variables are not completely dependent? shall we do a step wise regression?!
Comment: Nope. Look up stepwise regression before performing it (as with any analysis you don't understand), and read my answer. You don't need your variables to be completely dependent or completely independent to perform regression analysis. Its purpose is to estimate the degree of dependency, so its functionality *can't* depend on this.
Answer: The basic function of regression analyses is to estimate the strength of predictive associations between predictor (independent) variables and target (dependent) variables, usually both in terms of individual predictors and the total set of predictors (when there is more than one, as you've implied is relevant to your question's motivation). Much like a bivariate correlation, these predictive associations are essentially matters of effect size first, and can only become matters of significance by asking a question about these estimates, such as, "Do I think that more than 5% of all the other random samples like mine could exhibit predictive associations as strong or stronger than the one present in my sample, yet in fact be drawn from a population in which there is no association overall?" This is the question a typical null hypothesis significance test aims to answer about a regression model or regression coefficient. It is a question about an association that doesn't inherently need to involve matters of significance; one can ask it about any point estimate of a regression coefficient regardless of what data is used in producing the estimate, let alone whether that estimate is different from zero at all.
@ExpectoPatronum's comment is false. Even the correlation of completely uncorrelated data can be calculated ($r = 0$). If someone sets out to test "the significance" of this correlation, one probably means to test the two-tailed significance of its difference from zero. Since $r = 0, t_{(N-2)} = 0, p = 1$, but this doesn't stop one from using the relevant formulas to "calculate" these results.  The same is true in linear regression. If all $\beta = 0$, then the model's $R^2 = 0$, the omnibus $F_{(N-k-1)} = 0, p =1$, and all individual $t_{(N-k-1)}=0, p=1$. Totally "insignificant" results in the common sense of being identical to zero, but still a completely possible result of the analysis. If this result weren't a possible outcome of any significance test, one couldn't really claim to be falsifying the typical null hypothesis with it. Regardless, the significance tests aren't really necessary to consider when estimating $\beta$ or $R^2$, which are the only definitional products of bare-bones regression analysis. One can consider the significance of one's estimates of these parameters after calculating them if desired, but the estimation process is the more basic statistical procedure that has to precede the usual significance question, not the other way around.
To be fair, a more interesting interpretation of "significance" in this question might be with respect to a prior significance test of the data's distributional normality or homoscedasticity, but I assume these aren't the significance tests you have in mind. You seem to be worried about the weakness or uncertainty of causal(?) associations. At no extreme do these qualities of data utterly preclude regression analysis; they do not affect one's basic ability to perform the analysis at all. The validity of regression results is a different matter, however.
Answer: You can "do" a regression between any dependent (or output) variables and any independent (or input) variables. Different sorts of regression make different assumptions about the data (but often these are about the error term, as estimated by the residuals from the model).
You cannot know if the regression is significant without doing it.
Beyond that, it is hard to say, since you haven't told us anything about the data. What is your output variable? What is/are your input variable(s)? How were they collected? What is your sample size? etc.
You may find my post How to Ask a Statistics Question helpful in formulating your question.
Comment: it's not a survey. I've just calculated the benefits of an irrigation system and tried to change the inputs by a certain range  to observe how the benefits would change therefore my output is Y=benefits and I have about 50 repetitions (changing 8 inpupts 6 times)


procmail rewrite subject line if email recipient user fails match test

Question: I have a local procmail user "bob".
If an email arrives and matches email@example.com, then no action should be taken.
However, if an email arrives and is [anything_else]@domain.com then I would like to rewrite the subject line to insert "[spam]" at the front of the subject line.
So it is a reverse match on "bob@" (match on anything other than bob@) and we preserve the original subject line, just prepending "[spam]" to the front of it.
How can I do that with Procmail?
Answer: Your requirements are rather unclear. Procmail can match on any string, but do you really mean to look for the string anywhere in the message? And do you really mean to ignore messages without domain.com in them for the purpose of this rule?
:0 HB
* ! ()\<bob@domain\.com\>
* @domain\.com\>
{
    :0fhw
    * ^Subject:\/.+
    | formail -I"Subject: [spam]$MATCH"
}

The \< and \> word boundaries prevent matching on substrings like tombob or subdomain.complete.org, and the empty parentheses are a hack because Procmail is weird about regexes which start with a backslash.
If you mean you want to look only in the headers, drop the HB from the first colon line (you could leave the H but that's the default if you don't put any  flags). If you want to match a specific header, spell it out. If you want to examine the recipient specifically, the ^TO_ macro lets you do that in a number of different headers (To:, Cc:, etc) easily.
:0fhw
* ! ^TO_bob@domain\.com\>
* ^TO_[^<>@ ]+@domain\.com\>
* ^Subject:\/.+
| formail -I"Subject: [spam]$MATCH"

Because we dropped the HB flags, we can combine what was previously two recipes with different flags. The second ^TO_ checks for any address including bob, which however was already excluded by the previous negated condition.
This still has some corner cases which might need to be explored further; if you can edit your question to clarify it, perhaps I can update this to cover more than the basics.
SMTP doesn't require the recipient to be spelled out in the headers, though. The classic case is Bcc: which is also essentially the mechanism used by many mailing lists. Perhaps your MTA will spell out the recipient in Delivered-To: but properly speaking, this type of filter is better implemented in the MTA instead.
Comment: No, I do not mean to look for the string anywhere in the message - just in the TO field ... so if TO matches email@example.com, no action taken.  BUT, if the TO field is anything else, then I would like to rewrite the subject line with [SPAM] at the beginning.  Make sense ?
Comment: Anything at all, or any other recipient in this specific domain, like your question says? The second example already shows you exactly how to do this.
Comment: I tested the second example and it works very nicely - although there is one thing ... if the subject line is totally blank it stays blank - it does not get rewritten ...
Comment: You can change the last `.+` in the Subject: condition to `.*` to also capture empty Subject: lines. (Nobody should be sending messages with empty subjects, though.)


Date comparison of nearly the same values

Question: I have a table with two columns created_at and valid_from.
They suppose to be the same in most of the cases in my database.
When I want to get all of them where both columns are equal I get zero records.
Order.where('created_at == valid_from').length

Order Load (3609.4ms)  SELECT "orders".* FROM "orders" WHERE (created_at <> valid_from)
=> 0

So I took another aproach:
ord = Order.where("created_at != valid_from").first
  Order Load (741.0ms)  SELECT  "orders".* FROM "orders" WHERE (created_at != valid_from) ORDER BY "orders"."id" ASC LIMIT $1  [["LIMIT", 1]]
ord.created_at == ord.valid_from
  => false
ord.created_at
  => Wed, 04 Jul 2018 11:34:44 CEST +02:00
ord.valid_from
  => Wed, 04 Jul 2018 11:34:44 CEST +02:00
ord.valid_from.to_i
  => 1530696884
ord.created_at.to_i
  => 1530696884
ord.valid_from.to_i == ord.created_at.to_i
  => true
ord.valid_from == ord.created_at
  => false
ord.created_at.to_f
  => 1530696884.26669
ord.valid_from.to_f
  => 1530696884.2668211

So there is the micro, tinny difference between two dates. From the Rails perspective, it's the same. For the database - not.
What would be the best approach to deal with dates with micro differences?
Comment: Not sure how to do this with this Ruby syntax, but you can use [`date_trunc('second', ...)`](https://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC).
Comment: In pgsql you can do this with "::date"     For eg: SELECT 'Wed, 04 Jul 2018 11:34:44'::date    . SELECT "orders".* FROM "orders" WHERE created_at:date = valid_from:date
Answer: Take a look at this wonderful function of Postgres date_trunc(). :)
So basically comparison will look like
WHERE (date_trunc('second', created_at) != date_trunc('second', valid_from))

In your case, I think, rounding to "second" will be fine.
Hope it helps!
Comment: Working solution, tnx
Answer: Try the "::date" if you don't want to consider time but only date
For eg: SELECT 'Wed, 04 Jul 2018 11:34:44'::date
SELECT "orders".* FROM "orders" WHERE created_at:date = valid_from:date

Comment: Thank you but time is also important.


Override reformatting of cell excel VBA

Question: I have a large number of excel sheets with a date column in the form "dd-mm-yyyy". I need to sort the rows by the date in this date column. Manually if I select the column and replace all "-" with "/" then Excel auto formats the date cells from "General" to a "Date" number format so they can be easily sorted. Specifically it is the "*dd/mm/yyyy" since I am in Australia.
However when I recorded the macro it looks like this:
Range("D13:D134").Replace What:="-", Replacement:="/", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False

When I run the macro:

If the date has a day 12 or less then it flips the day and month fields      and changes the number format to Date
Otherwise it leaves the number format as General.

Before:
After:
I have tried setting the ReplaceFormat with:
Worksheets("Worksheet").Range("A1").NumberFormat = "d/mm/yyyy"
Application.ReplaceFormat.NumberFormat = "d/mm/yyyy"

Range("D13:D134").Replace What:="-", Replacement:="/", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=True

Now all the cells have a number format of date but still can't be sorted as ascending (only A-Z option is available) and there is still the same issue with swapping date and month fields on certain cells.
I even tried to append an X to the start of the cell so it would remain a general format during the replace. Then removing the X after. Same result.
For x = 13 To 134
Cells(x, 4) = "X" & Cells(x, 4)
Next x

Range("D13:D134").Replace What:="-", Replacement:="/", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False

For x = 13 To 134
Range("D" + CStr(x)) = Right(Range("D" + CStr(x)), Len(Range("D" + CStr(x))) - 1)
Next x

Answer: Does it work for you?
On Error Resume Next
For x = 13 To 134
    If Range("D" & x) <> "" Then
        Range("D" & x) = CDate(Range("D" & x).Value)
    End If
Next x
On Error GoTo 0

Answer: VBA isn't required for this!  You can fix the dates in 2 steps using excel functionality.
First you need to delimit the data:

Highlight your dates
Go to the 'Data' tab -> Click 'Text to Columns' in the Data Tools Section
In the pop-up select 'Delimited', then click Next
Under 'Delimiters' deselect 'Tab' and select 'Other'.   Type - into the box then click Next
Pick a destination cell next to your data so it doesn't get overwritten. Click Finish

Second, use the delimited data to create proper Excel dates
  You can use the following formula to get a date from your delimited data:
=DATE( [cell with year], [cell with month], [cell with day])
Comment: Thanks but I wanted to use VBA to automate the process as i have like 3000 sheets. Still I see how I could have used this answer to get me there, but someone else solved it perfectly.
Answer: A Date Issue
Sub DateProblem()

    Const cStrSheet As String = "Sheet1"
    Const cStrRange As String = "D13:D134"
    Const cStrCell As String = "E13"

    Dim vntS As Variant
    Dim vntT As Variant
    Dim i As Long

    vntS = Worksheets(cStrSheet).Range(cStrRange)
    ReDim vntT(1 To UBound(vntS), 1 To 1) As Date

    For i = 1 To UBound(vntS)
        vntT(i, 1) = DateSerial( _
                Right(vntS(i, 1), 4), _
                Mid(vntS(i, 1), 4, 2), _
                Left(vntS(i, 1), 2))
    Next

    With Worksheets(cStrSheet).Range(cStrCell)
        .Resize(UBound(vntT), UBound(vntT, 2)) = vntT
    End With

End Sub

Override reformatting of cell excel VBA


Equivalence of intervals with octaves between them

Question: Say we play C4 and G4 on the piano at the same time, stop the notes, then play D4 and A4 simultaneously, then the quality of this sound is the same as the quality of the first.
To understand why that was the case, I read about just intonation and equal temperament.
Physically, we are generating waves that travel through the air, so to simplify things I went to a program called desmos where you can simulate waves.
I constructed an analogous situation there by first pretending that a note that has frequency equal to 2pi (the default period of a sine wave) was a note in the equal temperament system.
Next to produce a note which is a perfect 5th above that note, we must multiply the original frequency by 2^(7/12), this is equivalent to going up seven semitones, which is the definition of a perfect 5th.
Then, as the piano uses hammers which vibrate strings and then as the pressure waves add together in the air before reaching our ears, I will take the summation of the original sine wave and the second sine wave that has a frequency which is 2^(7/12) times the original waves frequency, this is what f1(x) + g1(x) represents on desmos.
Next to represent the same situation, but with both tones raised by two semitones I conduct the same experiment but with f1(2^(2/12)*x) + g1(2^(2/12)*x) (in desmos I make two new functions and give it an offset so you can see it lower down). Visually we can see that the wave generated by this sum is identical to the first, but with a scaling in the x direction.
Mathematically, we can see that the new wave just has a period which is 1/(2^2/12) times the original period. Because the period is shorter, this corresponds to a higher frequency, and pitch, so playing these two notes together should indeed have the exact same quality but just higher.
After doing this, I wondered why when voicing chords on piano we are usually allowed to move notes by octaves so that the voicing is more clear without actually changing the chord.
To do this, let's consider a similar situation to the first thing we did. Say we are playing C4 and G4, then based on what I learned, playing C4 and G5 should also produce a wave with the same quality.
Experimentally we would be comparing the wave generated by f(x) + g(x), and then f(x) + g(2x), as this represents a shifting by one octave up.
After doing that, the waves that were generated by both the above summations had totally different qualities:

Can someone explain why C4 and G4 played simultaneously and C4 played with G5 should both have similar qualities?
Comment: The term 'quality' concerns me. It's hardly an objective term, and could be subject to  many different connotations.
Comment: @ElementsinSpace, yup - I fixed the typo. The second wave can be seen with as many cycles as needed by following the link - https://www.desmos.com/calculator/werca8k9vm
Comment: Right - In my writing when I talk about quality, I mean the shape of the wave produced. I said that the last two had different qualities because you cannot scale them along the x axis to produce the other. I'm just attempting to grapple with why we can move these intervals by octaves and still have it represent the same chord.
Comment: It'd be better if you could see at least two cycles/periods of the second wave too.
Comment: @cuppajoeman ah yeas, I should have just click on the links in the question. thank you
Comment: Possibly related question: https://music.stackexchange.com/questions/44783/why-do-octaves-sound-equivalent
Answer: I think your confusion comes from the fact that you're generating sine waves for comparison.
Sine waves are great for understanding constructive and destructive interference, but they're a pretty far cry from what a piano generates.
On any "real world" instrument the sound wave produced is composed of both the fundamental pitch and all of the overtones.  It's the variation of overtone distribution (the relative intensity of each overtone in relation to the fundamental) that creates timbre.
When you play C4 on the piano, the piano is producing a mix of C4, C5, G5, C6, E6, G6, Bb6, C8... the pitches produced aren't an exact match for the 12TET tuning we use, so the overtones from E6 on are "out of tune" a bit, but the overtones are also getting weaker as they go up.
Since the actual wave for C4 includes C5 and G5, components of the wave will line up nicely with D4 and A4 - they will differ only by the intensity of their distribution.  In other words, the peaks and troughs will be in exactly the same relative positions, but the amplitudes will vary a little bit.
EDIT: some illustrations might help.  Here's a perfect fifth with only fundamentals .
Here's a "real world" instrument with a fundamental and three overtones.  Each overtone is 50% of the intensity of the prior one.
And here's that "real world" instrument juxtaposed with a fundamental a 12th higher  - the fifth in the next octave - with no overtones.
These are all still simpler than what happens with real instruments, but you can see how the peaks and troughs coincide.
Comment: this answer implies that the answer to OP's question, "why when voicing chords on piano we are usually allowed to move notes by octaves so that the voicing is more clear without actually changing the chord", is that these loose voicings are a consequence of the harmonics of real-world instruments, and do not work with pure sine waves. this implication is entirely false.
Comment: Ahh, this really helps, I just made a new desmos experiment where you can compare the sum of the two with overtones and without. The setup is the sum of a note, and a note k semitones higher. Red is fundamentals only, black with .5 opacity is with 3 overtones. Orange is the sum of a note and a note k + 12 semitones higher with the same 3 overtones. I overlayed them on top of each other - and you can see that they match up quite decently. (https://www.desmos.com/calculator/qqrpbgdmi1 - change k to see different waves).
Comment: After all of that I still have one question though, would this mean that if you had some sort of keyboard which just produced pure sine waves and you listened to it through headphones that playing a perfect 5th, and then playing a perfect 5th with an extra octave between them that the waves would look like the image in the bottom of my first post, and then since there are no overtones it wouldn't still have the characteristics of the perfect 5th? Would that mean that electronic instruments have add the overtones in synthetically to make it sound right?
Comment: You can set up tone generators to produce pure sine waves.  But most electronic instruments do in fact add overtones, because pure sine waves aren't terribly useful for making music.  Juxtaposing two sine waves should look like your image.  What it would sound like is a different can of worms, because we'd be edging into psychoacoustics.
Comment: I see. Finally on an electric guitar how are the fundamentals included there? I know that the signal is an analog of the string vibrating, but I thought that the harmonics come from the body of the instrument vibrating, are harmonics also created by the strings themselves?
Comment: @cuppajoeman - the harmonics come from the string.  A vibrating string has the "wave" of the vibration moving both directions from the point where it's plucked, and after reflecting off the nut/saddle it interferes with itself.  That's a bit of s simplification, but the harmonics aren't produced by the body.
Comment: @Esther - you're reading something into this that isn't there.  The OP didn't ask about piano chord voicings, and I didn't address them.  The question is about acoustics, and specifically about why a 12th and a 5th interact differently.  The answer is that it's true for sine waves, but far less so for any instrument, because they also produce overtones.
Comment: I directly quoted the relevant part of the question.
Comment: @Esther - if you clicked through the link in his sentence "Let's consider a similar situation" you would see that the question asked, which followed that statement, is about the interaction of pure sine waves in 12TET, not about piano voicings.  I addressed the question he actually asked rather than what you perceived to be the relevant part.
Answer: The idea that you can play a note in a different octave, and it will basically be the same note and not change the harmony, is called "octave equivalence". Note that it is not called "octave equality". When people say that you can change the voicing of a chord by moving notes up or down by an octave, they are not claiming that you will get the exact same sound, only that the basic harmony won't change. (And even then, if you change which note is the bass note or the top note, i.e. if the different chord voicing is a different chord inversion, it may very well change your perception of the harmony.)
Comment: I don't think the choice of terminology of "octave equivalence" is that important.  (After all, equality is an equivalence relation?)
Comment: @Edward maybe the wording wasn't actually chosen so carefully when the term was invented, but it does make sense. Equality isn't merely _an_ equivalance relation, it is the equivalence relation to rule all equivalence relations. (a=b ⇒ a~b). But most equivalances are rather "shared trait" relations, and this is indeed the case for octave equivalence.
Answer: The answer about octave equivalence is essentially correct, but to take that answer a step further: the way we perceive notes is weird and doesn't accurately reflect the "underlying physical reality" of sound waves (e.g., timpani are pitched but drum kits aren't, even though toms clearly have a fundamental frequency like a timpani; and in fact, we sometimes do hear drum kits as pitched, just, only when context encourages us to); and music theory works with a set of arbitrary categorizations on top of this subjective perception. That is to say, wave diagrams won't provide any real insight into questions about interval equivalence.
The most "scientific" answer you will get to "why is a perfect 12th, harmonically, the same as a perfect 5th" is "octave equivalence"; but empiricism struggles here because:
(a) our concept of "sameness" here is arbitrarily defined, they're "the same" because, idk, it doesn't seem to affect people's enjoyment of music when we treat them as being the same, and
(b) "perfect 5th" can refer to a much wider variety of intervals than you might expect, there's no precise mathematical definition of "perfect 5th" that actually covers the wide variety of sounds considered to be "perfect 5ths" in real-world music.
Comment: The waves would look nearly the same if we use perfect fifths in a "perfect" Pythagorean 3:2 ratio instead of the 12TET ratio in the OP, right? I don't think your statement that "there's no precise mathematical definition of 'perfect 5th' that actually covers the wide variety of sounds considered to be 'perfect 5ths' in real-world music" actually matters here.
Comment: @Dekkadeci Yes, but I think OP's right to use the ratios we actually play in music rather than some approximation that happens to be historically relevant. That is, assuming they're actually asking about music at all, a surprisingly controversial position judging by the top answer's popularity.
Comment: At least if barbershop quartets are any indication (those use just intonation for those famous barbershop 7th chords), I strongly suspect that we sing 3:2 ratios for perfect 5ths, and it's the 12TET ratio that is the approximation.
Comment: @Dekkadeci The point is that OP's noticed that in a great deal of real-world music (sure, not all of it, barbershop quartet and string quartet being notable exceptions), the sound waves that correspond to a perfect 12th will look very different to the sound waves that correspond to a perfect 5th. Their question -- as far as I can tell -- is why we hear them as equivalent despite this discrepancy. The fact that intervals can't be reduced to a single definitive/canonical waveform seems relevant in this context.


Updating tkinter label from module, what to search to learn how to do it

Question: A quick description to make clear what I am trying to ask as I may not be using the correct terminology.
I have made a basic gui that:
(1). gives an options menu (2). Has button that uses the options menu choice to call a module that performs a calculation that outputs a variable from the module onto the console. (3). Has a label that updates after pressing the button
However;
I would like to have a label update with a variable created from the module (rather than go to the console).
I have tried to use 'getattr' without success.
Project background - I am at the start of trying to learn my first language, I have tried and failed before, so this time I am trying to learn by creating my own project. The project is a bolted joint calculator; pick your bolt diameter from a drop-down menu, hit a button and then it will display the area as a label.
The Question: How do I call a variable that is calculated in a module?
import tkinter as tk
from tkinter import *
import pandas as pd
import boltMod2

def show(whatever):
   choice = variable.get()

def temp():
    temps = boltMod2.calcSize(variable.get())
    lab.config(text = "Area is " + variable.get())# i would like to read 'minA' variable from boltMod.calcsize instead

window =Tk()
window.geometry("300x200")

#oprtions for Dropdown menu
sizes = ['M6', 'M8', 'M10']
choice = sizes[0]
variable = StringVar()
variable.set(sizes[0])

#dropdown menu
popupMenu1 = OptionMenu(window,
                           variable,
                           *sizes,
                           command = show)
popupMenu1.grid(column=0, row=1)

#button
myButton = Button(window,
                  text ="Calculate",
                  command = temp)
myButton.grid(column=1, row=2)

lab = Label(window,
            text = "select bolt ")
lab.grid(column=0, row = 3)

window.mainloop()

then the module "boltMod" is:
def calcSize(metricsize):
    print(metricsize + " is your bolt size")
    minA= 3.142*(8/2)**2 #normally values read off csv files for the
selected bolt
    print("The area is ")
    print(minA)

Comment: Please create a [mre] for us. Your brief explanation gives an idea of what you have tried but for a solution/change in code, we need the basis to do this. Otherwise I suggest to research `tk.StringVar` and the option `tk.Label(.., textvariable=`
Comment: great suggestion, i have uploaded a simplified version of the code. The reason i am trying to use a module 'boltMod' is I intend to add many functions to the program, eventually I want it to be a bolter joint calculator. I will read up on getting a better understanding of StringVar. thanks again
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: what do you mean by calculated in a module? can you include your code?
here is some code that seems to do what you are saying (formula is just ^2 instead of whatever you are actually doing):
from tkinter import *
from tkinter import ttk

root = Tk() #create root GUI
root.title("Name") #Change window title
root.geometry('800x500') #Change window size

def ButtonClick(id, output):
    if id == "o1": #if opt 1
        output.config(text="output: {}".format(1**2)) #1^2
    elif id == "o2":
        output.config(text="output: {}".format(2**2))
    else:
        output.config(text="output: {}".format(3**2))

#Main Frame---------------------------------------------------------------------
frm = ttk.Frame(root, padding=225) #Create frame
frm.grid(row=0,column=0) #grid the frame
#Prompt-------------------------------
global output
output = ttk.Label(frm, text="output: ") #show prompt
output.grid(column=0, row=0)
#Buttons------------------------------
#opt1
o1 = ttk.Button(frm, text="Option 1") #add EOL directory button
o1.grid(row=1, column=0) #grid the button
o1.config(command=lambda output=output: ButtonClick("o1", output)) #reference button press function
#opt2
o2 = ttk.Button(frm, text="Option 2") #add EOL directory button
o2.grid(row=2, column=0) #grid the button
o2.config(command=lambda output=output: ButtonClick("o2", output)) #reference button press function
#opt3
o3 = ttk.Button(frm, text="Option 3") #add EOL directory button
o3.grid(row=3, column=0) #grid the button
o3.config(command=lambda output=output: ButtonClick("o3", output)) #reference button press function

root.mainloop() #execute

Also, you don't need the "output" to be an input to the ButtonClick() function it depends on the program's needs.
Comment: thank you for your response, i need a bit more time to go over your code, there is a lot of parts I have not come across before (config, lamda etc), I will look into them and try to get a better understanding. Thank you for your help.


Finalizar processo e abrir novamente por .bat

Question: Meu problema atualmente é o seguinte, tenho um executável que tem a função de controle de acesso de funcionários, porem devido a algum problema nesse processo ele costuma parar de responder, com isso crei um bat para finalizar o processo, porem, é necessário clicar no bat esperar ele concluir e após isso abri novamente o executável de controle.
Queria uma ideia de como criar um bat que finalize o processo e após isso abra novamente o executável, isso é possível?
.bat:
taskkill /f /im ACCA.exe

Caminho do executável:
c:\exe\ACCA.exe

Desde já agradeço toda e qualquer ajuda,
Comment: Se você colocar um abaixo do outro no mesmo bat não funciona?
Comment: @WictorChaves já tentei ele simplesmente não abre, parece que ele só executa a primeira linha.
Comment: Se você precisa reiniciá-lo provavelmente ele está não está responsivo... depois do kill, quanto tempo ele demora para morrer?
Comment: @Bulfaitelo estou te aguardando no chat...
Answer: Você já colocou o comando necessário para finalizar o programa, que é o taskkill, agora só falta por um start antes do caminho do arquivo para inicializa-lo novamente.
Seu batch ficaria assim:
taskkill /f /im ACCA.exe
start c:\exe\ACCA.exe

Se quiser que ele espere alguns segundos antes de iniciar o programa você pode colocar o comando timeout /t 10 (para esperar 10 segundos), nesse caso o batch ficaria assim:
taskkill /f /im ACCA.exe
timeout /t 10
start c:\exe\ACCA.exe

Salva isso como [nomedoarquivo].bat e coloca numa tarefa agendada no Windows.
Comment: Laércio obrigado pela resposta, mas está caindo no mesmo problema na hora de iniciar o executável.
Comment: Quando o caminho tem espaços deve coloca-lo entre aspas, exemplo: `start "C:\ASC Solutions\ACCA\ACCA.exe"`
Comment: acabei movendo para um diretório sem espaços: https://i.stack.imgur.com/Hk41r.png
Comment: Você consegue ver o erro que dá? Coloque o comando `pause` no final do arquivo para ver qual o erro, o bat está salvo no C: se não estiver tem que colocar `C:` no início do `batch`.
Comment: chamei o bat pelo terminal ele simplesmente não da erro porem não inicia https://i.stack.imgur.com/2wca8.png
Comment: Veja no gerenciador de tarefas se ele está aberto.
Answer: Execute o seguinte código bat:
taskkill /F /IM ACCA.exe
ping 127.0.0.1 -n 10
start c:\exe\ACCA.exe

O ping serve como um sleep( ̶n̶ã̶o̶  encontrei a função de sleep no bat) para alguns casos de aplicações que são pesadas e precisam de um certo tempo para finalizar todos os seus serviços, o parâmetro -n 10 indica que o sistema deve aplicar o ping no ip(você pode usar outro ip) uma quantidade de 10 vezes antes de abrir o executável novamente.
@Editada
Utilizei a o comando timeout /t 10 citado na resposta editada do Laércio para substituir o comando ping(usado apenas para a espera da finalização total da aplicação desejada) e funcionou, você pode substituir a linha ping 127.0.0.1 -n 10 pelo comando timeout /t 10 caso você queira esperar 10segundos(além de que você pode encerrar a espera pressionando em qualquer tecla), tempo rasoável ao meu ver para finalizar qualquer aplicação. Recomendo utilizar o timeout, uma vez que o ping não foi feito de fato para pausar a execução. Fica ao seu critério utilizar o ping ou o timeout.
Nota: Não sei por qual motivo, mas ao conversar com o Bulfaitelo no Chat, vimos que ao criar um Atalho do executável c:\ACCA\ACCA.exe e adicionar o caminho desse atalho ao comando start, o comando funcionou como esperado.
Comment: usando esse bat, ele executa a primeira linha porem na segunda ele da erro e na terceira ele não encontra o arquivo veja a tela de erro: https://i.stack.imgur.com/n58CB.png
Comment: Retira o  `*` , coloquei apenas para sinalizar e explicar no texto. vou editar a pergunta.
Comment: testei ele finaliza faz o ping porem o star não inicia o aplicativo, percebi que o erro de não encontrar é por conta do espaçamento do diretório, parece que chamando por `start C:\acca...` ele não inicia o executável https://i.stack.imgur.com/kD5l9.png
Comment: No seu diretório `C:\ACCA` existe de fato um executável chamado `ACCA.exe` ?   Porque, pelo que entendi em sua pergunta, esse executável está no seguinte diretório: `c:\exe\ACCA.exe`
Comment: Certamente é nesse ponto que ele não funciona criei um `bat` só com o `c:\ACCA\ACCA.exe`ele simplesmente não iniciar o executável, se eu for no atalho não é passado nenhum parâmetro a mais, e se for diretamente no executável e clicar ele inicia normalmente
Comment: Verifique se seu executável realmente está no diretório `c:\acca` ou `c:\exe`.
Comment: Sim está https://i.stack.imgur.com/Hk41r.png
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/89328/discussion-between-bulfaitelo-and-andre-filipe).
Comment: Se está no `C:\ACCA`, irei editar sua pergunta. Favor aceitá-la.
Answer: Essa linha start não funciona no Windows. O que poderia fazer é o comando C:\caminho como no executar ai vai porém nessa batch não funcionaria o kill teria que fechar o programa manualmente para inicial a contagem regressiva da linha timeout
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Como fazer video 360º

Question: Alguém tem alguma ideia de como posso fazer um video panoramico que gira 360 graus? Onde clica e navega pelo video 360 graus
Comment: emersonnw, bem-vindo ao [pt.so]! Sua pergunta foi fechada porque vários usuários consideraram-na [vaga](http://pt.stackoverflow.com/help/closed-questions). Isso significa que não é possível responder objetivamente. No entanto você pode editá-la de acordo com o formato do site, por exemplo, especificando melhor o que quer e focando em uma dúvida técnica ao invés de simplesmente pedir tudo pronto. Sugiro que leia sobre [como fazer uma boa pergunta](http://pt.stackoverflow.com/help/how-to-ask). Fique à vontade também para fazer outras perguntas, apenas procure seguir o formato do site. Abraço!
Answer: Tente o Valiant 360º.
Está disponivel no GitHub.
https://github.com/flimshaw/Valiant360
Comment: Fantástica biblioteca, nota mil, valeu!

Como fazer video 360º


In a statitical experiment involving independent coin tosses, what is the number of heads required to get $m$ tails?

Question: I know that the solution is a negative binomial distribution. However, I was a looking for a proof for the same along the following lines. If the number of coin tosses is fixed to be $n$, then the distribution of number of heads follows a binomial distribution, that is
\begin{equation}
P(N_h = n_h) = \frac{n!}{n_h!(n-n_h)!} p^{n_h}(1-p)^{n-n_h}\:,
\end{equation}
where $p$ is the probability of observing a head.
Hence, if we condition on the number of tails observed $m$, we should be able to get the desired distribution. Hence,
\begin{align*}
P(N_h = n_h| N_t = m) &= \frac{P(N_h = n_h, N_t = m)}{P(N_t = m)} \\
                      &= 1{\{n_h+m =n\}}
\end{align*}
I know that this is the wrong way to this problem. I was wondering about how to proceed correctly.
Answer: Assume that we have observed $m$ tails. The last coin toss must have given us a tail - otherwise we would have stopped earlier. We can now count in how many ways this can occur with $n_h$ heads. Thus, we have $n_h + m$ tosses, and the last one is fixed (tail). We then have to place $m - 1$ tails in $n_h + m - 1$ places. We can do this in
\begin{equation}
k_{n_h}  =\pmatrix{n_h + m - 1 \\ m - 1}
\end{equation}
ways, using binomial coefficients. Each of them have equal probability, namely $p^{n_h}(1-p)^m$, using the independence of the tosses. Each of the $k_{n_h}$ different ways are obviously disjoint events, and therefore we can get the desired probability simply by summing their respective probabilities. All in all,
\begin{equation}
P(N_h =  n_h | N_t = m) = \pmatrix{n_h + m - 1 \\ m - 1} \cdot p^{n_h}(1-p)^m,\ n_h \in \mathbb{N}_0,\ m \in \mathbb{N}.
\end{equation}
This is exactly the negative binomial distribution with parameters $m$ and $p$.
Answer: I'm not quite sure of understanding the question but I'll give it a try.
In order to get $m$ tails you need to get $n-m$ heads, if you calculate $P(N_h = n-m)$ you will get the probability of getting $n-m$ heads and $m$ tails.


sklearn logistic regression converging to unexpected coefficient for a simple case

Question: The case is as follows:
Suppose that
import numpy as np

X = np.array([1, 1, 1])
y = np.array([1, 0, 1])

Then I perform a logistic regression with no intercept to check out the fitted coefficient:
from sklearn.linear_model import LogisticRegression

def fit_predict(X, y, fit_intercept=True):
  model = LogisticRegression(fit_intercept=fit_intercept)
  model.fit(X.reshape(-1, 1), y)
  print(f'model coefficients: {model.coef_}')

fit_predict(X, y, fit_intercept=False)

# output: [[0.2865409]]

I am pretty confused by this output. According to my algebra (directly solving the optimization constraint), the coefficient should be $logit(2/3) \approx 0.6931471805599452$.
Is this because my math is wrong, or because something else is going on that I don't know about?
The algebra is as follows, starting with the following equation:
$$ \sum_i y_i \cdot x_i - sigmoid(x_i) \cdot x_i = 0$$
If we plug the values in, then $$2 = 3\cdot sigmoid(1)$$.
I conclude that $\beta = logit(2/3)$.
Thanks in advance.
Comment: Sklearn applies a penalty by default. I would see that penalty to 0 and recheck your estimates prior to continuing.
Comment: @Syllabear You can write an answer explaining how Demetri's hint helped you answer the question.
Comment: That worked! Thanks :-)
Answer: As Demetri suggested, we need to add penalty='none' for the code to give expected results.
The revised code is as follows:
from sklearn.linear_model import LogisticRegression

def fit_predict(X, y, fit_intercept=True):
  model = LogisticRegression(fit_intercept=fit_intercept, penalty='none')
  model.fit(X.reshape(-1, 1), y)
  print(f'model coefficients: {model.coef_}')

Comment: Weird API that they went with the string `none`.
Comment: @MatthewDrury That is not the only weird thing.  The penalty parameter (they call it `C`) is the inverse of the regularization strength so $C = 1/\lambda$.  I imagine they did this to make grid searches for the optimal strength a little less cumbersome.
Answer: I will add my own answer to this question in order to shine some light on why a penalty is added by default. I'm also posting for posterity as you are not the first person to get caught by this and you won't be the last.
Back in 2019, Zachary Lipton discovered sklearn applies the penalty by default too and this sparked a very intense debate on twitter and elsewhere.  The long and the short of that discussion is that sklearn sees itself as a machine learning library first which in their eyes means that they favor other things over unbiasedness and estimates of effects.  The most striking example of their philosophy (in my opinion) comes when Andreas Mueller plainly asks why someone would want an unbiased implementation of logistic regression.  Inference simply isn't on their radar.
Hence, LogisticRegression is not the de jure Logistic Regression.  It is a penalized variant thereof by default (and the default penalty doesn't even make any sense). There is another sharp point.  Had you learned about penalized logistic regression a la ridge regression or the LASSO, you would be surprised to learn sklearn parameterizes the penalty parameter as the inverse of the regularization strength.  Hence setting $\lambda=2$ in LASSO or Ridge would correspond to C=0.5 in LogisticRegression.
Let me sum up by making this completely unambiguous.
If you are intent on estimating the effects of some covariates on a binary outcome, and you insist on using python Do Not Use Sklearn.  Use Statsmodels.
If however, you insist on using sklearn, remember that you need to set penalty='none' in the model instantiation step.  Else, your estimates will be biased towards the null (by design).
Comment: @user257566 Its been a while since I've taken a math stats course, but if I remember correctly the MLE may be biased but it is consistent (meaning as $n\to \infty$ we can estimate the parameter to arbitrary precision).
Comment: Their preference for unbiased results here also uses the ML definition for 'bias'. That is different from the definition of 'bias' in (at least social science) statistical training. Hilariously this means that, under the typical (ss?) stats definition, the result is biased towards 0.
Comment: You're right, thanks for the correction. Sloppy reading on my part. Got burnt once too often on that misunderstanding and turned into a raw nerve.
Comment: Hi, is the MLE in logistic regression unbiased? Or is the asymptotic distribution just centered at the true coefficients?
Comment: `sklearn` and `statsmodel` are not the only implementations and for instance it's easy to get more flexibility by implementing your own generative model [in `pytorch` for instance](https://laurentperrinet.github.io/sciblog/posts/2020-04-08-fitting-a-psychometric-curve-using-pytorch.html)


How To Display Image instead of Taxonomy name using Views to display my nodes?

Question: I Have Entity Module and already have a Taxonomy Vocabulary with terms and an Image Field created. Each term has a unique image.
I Have a Content Type with a Term Reference field set to allow multiple selections of my Vocabulary.
I now want to have my Nodes displayed in a Views Table, Title, Node Image, and Taxonomy terms as images rather than their names.
How do I make this possible? Here is a link to what the site currently is (HTML Table rather than a view - very limiting and slow for updating). http://dev.destinationsound.net/
The different color circles are what will be taxonomy terms.
Drupal 7
Note: This is not for a taxonomy term page but rather a list of nodes that have taxonomy terms associated with them.
Answer:
Create a view of the appropriate nodes
Set the view output type to be "table"
Create a "relationship" in the view between node and taxonomy term
Now you can add the image field from the term to your views output
If you use multiple vocabularies, add a filter to select just the vocabulary you are interested in.

If you don't already have the imagecache module installed, I recommend it as it will let you control the size of the displayed image.
Comment: Thanks. I tried adding a relationship and what it did, since one node has multiple terms, it displays the node multiple times, once for each term it has. I chose "Content: Taxonomy terms on node", selected required and selected the vocabulary I want associated.
Comment: Its not an issue of multiple vocabularies, rather multiple terms within my vocabulary. Each Node has up to 6 terms that can be simultaniously selected. This is resulting in repeated entries of the same node, one for each node. In my example I have 2 test nodes. The view outputs 3 of each node (6 total) because each node has 3 terms selected. I want one listing for each node but with their multiple terms showing.
Comment: You can solve this in 1 of two ways:

- Select the "unique" setting in the view
- Enable the "aggregation" feature
Comment: Better answer: You can solve this by enabling the "aggregation" feature, and then choose an aggregation method for your taxonomy field, e.g. "group results together".
Comment: Almost there. It now only shows 2 nodes, but now only one of the term images is showing. There should be all three
Comment: Probably you just need to pick a different aggregation method.


Drawing a shape with an undefined size

Question: I have been looking at the Java2D tutorials and was wondering how to draw a shape using the mouse to define its size(i.e the size of the shape is not fixed). I haven't come across a tutorial specifically for this and was wondering how I could implement this for a rectangle for example.
Comment: Did you try http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseMotionListener.html?
Answer: Basically, the size is FIXED at every moment. When you add a MouseMotionListener, before the next event is captured, you can paint the shape on the screen with the size depending on current MouseEvent.getPoint() which tells you the coordinates of your mouse location.
Override the paintComponent(Graphics g) method of the component. and call repaint() method after each update of the mouse location and the size of the shape:
class YourPanel extends JPanel extends MouseMotionListener, MouseListener {

    private Rectangle rect = new Rectangle();

    public YourPanel () {
        addMouseListener(this);
        addMouseMotionListener(this);
    }

    @Override
    public void paintComponent (Graphics g) {
        super.paintComponent(g);
        g.draw(rect);
    }

    @Override
    public void mouseDragged (MouseEvent me) {
        rect.setSize(me.getX() - rect.x, me.getY() - rect.y);
        repaint();
    }

    @Override
    public void mousePressed (MouseEvent me) {
        rect.setLocation(me.getX(), me.getY());
        repaint();
    }

    // Other methods...

}

Answer: Shapes is a word and java class  that represents differnet geometric figures like rectangles, ellipses, poly lines, etc.
So first the user would have to decide which shape, e.g a poly line.
You then would catch mouse left click events, and for each click read the mouse coordinates and add that coordinate pair (e.g java.awt.geom.Point2D()) to an ArrayList<Point2D>.
The size of such an list is (practically) unbounded. On each click you will create a current shaped object that will be drawn. Once the user clicks right mouse, the shape is ready und you store it in list of shapes.
Answer: You should have your class implement a mouse listener, then save the variables of the mouse listener with getX and getY to draw the shape.

Drawing a shape with an undefined size


navbar in R flexdashboard cuts off main content

Question: I'm working on a flexdashboard with lots of pages, and on small screens, the navbar takes up two lines and cuts off the top of the main content.
Here's a sample dashboard with several navbar items:
<code>---
title: "Example long title"
output:
  flexdashboard::flex_dashboard
---

Home Page {data-icon="fa-home"}
=====================================

Some sample text that will get cut off

Example Page Title 2
=====================================

Example Page Title 3
=====================================

Example Page Title 4
=====================================

Example Page Title 5
=====================================

Example Page Title 6
=====================================

Example Page Title 7
=====================================
</code>
After I knit the document, the result looks fine on a large screen:

But when I shrink the window, the navbar turns into two lines and the top of the main content gets cut off:

Is there a way to prevent the top of the main content from getting covered up, without removing items from the navbar?
Thanks
Comment: Does this answer your question? [Prevent navigation bar from overlapping content in flexdashboard R](https://stackoverflow.com/questions/42914936/prevent-navigation-bar-from-overlapping-content-in-flexdashboard-r)
Comment: Have you tried using media queries to add more padding on the top of the body at the size where the navbar turns in to two lines? (I'm assuming you are using a fixed position on the navbar?)
Answer: You could try turning the flexdashboard navbar into the side bar. With inline CSS code. Using this Stackoverflow question

<code>---
title: "Example long title"
output:
  flexdashboard::flex_dashboard
---

Home Page {data-icon="fa-home"}
=====================================

Some sample text that will get cut off

Example Page Title 2
=====================================

Example Page Title 3
=====================================

Example Page Title 4
=====================================

Example Page Title 5
=====================================

Example Page Title 6
=====================================

Example Page Title 7
=====================================

<style>
.navbar {
margin: 0;
padding: 0;
height: 100%;
display: block;
position: fixed;
width: 200px; /* Modify the width of the     sidebar */
}
body {
margin-left: 200px; /* Add a left margin to     avoid content overlay */
padding-top:0px
}
</style>
</code>


Is (0,0) a minimum or saddle point of $f(x,y)=2x^4+y^2−3yx^2$?

Question: I saw that $f(x,y)=2x^4+y^2−3yx^2$ has a critical point at $(0,0)$ calculating the gradient of the function and equalizing to (0,0). if I study the behavior of the function at an environment of $(0,0)$ reducing the problem to a single-variable function using straights with the form $y=ax$ I have $f(x,ax)=2x^2+x^2a^2-3ax^3$ then $f'(0,0)=0$ and $f''(0,0)=4+2a^2>0$ so along any straight line that passes through the origin, f
has a minimum at $(0,0)$
But if I study too the behavior of the function at an environment of $(0,0)$ reducing the problem to a single-variable function using parabolas with the form $y=ax^2$ namely: $f(x,ax^2)=2x^4+a^2x^4-3ax^4=x^~(2-3a+a^2)$ then, $f'(x,ax^2)=4x^3(2-3a+a^2)$ and $f'(0,0)=0$. Then, $f''(x,ax^2)=12x^2(2-3a+a^2)$ so $f''(0,0)=0$ given that $x^2>0$ for all $x$ pertaining to real numbers, $x≠0$ then:
$i)$ if $a=-1, f''(x,-x^2)>0$
$ii)$ if $a=3/2, f''(x,3x^2/2)<0$
so by $i)$ and $ii)$ $(0,0)$ is a saddle point
So I don't know if $(0,0)$ is a minimum or saddle point.
Comment: $f$ does not have all even exponents as there is $y^1$ in the term $-3yx^2$
Comment: thanks, I corrected that with another analysis
Comment: @Ayesca No problem. Good intuition, btw
Comment: ($f''(0,0) = 2a^2$)
Answer: [Answering the edited post]
Your analysis with the parabolas show correctly that $(0,0)$ is a saddle point.
Your situation shows precisely what we must be wary of when considering limits and local behaviour in more dimensions. Even if the point is a minimum along any straight line going through it, it can still be a saddle point, since we must consider all curves going trough the point. This is a very important thing to remember.
EDIT/NOTE:
Usually, we would try to use the second partial derivative test (Hessian matrix) to determine the type of critical point. In this case, the test is inconclusive, so we have to get creative.
Comment: Thank you very much for the answer and the comment! Do you have any tools, methods or recommendations about these situations where the Hessian matrix is not decisive?(In case I find myself facing an exercise in which creativity doesn't arouse me in principle)
Comment: I'm not really the best one to ask... But always plot the function if you can. In this case we could the see a parabola shape to give us the right idea. Otherwise do something like what user did, i.e. rewrite the function so you can clearly see the right answer. Completing the square is useful in polynomials.
Answer: We have that
$$f(x,y)=2x^4+y^2−3yx^2=-\frac14x^4+\left(y-\frac32x^2\right)^2$$
therefore it is a saddle point indeed for $x\neq 0$ we have

for $y=0\implies f(x,y)>0$
for $y=\frac32x^2\implies f(x,y)<0$

There are not general methods when hessian matrix test fails. Excluding numerical methods, by hands the best we can do is to try some good manipulation in order to determine the sign of the function near the point of interest.


Find $a_{0}, a_{1}, a_{2}, a_{3} \in \mathbb C$ for which $f^{*}=a_{0}p_{0}^{*}+ a_{1}p_{1}^{*}+a_{2}p_{2}^{*}+ a_{3}p_{3}^{*}$

Question:
In the linear space $\mathbb C[x]_{3}$ is a basis: $p_{0}(x)=1$, $p_{1}(x)=x$, $p_{2}(x)=x(x-i)$, $p_{3}(x)=x(x-i)(x-1)$. $(p_{0}^{*}, p_{1}^{*}, p_{2}^{*}, p_{3}^{*})$ is a basis of space $(\mathbb C[x]_{3})^{*}$ which is dual for a basis $(p_{0}, p_{1}, p_{2}, p_{3})$. Functional $f^{*} \in (\mathbb C[x]_{3})^{*}$ is such that $f^{*}(p)=p(-i)$. Find $a_{0}, a_{1}, a_{2}, a_{3} \in \mathbb C$ for which $f^{*}=a_{0}p_{0}^{*}+ a_{1}p_{1}^{*}+a_{2}p_{2}^{*}+ a_{3}p_{3}^{*}$.

Can you get me some tips to this question? I never had similar task and I do not even know what to look for to start this task. I'm weak from line functionalities and it's too hard for me.
Answer: Note that by the definition of the dual basis,
$$p_j^*(p_i) = \begin{cases}0 & i \ne j\\1 & i = j\end{cases}$$
So if $$f^* = a_0p_0^* + a_1p_1^* + a_2p_2^* + a_3p_3^*$$ then
$$f^*(p_i) = a_i$$
for all $i$
And since $f^*(P) = P(-i)$ for any polynomial $P$, you can calculate $f^*(p_i)$ easily.


Techniques to Improve Vocal Volume?

Question: I am a singer who typically does acoustic guitar type performance, but I've been playing with full 'rock' bands for a little while now and am having a terrible time of getting 'loud' enough to cut over the ruckus. I can hang tight, but I'd like to be louder.
Can anyone make some recommendations for how I can a. improve my own ability to reach sustainable volume and b. equipment that can help give me a boost
I have upgraded to a higher quality mic, do know that I have to basically make mouth-love to it (in terms of being super close) when I sing -- but I'm still struggling...
Answer: If you've got a microphone, you shouldn't be getting volume from your vocal chords - if you want louder, turn up the amplifier. Consider that the electric guitarist who's drowning you out is making an incredibly quiet sound, until his amp gets hold of it.
If your amplifier doesn't go loud enough, then either you need a more powerful PA, or everyone else needs to go quieter. When inexperienced people play in a rock configuration, there's often a tendency for "everything louder than everything else" - and often turning other things down is the answer (but it's difficult to convince everyone of this).
Make sure your microphone is one designed for live vocals. Typically that means a dynamic mic with a cardioid sensitivity pattern. That means that if you point it at your mouth, it will pick up your voice and not too much of the rest of the on-stage sound. This is a different set of requirements from a studio vocal mic, where normally other sounds are suppressed using other methods.
You shouldn't need to go super-close to the microphone. With a typical dynamic microphone, going closer will result in a more "boomy" sound. You can use that to artistic effect; many singers have a "voice" achieved by practically whispering into a very close mic - then as their voice gets louder, they back away from the microphone to get a more natural tone. The audience might perceive that as going from quiet to loud - but in fact the actual loudness if you measured it, is the same throughout.
It may not be that you're too quiet - it may be that there's not space for your voice in the arrangement. If your voice is occupying the same frequencies as the guitar part, then one will get lost in the other. For parts to stand out, they need to occupy their own slice of the frequency spectrum.
Comment: Slim, Thanks for your response. I think the problem is one that many women face because our frequency of vocals is one that get drowned out very often. The problem with turning myself up is that  you can't do much to turn down the drums.. and feedback! we're often crammed into tiny areas so monitors are always on the brink of feeding back. It sounds like, from what you're saying, that I need to understand the PA and how it's set up a lot better and not leave that in the hands of a guitar player!       That's very interesting about the guitar and vocals occupying the same frequency spectrum!
Comment: @Meeka, when you're crammed into a tight space, do you *need* the monitors?  Can you see and hear each other well enough without them, thus eliminating the feedback problem?
Answer: Alright - I just got back from a class on this in Boston and I think I might have gotten a few answers there and from ya'll :)
First - I did actually ask about the possibility of the guitar and vocal frequencies cancelling each other out and was told that the odds of this and the difference in timbre make it virtually not a concern...
BUT the biggest thing I learned came from discussing this with the sound guy - who told me that when I said I needed to be louder, I was not specific, and he thought I needed to hear myself better in the monitors. We did another gig where I could give specific direction - and asked for a good friend to monitor levels and text me on stage - and we nailed it.
From my class, I found out that my posture isn't great. (Yay to the comments section for diagnosing this!) - so that did help me control the changes and kept me at a steady volume (still working on it) -- and I also learned that I was in SERIOUS danger of having caused myself damage. --- Trying to compete with a hard rock band volume so that the 'show would go on' was a big mistake. -- Got myself a better mic. And I started transposing the beats and giving the drummer cues on what he was playing groovewise, if he should use brushes, and counting him off on songs he didn't know that well.
You guys were right in the comments section, once the drummer felt more comfortable and confident he was able to bring the volume down and play with dynamics and groove.
I do still have a lot of work to do on chest singing so that I can be able to safely belt in situations where no matter what I do, the sound guy sucks, the acoustics are terrible, and the drummer is a stranger who makes mistakes (it happens.. haha) -- but I appreciate everyone's advice. It really helped me have an honest discussion with sound and the band and get something very simple fixed and move in the right direction!!
Answer: When you're singing acoustic songs, you may well be using your head voice, as this lends itself well to that genre. When belting out rock songs, you need to use your chest voice - from the diaphragm - to project.This takes a lot of practice, but will amplify your voice naturally.
Drummers and guitarists can play quietly, it just takes a lot of courage for them and they tend to hide behind their potential volume.
If you have  feedback it's God's way of saying  turn everything down, it's too loud !!  Or - don't stand in front of that speaker with a live mic.In a small room, there should be no need for foldback, as with careful placing of main p.a. speakers,the sound should be audible to the whole band, with the exception maybe of the drummer, at the back, who will then need to stop making such a racket so he CAN hear what's going on. He is, after all a member of a TEAM.

Techniques to Improve Vocal Volume?


MS Access SQL How to put a table name as Variable (how to run one query for multiple tables)

Question: Lets say I have a query like this:
Parameters Table_Name string, Field_Name string;

Update Table_Name Set Table_Name.[field1] = "new value", Table_Name.[field2] = "new Value" Where Table_Name.[Field_Name] = "Some value"

Basically I have the same query which I need to run against different tables which share some fields together. I want to be able to type the table name when I run the query.
I know this can be achieved with VBA, but this way would be a lot easier than VBA. Although VBA is also welcome but I would like to be able to do this in pure SQL.
How to achieve the above logic for table names AND field names?
Answer: Is this being done in MSAccess or in SQL Server?  If you've got a SQL Server behind things, then you'll be looking to do some sp_executesql calls to get the job done.  If you're doing this in MSAccess, you can accomplish the same by building dynamic SQL statements in VBA - either way would work if you've got Access pointing to SQL, though.


NSKeyedUnarchiver - how to prevent a crash

Question: I guess this is very obvious, but I have a question about loading data. If have a file called library.dat which stores all kind of information about objects in the app. It's set up all nicely (in terms of the initWithCoder and encodeWithCoder methods etc.), but I was just wondering what happens if the library.dat ever gets corrupted. I corrupted it a bit myself and the app will then crash. Is there any way to prevent a crash? Can I test a file before loading it? Here is the bit which can potentially be very fatal:
<code>    -(void)loadLibraryDat {

    NSLog(@"loadLibraryDat...");
    NSString *filePath = [[self documentsDirectory] stringByAppendingPathComponent:@"library.dat"];

    // if the app crashes here, there is no way for the user to get the app running- except by deleting and re-installing it...
    self.libraryDat = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

}
</code>
I had a look at *NSInvalidUnarchiveOperationException but have no idea how I should implement this in my code. I'd be grateful for any examples. Thanks in advance!
Answer: You can wrap the unarchive call with @try{}@catch{}@finally. This is described in Apple docs here: http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/ObjectiveC/Chapters/ocExceptionHandling.html
<code>@try {
    self.libraryDat = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
} @catch ( NSInvalidUnarchiveOperationException *ex ) {
    //do whatever you need to in case of a crash
} @finally {
    //this will always get called even if there is an exception
}
</code>
Comment: Thanks a lot for confirming that this is the official way to handle this.
Comment: NSInvalidUnarchiveOperationException is a string, not a class of Exception. So I think you have to catch NSException, then check against its name...?
Answer: Have you tried 'try/catch' blocks? Something like this:
<code>@try {
    self.libraryDat = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
@catch (NSException* exception) {
    NSLog(@"provide some logs here");
    // delete corrupted archive
    // initialize libraryDat from scratch
}
</code>
Comment: I think there is no other simple solutions. Unfortunately.
Comment: Or should this be @catch(NSException *exception) ?
Comment: `NSInvalidUnarchiveOperationException` is _not_ an exception, it's a string constant. It should be `@catch (NSException* exception)`
Comment: Thanks! I'm fairly new to this and people always warned against 'try/catch' blocks. Sounds very reasonable in this case, though. I guess there is no other way but to work with blocks, right?
Comment: Just tried this, but xCode tells me that "Unknown type name 'NSInvalidUnarchiveOperationException'" -- do I have to define it previously?
Comment: Have you imported NSKeyedArchiver.h?


Enabling and disabling CDN via ScriptManager

Question: I want to use the Microsoft's CDN for hosting the AJAX Library for my .NET 4.0 web application.  However, I was asked to implement a fallback for when the CDN isn't available or when developers want to develop locally without internet.  In these scenarios the ScriptManager should send the locally hosted copies rather than the CDN copies of the JavaScript.  I know I can manually disable the CDN in the scriptmanager, but this can be tedious and potentially lead to missed configurations reaching production.
Is there a more elegant way to use a local copy of the JavaScript files without manually disabling CDN in every spot in code via ScriptManager?
Answer: Taken from html5 boiler plate
<code><script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.4.2.js"%3E%3C/script%3E'))</script>
</code>
Comment: Thanks for the tip, however I can do this easily outside of the ScriptManager.  I was hoping for an answer more geared towards the .NET ScriptManager control.


A view only shows if a certain filter criteria does not exist?

Question: I have a view that I am using to list events, specifically "today's events." I used a filter criteria to allow me to only display events that were happening "today" (as asked by an earlier question. I have recently realized that there will not necessarily be an event "Today", and if there isn't, I have a problem, because nothing is displaying. what I want is to have either a separate view (or do it in the current view if it is possible) that only displays if there are no events "today" what I want it to display instead is "upcoming events." that way, if there are no events on the day that you are looking at the site, than ou will see future events instead.
Answer: Under the advanced tab you can define "No Results Behavior".  This will allow you to add a view or html instead.  This will be in the same view.