Interpreting exp(B) in multinomial logistic regression

Question: This is somewhat of a beginner's question, but how does one interpret an exp(B) result of 6.012 in a multinomial logistic regression model?
1) is it 6.012-1.0 = 5.012 = 5012% increase in risk?
or
2) 6.012/(1+6.012) = 0.857 = 85.7% increase in risk?
In case both alternatives are incorrect, can someone please mention the correct way?
Ive searched many resources on the internet and I get to these two alternatives, and I am not entirely sure which one is correct.
Answer: It will take us a while to get there, but in summary, a one-unit change in the variable corresponding to B will multiply the relative risk of the outcome (compared to the base outcome) by 6.012.
One might express this as a "5012%" increase in relative risk, but that's a confusing and potentially misleading way to do it, because it suggests we should be thinking of the changes additively, when in fact the multinomial logistic model strongly encourages us to think multiplicatively.  The modifier "relative" is essential, because a change in a variable is simultaneously changing the predicted probabilities of all outcomes, not just the one in question, so we have to compare probabilities (by means of ratios, not differences).
The rest of this reply develops the terminology and intuition needed to interpret these statements correctly.
Background
Let's start with ordinary logistic regression before moving on to the multinomial case.
For dependent (binary) variable $Y$ and independent variables $X_i$, the model is
$$\Pr[Y=1] = \frac{\exp(\beta_1 X_1 + \cdots + \beta_m X_m)}{1+\exp(\beta_1 X_1 + \cdots + \beta_m X_m)};$$
equivalently, assuming $0 \ne \Pr[Y=1] \ne 1$,
$$\log(\rho(X_1, \cdots, X_m)) = \log\frac{\Pr[Y=1]}{\Pr[Y=0]} = \beta_1 X_1 + \cdots + \beta_m X_m.$$
(This simply defines $\rho$, which is the odds as a function of the $X_i$.)
Without any loss of generality, index the $X_i$ so that $X_m$ is the variable and $\beta_m$ is the "B" in the question (so that $\exp(\beta_m)=6.012$).  Fixing the values of $X_i, 1\le i\lt m$, and varying $X_m$ by a small amount $\delta$ yields
$$\log(\rho(\cdots, X_m+\delta)) - \log(\rho(\cdots, X_m)) = \beta_m \delta.$$
Thus, $\beta_m$ is the marginal change in log odds with respect to $X_m$.
To recover $\exp(\beta_m)$, evidently we must set $\delta=1$ and exponentiate the left hand side:
$$\eqalign{
\exp(\beta_m) &= \exp(\beta_m \times 1) \\
& = \exp( \log(\rho(\cdots, X_m+1)) -  \log(\rho(\cdots, X_m))) \\
& = \frac{\rho(\cdots, X_m+1)}{\rho(\cdots, X_m)}.
}$$
This exhibits $\exp(\beta_m)$ as the odds ratio for a one-unit increase in $X_m$.  To develop an intuition for what this might mean, tabulate some values for a range of starting odds, rounding heavily to make the patterns stand out:
<code>Starting odds  Ending odds  Starting Pr[Y=1]  Ending Pr[Y=1]
0.0001         0.0006       0.0001            0.0006
0.001          0.006        0.001             0.006
0.01           0.06         0.01              0.057
0.1            0.6          0.091             0.38
1.             6.           0.5               0.9
10.            60.          0.91              1.
100.           600.         0.99              1.
</code>
For really small odds, which correspond to really small probabilities, the effect of a one unit increase in $X_m$ is to multiply the odds or the probability by about 6.012. The multiplicative factor decreases as the odds (and probability) get larger, and has essentially vanished once the odds exceed 10 (the probability exceeds 0.9).

As an additive change, there's not much of a difference between a probability of 0.0001 and 0.0006 (it's only 0.05%), nor is there much of a difference between 0.99 and 1. (only 1%).  The largest additive effect occurs when the odds equal $1/\sqrt{6.012} \sim 0.408$, where the probability changes from 29% to 71%: a change of +42%.

We see, then, that if we express "risk" as an odds ratio, $\beta_m$ = "B" has a simple interpretation--the odds ratio equals $\beta_m$ for a unit increase in $X_m$--but when we express risk in some other fashion, such as a change in probabilities, the interpretation requires care to specify the starting probability.
Multinomial logistic regression
(This has been added as a later edit.)
Having recognized the value of using log odds to express chances, let's move on to the multinomial case.  Now the dependent variable $Y$ can equal one of $k \ge 2$ categories, indexed by $i=1, 2, \ldots, k$.  The relative probability that it is in category $i$ is
$$\Pr[Y_i] \sim \exp\left(\beta_1^{(i)} X_1 + \cdots + \beta_m^{(i)} X_m\right)$$
with parameters $\beta_j^{(i)}$ to be determined and writing $Y_i$ for $\Pr[Y=\text{category }i]$.  As an abbreviation, let's write the right-hand expression as $p_i(X,\beta)$ or, where $X$ and $\beta$ are clear from the context, simply $p_i$.  Normalizing to make all these relative probabilities sum to unity gives
$$\Pr[Y_i] =\frac{p_i(X,\beta)}{p_1(X,\beta) + \cdots + p_m(X,\beta)}.$$
(There is an ambiguity in the parameters: there are too many of them.  Conventionally, one chooses a "base" category for comparison and forces all its coefficients to be zero.  However, although this is necessary to report unique estimates of the betas, it is not needed to interpret the coefficients.  To maintain the symmetry--that is, to avoid any artificial distinctions among the categories--let's not enforce any such constraint unless we have to.)
One way to interpret this model is to ask for the marginal rate of change of the log odds for any category (say category $i$) with respect to any one of the independent variables (say $X_j$).  That is, when we change $X_j$ by a little bit, that induces a change in the log odds of $Y_i$.  We are interested in the constant of proportionality relating these two changes.  The Chain Rule of Calculus, together with a little algebra, tells us this rate of change is
$$\frac{\partial\ \text{log odds}(Y_i)}{\partial\ X_j} = \beta_j^{(i)} - \frac{\beta_j^{(1)}p_1 + \cdots + \beta_j^{(i-1)}p_{i-1} + \beta_j^{(i+1)}p_{i+1} +\cdots + \beta_j^{(k)}p_k}{p_1 + \cdots + p_{i-1} + p_{i+1} + \cdots + p_k}.$$
This has a relatively simple interpretation as the coefficient $\beta_j^{(i)}$ of $X_j$ in the formula for the chance that $Y$ is in category $i$ minus an "adjustment."  The adjustment is the probability-weighted average of the coefficients of $X_j$ in all the other categories.  The weights are computed using probabilities associated with the current values of the independent variables $X$.  Thus, the marginal change in logs is not necessarily constant: it depends on the probabilities of all the other categories, not just the probability of the category in question (category $i$).
When there are just $k=2$ categories, this ought to reduce to ordinary logistic regression. Indeed, the probability weighting does nothing and (choosing $i=2$) gives simply the difference $\beta_j^{(2)} - \beta_j^{(1)}$.  Letting category $i$ be the base case reduces this further to $\beta_j^{(2)}$, because we force $\beta_j^{(1)}=0$.  Thus the new interpretation generalizes the old.
To interpret $\beta_j^{(i)}$ directly, then, we will isolate it on one side of the preceding formula, leading to:

The coefficient of $X_j$ for category $i$ equals the marginal change in the log odds of category $i$ with respect to the variable $X_j$, plus the probability-weighted average of the coefficients of all the other $X_{j'}$ for category $i$.

Another interpretation, albeit a little less direct, is afforded by (temporarily) setting category $i$ as the base case, thereby making $\beta_j^{(i)}=0$ for all the independent variables $X_j$:

The marginal rate of change in the log odds of the base case for variable $X_j$ is the negative of the probability-weighted average of its coefficients for all the other cases.

Actually using these interpretations typically requires extracting the betas and the probabilities from software output and performing the calculations as shown.
Finally, for the exponentiated coefficients, note that the ratio of probabilities among two outcomes (sometimes called the "relative risk" of $i$ compared to $i'$) is
$$\frac{Y_{i}}{Y_{i'}} = \frac{p_{i}(X,\beta)}{p_{i'}(X,\beta)}.$$
Let's increase $X_j$ by one unit to $X_j+1$.  This multiplies $p_{i}$ by $\exp(\beta_j^{(i)})$ and $p_{i'}$ by $\exp(\beta_j^{(i')})$, whence the relative risk is multiplied by $\exp(\beta_j^{(i)}) / \exp(\beta_j^{(i')})$ = $\exp(\beta_j^{(i)}-\beta_j^{(i')})$.  Taking category $i'$ to be the base case reduces this to $\exp(\beta_j^{(i)})$, leading us to say,

The exponentiated coefficient $\exp(\beta_j^{(i)})$ is the amount by which the relative risk $\Pr[Y = \text{category }i]/\Pr[Y = \text{base category}]$ is multiplied when variable $X_j$ is increased by one unit.
Comment: Great explanations, but the OP explicitly asked for the *multinomial* model. I may be reading more into the question than the OP intended, and the explanation for the binary case may be adequate, but I would love to see this answer cover the general multinomial case too. Even though the parametrization is similar, the "log-odds" are in general with respect to an (arbitrary) reference category, and they are not really log-odds, and a unit change in $X_i$ results in a combined change of these "log-odds", and an increasing "log-odds" does not imply and increasing probability.
Comment: thanks for writing this down. The complete answer is a very good reference.
Comment: @NRH That's an excellent point.  I had somehow read "multivariate" instead of "multinomial."  If I get a chance to return to this I will try to flesh out those details.  Fortunately the same mode of analysis is effective in finding the correct interpretation.
Comment: @NRH Done.  I welcome your suggestions (or anyone else's) about how to make the interpretation clearer, or for alternative interpretations.
Answer: Try considering this bit of explanation in addition to what @whuber has already written so well.  If exp(B) = 6, then the odds ratio associated with an increase of 1 on the predictor in question is 6.  In a multinomial context, by "odds ratio" we mean the ratio of these two quantities:  a) the odds (not probability, but rather p/[1-p]) of a case taking the value of the dependent variable indicated in the output table in question, and b) the odds of a case taking the reference value of the dependent variable.
You seem to be looking to quantify the probability--rather than odds-- of a case being in one or the other category.  To do this you would need to know what probabilities the case "started with" -- i.e., before we assumed the increase of 1 on the predictor in question.  Ratios of probabilities will vary case by case, while the ratio of odds connected with an increase of 1 on the predictor stays the same.
Comment: "If exp(B) = 6, then the odds ratio associated with an increase of 1 on the predictor in question is 6", if I read @whuber's answer correctly it says that the odds ratio *will be multiplied* by 6 with an increase of 1 on the predictor. That is, the new odds ratio will not be 6. Or am I intepreting things incorrectly?
Comment: Where you say "the new odds *ratio* will not be 6" I would say "the new *odds* will not be 6...but the ratio of the new to the old *odds* will be 6."
Comment: Yes, I agree with that! But I just thought that "the odds ratio associated with an increase of 1 on the predictor in question is 6" does not really say that. But maybe I am just misinterpreting it then. Thanks for the clarification!
Answer: I was also looking for the same answer, but the once above were not satisfying for me. It seemed to complex for what it really is. So I will give my interpretation, please correct me if I am wrong.
Do however read to the end, since it is important.
First of all the values B and Exp(B) are the once you are looking for. If the B is negative your Exp(B) will be lower than one, which means odds decrease. If higher the Exp(B) will be higher than 1, meaning odds increase. Since you are multiplying by the factor Exp(B).
Unfortunately you are not there yet. Because in a multinominal regression your dependent variable has multiple categories, let's call these categories D1, D2 and D3. Of which your last is the reference category. And let's assume your first independent variable is sex (males vs females).
Let's say the output for D1 -> males is exp(B)= 1.21, this means for males the odds increase by a factor 1.21 for being in the category D1 rather than D3 (reference category) compared to females (reference category).
So you are always comparing against your reference category of the dependent but also independent variables. This is not true if you have a covariate variable. In that case it would mean; a one unit increase in X increases the odds by a factor of 1.21 of being in category D1 rather than D3.
For those with an ordinal dependent variable:
If you have an ordinal dependent variable and did not do an ordinal regression because of the assumption of proportional odds for instance. Keep in mind your highest category is the reference category. Your result as above are valid to report. But keep in mind that an increase in odds than in fact means an increase in odds of being  in the lower category rather than the higher! But that's only if you have an ordinal dependant variable.
If you want to know the increase in percentage, well take a fictive odds-number, let's say 100 and multiply it by 1.21 which is 121? Compared to 100 how much did it change percentage wise?
Answer: Say that exp(b) in an mlogit is 1.04. if you multiply a number by 1.04, then it increases by 4%. That is the relative risk of being in category a instead of b. I suspect that part of the confusion here might have to do with by 4% (multiplicative meaning) and by 4 percent points (additive meaning). The  % interpretation is correct if we talk about a percentage change not percentage point change. (The latter would not make sense anyhow as relative risks aren't expressed in terms of percentages.)


The  route 's path

Question: My <front> and <none> route is now using one of my view path... I think it's because I delete the default home view.
I don't need it because my home page is a Panels Page...
How to set the <front> route to use an other path ?
EDIT :
Exemple:
i've a view called myContentAdminView, with this url defined : /my-content-admin-view.
if i look in the bdd, in the router table, the both path of the  front> and  none> route are set to  /my-content-admin-view. this values are sync with the url view, i don't know why and how to change that.
The front> is use for exemple when you disconect.
The none> route is use by the MenuBlock to check if a user has the right to see a link with no route (like this one : '#a-anchor-link')
Comment: You want `` to be your panel page? or something else?
Comment: it's already done in the base site parameters configuration. But the  route is the one use for exemple when you are disconected, aperently.
Comment: Also when you add a link in a menu tree with a url like this : "#my-anchor-link", the system check the  route to see if a user can see it. For me anoymous people can't see the link...because the  route is attached with a administration view xD
Answer: The defaults for these routes are defined in system.routing.yml:
'<front>':
  path: '/'
  defaults:
    _title: Home
  requirements:
    _access: 'TRUE'

'<none>':
  path: ''
  options:
    _no_path: TRUE
  requirements:
    _access: 'TRUE'

The router table is rebuilt every time you clear the cache. Then all static routes defined in yaml-files are collected and put in the router table.
If you get other path values for these routes, then you must have overridden this somewhere, for example in a view.
This has nothing to do with the setting in site configuration.
If you a looking for a specific path you can search in all *.routing.yml files for the static routes. Most of the dynamically generated routes probably are somewhere in the config files. You can export the full config of your site (admin/config/development/configuration/full/export) and search there for a specific string.
Comment: yes, I think i did it in my view, because it's the path of my view. How did i change that? I don't remember did anyting about that expect to delete the home page view. I don't found any option about it :s
Comment: I added some ideas how you can try to find the path.
Comment: I allready search in those file...nothing founed. It's someting else. It's using a specific bloc in a specific view, since i deleted the front page.

The  route 's path


What's the root of this chord progression

Question: I've encountered a chord progression, but I'm not quite sure to which key it belongs (I discovered it by playing around on a guitar). The chord progression sounds like this: Amadd9 Em/G F#7add11
Answer: Remember root is not the same as key. You've used both words in your question.
The root of an Amadd9 chord is A. The root note of an Em/G chord is E, because the chord is simply an Em chord, but not in root position. [In classical music this chord would be called E minor, first inversion.] The root note of F#7add11 is F#.
As for key: your first two chords suggest we are in A minor, but we've only heard the notes C, E, G, A and B so far and we could equally be in C major. And until we hear an F of some sort we might equally be in E minor or G major.
Your third chord introduces an F# and a C# which suggest we're moving away from A minor in a 'sharpwards' direction. So far your progression doesn't 'belong' to any key. It hasn't yet established one. This doesn't matter of course, if you're happy with it. You could play alternate chords of A minor and D minor all day without establishing a key.


If $g(x+y)=g(x)g(y)$ and $g$ is not identically zero, then $g(0)= 1$

Question: Let $g:\mathbb{R}\to \mathbb{R}$ such that
(i) for all $y_{1},y_{2} \in (0, \infty)$, $g(y_{1}+y_{2})=g(y_{1})(y_{2})$
Suppose in addition that
(ii) there exists $y \in \mathbb{R}$ such that $g(y)\neq 0$
Prove that $g(0)=1$

I am supposed to use both conditions, however this is the only way I can figure out how to do it.  Could anybody tell me if I am doing it correctly or in what step I am using the second condition?
Since $0 = 0 + 0$ we have $g(0)=g(0 + 0)$.  By condition (i) we have $g(0+0)=g(0)g(0)$. So $g(0)=g(0)g(0)$. Then dividing both sides by $g(0)$, we have $g(0)=1$.
That seems to prove it, but I did not use the second condition.  At least I don't think I did? Am I wrong?
Comment: $g(0)=g(0)g(0)\implies g(0)=1$ or $g(0)=0.$
Comment: Do you only have those conditions in $(0,\infty)$, not $[0,\infty)$?
Comment: Now you just have to discard the second case presented by @mfl... Can you use the second conditions?
Comment: For suitable $y$, you have $0\ne g(y)=g(y+0)=g(y)g(0)$, so ... ?
Answer: Since $g(y)=g(0+y)=g(0)g(y)$, where $g(y)\not=0$, then $g(y)(1-g(0))=0 \implies g(0)=1.$


how to round a number to N decimal places in C++? (correction)

Question: I want to round a number (6.756765345678765) to 10 decimal places , but it returns '6.75677', although it could returns '6.7567653457'
#include <iostream>
#include <cmath>
using namespace std;

double rounded(double number, int N)
{
    return round(number * pow(10, N)) / pow(10, N); // i've chanched float to double
}

int main()
{
    double value = 6.756765345678765;
    cout << rounded(value, 10)
}

I'd like to see a function returns rounded number
Frankly speaking, I'd see an alternative of function 'round' in python
print(round(6.756765345678765, 10))

Answer: You can use setprecision(10) function of <iomanip>.
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    double value = 6.756765345678765;
    cout << setprecision(10) << value;
}

Output:
6.756765346

Answer: Your issue is not your code. Your issue is the cout itself. You have to set its precision to print the double correctly. Here is a previous question related to your issue: How do I print a double value with full precision using cout?
You can try the same code but with: cout.precision(X) where X is the maximum precision you want to display.
Comment: yeah it works, to round a number to 10 decimal places, I have to use 'cout.precision(11)'


URIError: malformed URI sequence?

Question: The below code error's out with URIError: malformed URI sequence? when there is a % sign like 60% - Completed in the URL string from where I need to extract the parameter value e.g. http://some-external-server.com/info?progress=60%%20-%20Completed

I dont have control of the server and need to process the output in my html page.
Comment: possible duplicate of [Javascript decodeURI(Component) malformed uri exception](http://stackoverflow.com/questions/9064536/javascript-decodeuricomponent-malformed-uri-exception)
Comment: Possible duplicate of [Why does decodeURIComponent('%') lock up my browser?](http://stackoverflow.com/questions/7449588/why-does-decodeuricomponent-lock-up-my-browser)
Answer: I think you need to URI encode the percentage sign as '%25'
http://some-external-server.com/info?progress=60%25%20-%20Completed

[EDIT]
I guess you could do something like this:
var str = "60%%20-%20completed";
var uri_encoded = str.replace(/%([^\d].)/, "%25$1");
console.log(str); // "60%25%20-%20completed"
var decoded = decodeURIComponent(uri_encoded);
console.log(decoded); // "60% - completed"

Comment: You may not be able to use decodeURIComponent then, or you may need to preprocess the url before passing it to that function. Are spaces the only other special character you can expect in the url?
Comment: As mentioned above  - I dont have control of the server and need to process the output in my html page.
Comment: No, there could be other special characters in the URL. Anything which would let me extract parameter value in this condition?
Comment: I tried to use this on the `getParameterByName` function but can't seem to get it working. Can you provide an example in the above code's context for a newbie.
Comment: Here is the code : ``
Comment: `TypeError: results is null` on line `var uri_encoded = results[1].replace(/%([^\d].)/, "%25$1");`.
Comment: the value of results is null. you need to check for this before the line `var uri_encoded = ...`

URIError: malformed URI sequence?


load desabilita funções jquery

Question: estou dando um load() na minha div, porem ele sempre desabilita comandos jquery assim que ele da load! Alguma solução???
   $(document).ready(function () {

$('#form_campo').on('submit', function() {

    $.ajax({
        url: 'matriz/salvacad.php',
        type: 'post',
        data: $('#form_campo').serialize(),
        success: function(data) {
        $('.erase').click();

$(".menu").load(location.href + " .menu > *");

        }

    });

    return false;
    });

a função do jquery em um outro arquivo é
    $('.cat').click(function (e) {
    e.preventDefault();
       $('.categoria').fadeToggle("fast");
       $('.menu').fadeOut('slow');
});
    $(".close_red").click(function(e){
    e.preventDefault();
     $(".categoria").fadeOut('fast');

                          });

mas so funciona antes do reload, ou dando um refresh na pagina

Categoria

            <?php
               mysql_set_charset('utf8');

$mostra = mysql_query("SELECT * FROM categoria" )or die (mysql_error());
$ver = mysql_fetch_array($mostra);

$status = $ver["categoria"];

if (empty($status)){

 echo('');

}
    else{

    echo('
Campos do Produto

   ');

    }
            ?>

Produtos

Comment: Você quer carregar uma url (http://localhost.menu. > *) dentro da classe menu?
Comment: @RicardoPontual o resultado nao vem do $_POST, é so o result que aparece numa consulta sql, vou editar pra tu ver
Comment: @adventistaam isso mesmo, vem de um localhost,
Comment: Tentou usar um append?
Comment: deu certo a ajuda do @RicardoPontual, porem meu form desabilitou o submit depois do load tbm
Answer: Bom usando a dica do @Ricardo Portugal, mudamos o query depois que ela retorna e deixamos assim!
    $('.menu').on('click','.cat', function (e) {
    e.preventDefault();
       $('.categoria').fadeToggle("fast");
       $('.menu').fadeOut('slow');
});

usamos o comando .on() que ele ativa as alterações e o uso da query, qto ao formulario, ele deu redundancia com um outro form dentro dele, então removi!
Por enquanto resolvido!!
Answer: possível Solução um:
Adicionar o código no callback do load
$(".menu").load(location.href + " .menu > *", function(){

    $('.cat').click(function (e) {
        e.preventDefault();
        $('.categoria').fadeToggle("fast");
        $('.menu').fadeOut('slow');
    });

    $(".close_red").click(function(e){
        e.preventDefault();
        $(".categoria").fadeOut('fast');
    );
});

Possível solução dois:
Usando o jQuery(document.body) mesmo com o load de uma nova parte, ele sempre irá ler o documento todo
jQuery(document.body).on('click', '.cat', function (e) {
    e.preventDefault();
    $('.categoria').fadeToggle("fast");
    $('.menu').fadeOut('slow');
});

jQuery(document.body).on('click', '.close_red', function (e) {
    e.preventDefault();
    $(".categoria").fadeOut('fast');
});

Digo "possível" porque já houve um caso que um não funcionou, porém o outro sim

load desabilita funções jquery


Erro: Nem todos os caminhos de código retornam um valor

Question: Segue o erro:

"Conta.LoginCliente(string, string)":nem todos os caminhos de código
retornam um valor

    class Conta
    {
        #region atributos
        public String nomeCliente { get; set; }
        public String numAgencia { get; set; }
        public String numConta { get; set; }
        public Boolean contaExiste { get; set; }
        public Decimal saldoCC { get; set; }
        public Decimal saldoPoupanca { get; set; }

        #endregion

    #region metodos

    public  Conta()
    {
        Console.WriteLine("Conta não existe");
    }

    public Conta(String znome, String zAgencia, String zConta, Decimal zsaldoCC, Decimal zsaldoPP)
    {
        nomeCliente = znome;
        numAgencia = zAgencia;
        numConta = zConta;
        saldoPoupanca = 0.0m;
        zsaldoCC = 0.0M;
        contaExiste = true;
    }

    public Conta LoginCliente( String Agencia, String Conta)
    {
        DAO.SQL conexao = new DAO.SQL();
        conexao.AbrirConexao();
        Conta conta = conexao.ConsultarCliente(Agencia, Conta);
        conexao.FecharConexao();
        if(conta != null)
        {
            return conta;
        }

Comment: O que você deseja retornar se a conta for nula? O `ConsultarCliente()` recebe a conta como argumento. E retorna conta também. Pode ser outra conta? Pode ser nula? Este código tem várias coisas esquisitas.
Comment: Gente o erro que estou recebendo tá vindo do LoginCliente
Answer: O erro acontece porque você não está retornando nada explicitamente.
Para consertar, recomendo que crie uma variável para fazer o return:
public Conta LoginCliente( String Agencia, String Conta)
{
    Conta retorno = null;
    DAO.SQL conexao = new DAO.SQL();
    conexao.AbrirConexao();
    Conta conta = conexao.ConsultarCliente(Agencia, Conta);
    conexao.FecharConexao();
    if(conta != null)
    {
        retorno = conta;
    }
    return retorno;
}

Ou faça o retorno explicito do que deseja retornar e retorne conta caso a condição seja verdadeira:
public Conta LoginCliente( String Agencia, String Conta)
{
    DAO.SQL conexao = new DAO.SQL();
    conexao.AbrirConexao();
    Conta conta = conexao.ConsultarCliente(Agencia, Conta);
    conexao.FecharConexao();
    return conta != null ? conta : null;
}

Usei o null só para ilustrar melhor a solução, até porque não teria motivo retornar null, sendo que o valor de conta já vai ser null nessas ocasiões. Mas caso queira retornar nulo mesmo, só não fazer o if:
public Conta LoginCliente( String Agencia, String Conta)
{
    DAO.SQL conexao = new DAO.SQL();
    conexao.AbrirConexao();
    Conta conta = conexao.ConsultarCliente(Agencia, Conta);
    conexao.FecharConexao();
    return conta;
}

Comment: Pode transformar o if/ternário num `return` direto que tem o mesmo efeito para o código ilustrado
Comment: Sim, como foi escrito no final da resposta, usei o `null` só para ilustrar melhor a solução, mas acredito que o mais apropriado não seria retornar `null`.
Comment: Não me expliquei corretamente, eu quis dizer fazer `return conta;` diretamente.
Comment: @Isac Sim, eu entendi, você quem não me entendeu kkk. Editei minha resposta, de qualquer maneira. Para ficar mais facil de entender.
Answer: Fiz um código melhorado dentro dos padrões do C#.
Também comentei que precisa implantar o padrão disposable na classe de conexão para garantir que a conexão seja fechada mesmo se uma exceção for lançada. Não foi muito fã desses gerenciadores de conexões, mas o pior é que alguém fez uma errada, divulgou e todo mundo copia errado sem entender o que está acontecendo aí.
public Conta LoginCliente(string agencia, string conta) {
    DAO.SQL conexao = new DAO.SQL();
    conexao.AbrirConexao(); //esta classe deveria adotar o padrão Disposable
    Conta cliente = conexao.ConsultarCliente(agencia, conta);
    conexao.FecharConexao(); //se der exceção isto nunca será executado
    return cliente;
}

Coloquei no GitHub para referência futura.
O motivo do erro é que o return está em um trecho de código condicional, então se entrar no if tem um return, mas se não entrar não tem, ele precisa retornar uma Conta aconteça o que acontecer no código, a não ser que role uma exceção.
Comment: @RovannLinhalis esse código todo não faz sentido, eu respondi mais por causa disto. Eu reescreveria tudo, mas isso não dá, então pelo menos resolve alguns problemas dele assim. Dei uma melhorada, com sua observação. Esses nomes me confundiram. Obrigado.
Comment: ps. `conta` é um parâmetro e logo abaixo está declarando um objeto do tipo `Conta` de mesmo nome.


Limpar conteúdo do meu console netbeans em java

Question: Bom dia pessoal, qual comando eu utilizo em java para limpar o console do meu netbeans? Pois tenho um método que fica a cada x tempos imprimindo algumas mensagens e quero que fique limpando isso do meu console.
Answer: Para limpar o console, você pode criar e executar o método abaixo, que identifica o SO e executa o comando adequado para limpar o console:
public final static void clearConsole(){

        try{
            final String os = System.getProperty("os.name");

            if (os.contains("Windows")){
                Runtime.getRuntime().exec("cls");

            }else{
                Runtime.getRuntime().exec("clear");
            }
        }
        catch (final Exception e){
        //  Tratar Exceptions
        }
    }

OBS.: Adaptação da resposta original publicada pelo usuário Dyndrilliac em: https://stackoverflow.com/questions/2979383/java-clear-the-console
Answer: /**
 * Função que limpa a Saída/Output do Netbeans
 */
public final static void limparSaida() {
    try {
        Robot robot = new Robot();
        robot.setAutoDelay(10);
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_L);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_L);
    } catch (AWTException ex) {
    }
}

Comment: tente explicar sua resposta...
Answer: Tente usar antes o comando System.out.print ('\u000C');
Comment: O que faz esse comando mais especificamente?


Is it a bad idea to use a variable that is strongly correlated with my independant variable of interest as a control variable?

Question: I am currently looking into the correlation between academic freedom (my independant variable) and university rankings (my dependant variable) using OLS.
I find a negative significant correlation, but since I only have one dependant variable, this results suffers from omitted variable bias. In order to take this into account, I want to introduce some control variables into my model (that are both correlated with my independant and dependant variable).
One of these controls is the presence of democracy/civil liberties (as measured by the Freedom House dataset) in the country. When I regress academic freedom on these variables, I find a very high correlation (the coefficient for both democracy and civil liberties is 0.95).
Because of this high correlation, I was wondering if it was a good idea to use democracy/civil liberties as a control variable to isolate the effect of academic freedom. Is there a risk of a biased coefficient because of this high correlation ?
If there is a risk, would the use of proxies for qualities of institutions that are less correlated with academic freedom be a solution to still control for democracy in my model ?
Answer: In OLS you have omitted-variable bias if the omitted predictors would have non-zero coefficients in the model and are correlated with the included predictors. Then the included predictors are correlated with the error term in the model. To minimize bias in your study, you want to include all predictors that are correlated with academic freedom and would still be associated with the outcome when academic freedom is taken into account.
The problem with including other predictors correlated with academic freedom isn't bias. Including a predictor whose omission would lead to omitted-variable bias would, if anything, reduce bias. The problem with including multiple correlated predictors is that their individual coefficient estimates will then have high variances, due to multicollinearity. Depending on the data, you might thus find that neither predictor individually has a "significant" association with outcome.
That's not necessarily a problem. You could, for example, evaluate the combination of the measures of academic freedom and democracy together instead of trying to isolate them individually. The negative covariances among the coefficient estimates can offset the high variances of the individual estimates when you consider them together.
An alternative might be to treat the measure of democracy as an instrumental variable, as explained in detail in a Wikipedia article and more heuristically on this Cross Validated page. In that case you want the instrumental variable to be highly correlated with the included predictor of primary interest but not with the model's error term and not to be associated with outcome except insofar as the instrument is associated with the included predictor. Whether this makes sense in your situation requires careful application of your understanding of the subject matter. If you want to take that approach you should consult with a statistician or econometrician experienced in such modeling, as there are many underlying assumptions and ways that you might be led astray.
Comment: Thank you for your very clear answer ! When I regress ranking on both academic freedom and democracy, neither of them have a significant effet. Can I conclude from that that when democracy is held constant, there is no correlation between academic freedom and university rankings ?
Comment: @MullerI. no, that's the point of the second and third paragraphs. With highly correlated predictors you can't "hold one constant" very well while you change another. Thus you have very high error estimates for the predictors _individually_. If the model _as a whole_ is significant then you can say that academic freedom and democracy _together_ are associated with university rankings, just not which is individually important. If democracy is a valid instrument here, you could use instrumental-variable methods to evaluate the causal association of academic freedom with rankings.
Comment: So the only scenarion where I can say something about democracy and academic freedom's correlation with the dependant variable is when both are significant, right ? If only one or neither are significant, there's not much I can deduce ? (and I don't think using democracy as an instrument would work, I thought about it but it wouldn't satisfy the exclusion restriction I think)
Comment: @MullerI. even if neither one is significant individually, it's possible for them _together_ to be significant. For example, an `anova()` comparison of a regression model that contains both democracy and academic freedom as predictors against a corresponding model that contains neither of them as predictors could show that the _combination_ of them is significantly associated with ranking.


how to run cron hook after a week

Question: i have created a module to hook Drupal cron system and the function in my module is being executed on every cron run, which is perfect.
I need this hooked cron function to run only once weekly without scheduling the default Drupal cron job .
Any help on this ?
Thanks
Answer: Check out the variety of cron modules that set intervals, like Elysia cron.
https://www.drupal.org/project/elysia_cron
Comment: Thank you. Nice module. Exactly what i was looking for. BTW, i did find my cron hook in the settings tab "admin/config/system/cron" may be added by this module. And i did configure the hook to run after a week. But on the status page it shows a PAUSE icon which means " Job is disabled by settings, and won't run until enabled again" . So really will it run after a week ?
Comment: sorry, i ticked the "disabled" icon next to the cron job.
Comment: @brainHax I personally use [Ultimate Cron](https://www.drupal.org/project/ultimate_cron)

how to run cron hook after a week


Prove Set is a Subspace of a Vector Space

Question: I would like to solve the following problem:
Asume $A$ and $B$ are two subspaces from vectorial real space of matrices $m*n$ where
$A$= {$\begin{pmatrix}
        a & b & c \\
        d & 0 & 0 \\
        \end{pmatrix}$,$b=a+c;a,b,c,d\in \mathbb{R} $},
$B$= {$\begin{pmatrix}
        a & b & c \\
        d & 0 & 0 \\
        \end{pmatrix}$,$c=a+2b;a,b,c,d\in \mathbb{R} $},
Prove that set $A\cap B$ is a vectorial subspace of matrices $m*n$
I'm not sure if this is the right approach but I would start off by finding $A\cap B$ which I know would result in:
$A\cap B$=$\begin{pmatrix}
        a & b & c \\
        d & 0 & 0 \\
        \end{pmatrix}$
Altough I'm not sure what to do with the expressions: $b=a+c$ and $c=a+2b$
After that just prove if the subset:

Is closed under addition.
Is closed under scalar multiplication.
Has vector $0$
Answer: You have all the pieces.
For the intersection, both $b=a+c$ and $c=a+2b$ must hold. After some rearranging you have $b=-2a$ and $c=-3a$. So you can write
$$A \cap B = \left\{\begin{bmatrix}a&-2a&-3a\\d&0&0\end{bmatrix} : a,d \in \mathbb{R}\right\}$$
Answer: You can prove the theorem that says "Let $U$ and $W$ be subespaces of $V$. Then, $U\cap W$ is a subespace of $V$". Both have the zero vector, because the zero vector is in $U$ and $W$. Take two elements $a, b$ in the intersection, then, $a,b\in U$ and $a,b\in W$, and like $U$ and $W$ are subespaces, $a+b\in U$ and $a+b\in W$, then, $a+b\in U\cap W$. For the scalar closure, let $\lambda\in\mathbb{R}$ and $a$ in the intersection, then, $a\in U$ and $a\in W$ and how $U$ and $W$ are subspaces,$\lambda a\in U$ and $\lambda a\in W$, then, $\lambda a\in U\cap W$. Your problem follows of this theorem.


How can I reduce this problem to classification?

Question: I have data X with rows which are features associated to a whole "grid". A grid is full of training points that have (x,y) coordinates inside the grid and a classification from {0,1,2}. Given many grids, our task is to be able to label points in a new grid as 0, 1, or 2.
We are solving this problem now by drawing bounding polygons around areas containing points labeled as 1 or 2 and performing regression to find their centroids and several radii. But this seems unsatisfying and may break down in unforeseen complicated cases.
We considered building many classifiers that each take X plus the (x,y) of a point as features and are trained to output {0,1,2} specifically for this (x,y) in the grid, but there are too many points in the grid to train so many classifiers, and beside that we can not guarantee that our training points will be at regularly-placed (x,y) in the future.
Is there a clever way to reduce the problem to standard classification?
Comment: This does not sound like a machine learning problem to me, but maybe I didn't quite get it.
Could you explain how a point/cell in the grid is mapped to 0,1 or 2?
Comment: The grid is a map, and points in the grid are used as parameters in simulations. Depending upon the outcome of the simulation, the point gets a label. It is an ML problem: X is a set of other features associated with each grid (independent of the "map" aspect), and the output we are using now is a 38 dimensional Y: [x coordinate of centroid, y coordinate of centroid, one radius every 10 degrees around].
Comment: To clarify, you have a series of grids which each have NX columns and NY rows, and also for each grid you have a set of covariates, which I'll call Z, of length NZ. Your task is to train on a set of grids and their corresponding Z's, and then given a new Z to predict values for each of the NX*NY points in the new grid?
Comment: Affirmative, yes
Answer: Okay, I came up with a few ideas:
Idea 1: Assume the training points are arranged in a regular grid or that if they are irregularly-spaced, we can make some transformation to a grid by choosing the closest point's classification for grid-points or something. Train independent classifiers on every grid point. Advantages: Highly parallelizeable. Disadvantages: Doesn't take advantage of spatial correlations because no learner is aware of the others. You have to keep a lot of classifiers around to build your model. And you lose a little information in the transformation to a grid if points are not already regularly-spaced. Points must be regularly spaced for this, because each classifier has to correspond to a particular (x,y) location in the grid for training to work.
Idea 2: Join (x,y) with X data to generate a larger training matrix, and train one classifier on this. Advantages: The classifier can learn spatial relationships and correlations very naturally. The final model only has one agent. Disadvantages: Not so naturally parallelizeable. Each row of X, corresponding to many (x,y) points, will be duplicated over and over in the join. Training is slow, meaning we would need some kind of data reduction on the grid points to make the join less explosively large.
Idea 3: The Label Powerset transformation, where one "create[s] one binary classifier for every label combination attested in the training set" and then at query-time selects the answer to be the label combination belonging to the binary classifier with highest confidence. Advantages: None in this context that I can think of. Disadvantages: The number of possible combinations in the output space is huge, so we almost certainly don't have enough data to train each binary classifier, and the number of these classifiers in the final model would be huge. And what about cases where the answer should really be something not seen in the training data? This can't handle that.
Idea 4: True multi-label classification to find all y labels for all grid-points in a grid simultaneously as a one multi-dimensional output from a single agent. Advantages: Single agent. Disadvantages: Only a few kinds of learners support this functionality: AdaBoost.MH, AdaBoost.MR, ML-kNN, Decision Trees, Neural Nets (BP-MLL), and some vector-valued kernel methods (possibly some SVM?). Of these, only Decision Trees (and associated types) and kNN have this multi-output functionality built in in scikit-learn.
Idea 5: Do some kind of stochastic ensemble on joined data (as used for Idea 2). Advantages: Parallelizeable. Agents and the ensemble get some notion of spatial relationships between points. Disadvantages: Many agents.
Idea 6: Train one classifier on Idea-2-like joined data, but do data reduction to reduce the total number of points. Possibilities: clustering, only training on points around boundaries, using representative subsets.


Strongswan running in container to create VPN tunnel between LAN and GCE?

Question: I've got a CentOS 7 VM running strongSwan which sets up a VPN tunnel between our LAN and Google Compute Engine (Google Cloud VPN). This makes local machines on the LAN accessible by GCE instances and vice versa.
I'd like to run strongSwan in a Docker container instead of the resource hungry VM. However, I'm pretty sure I cannot make the container aware of our LAN and therefore not make GCE instances access the machines on our LAN (and vice versa) - as the VPN tunnel would only be created between the container's network and Google's network.
Am I correct or can this somehow be achieved?
Answer: strongSwan uses IPsec in tunnel mode, which (on Linux) requires loading and using a few kernel modules. Loading the module and configuring it is not something you can do inside a normal container. You can get around this by making the container privileged and using a "host" mode network so that the container can see the tunnel it creates(docker run --privileged --net=host), but essentially this disables the isolation between the container and it's host, so it's probably not what you want.


Multicolor text in TreeView (Embarcadero RAD studio)

Question: I am writing a piece of software in C++ RAD studio 2010 and got a question about TreeView.
Is it possible to use multicolor text in a TTreeView component? I could not find a easy way but to implement custom drawing which seems to be weird nowadays. Are there any straight-forward ways or maybe additional components that can do it for me?
UPDATE
Ended up doing it with custom drawing.
<code>void __fastcall TForm1::TreeView1AdvancedCustomDrawItem(TCustomTreeView *Sender, TTreeNode *Node,
    TCustomDrawState State, TCustomDrawStage Stage, bool &PaintImages,
    bool &DefaultDraw)
if (Stage == cdPostPaint)
  {
 TRect rect(Node->DisplayRect(true));
 String redText = "redtext";
 String greenText = " greentext";
 Sender->Canvas->Font->Color = clRed;
 Sender->Canvas->Refresh();
 Sender->Canvas->TextOut(rect.Left, rect.Top, redText);

 rect.Left += Sender->Canvas->TextWidth(redText);

 Sender->Canvas->Font->Color = clGreen;
 Sender->Canvas->Refresh();
 Sender->Canvas->TextOut(rect.Left, rect.Top, greenText);

 rect.Left += Sender->Canvas->TextWidth(greenText);
  }
</code>
It was important to use Refresh so that the method works.
Also, after having realized that I needed multiline text to output I switched to VirtualTreeView component from soft-gems
Comment: I have never had to use TCanvas::Refresh() inside a custom-draw handler.  Changing the Font multiple times has always worked fine for me without any extra work.
Answer: Custom drawing is the only way.  There is nothing weird about that.  Many controls support custom drawing.


Can't get the CPU Usage in C# using PerformanceCounter - System.FormatException

Question: I always used this simple code (from #278071) to get CPU usage:
<code>var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");

public string getCurrentCpuUsage() {
        return cpuCounter.NextValue()+"%";
}
</code>
It worked perfectly for years. But it's not working after upgrade. I'm using Windows 10 now and cpuCounter.NextValue throws System.FormatException: Input string was not in a correct format.
What's wrong? Is it because of Windows 10? Or it's because of my new CPU - Xeon E5-2683? How can I get the CPU usage?
upd:
System.FormatException is thrown when I'm using .NET Framework 3.5. I switched to .NET Framework 4.5 and now it throws InvalidOperationException: Cannot load Counter Name data because an invalid index '' was read from the registry.
Comment: Is it `cpuCounter.NextValue()` that throws the error, or `cpuCounter.NextValue()+"%"`?
Comment: cpuCounter.NextValue();
cpuCounter.NextSample() throws exception too.
Comment: Works on my win10 machine, so it is probably not that. Code seems fine.
Comment: The question you linked is 10 years old. The links in the linked answer points to documentation of .Net version 2.0 . What is your .Net version ? Can you check for your answer in the corresponding documentation version ?
Comment: Just updated question.
Comment: Problem solved.
Answer: Solution: Cannot load Counter Name data because an invalid index -Exception
Just run "lodctr /r" as Administrator. Everything is fine now.


(Geometrically) Where are the critical points of the solutions of $y' = x − 2y$? How many critical points can a single solution have?

Question: Question Continued: For what values of $y_{0}$ does the solution $y$ with $y(0) = y_{0}$ have a critical point? When there is one, is it a minimum or a maximum?
This is a question on an MIT OpenCourseWare Practice Problem Sheet for Differential Equations. I am having just a minor doubt in the solution given on the website. I will paste the entire solution here and then state my doubt.
Solution: All critical points lie on the $y' = 0-isocline$, which is the line $y = \frac{1}{2}x$. We will argue that solutions above the linear integral curve $y = \frac{1}{2}x − \frac{1}{4}$ have exactly one critical point and solutions below it have no critical points. For graphical intuition, refer to the following screenshot.

The question can be rephrased as how do solutions touch or intersect the nullcline. From the graph, it seems that the solution space is divided in two, and the only solutions to intersect the nullcline are those that lie above the $\frac{1}{2}-isocline,$ $y = \frac{1}{2}x − \frac{1}{4}$. The $\frac{1}{2}-isocline$ is an asymptote as can be seen from the figure, and solutions stay above this line for all x if they are above it at any point – for example, if they have a larger $y$-intercept $(y_{0} > -\frac{1}{4})$.
We will show that solutions have a critical point exactly when they are contained in the upper solution space. One direction of this is easy. All the critical points lie on the nullcline, which is in the upper solution space, so a solution has a critical point only if it also lies in the upper solution space. To show the other direction, use the geometry of the isoclines that we found -
 that these are parallel lines of slope $\frac{1}{2}$, of steadily increasing value equal to negative double their $y$-intercept. So solutions in the upper solution space have translational symmetry and all look like the solution through $(0, 0)$, shifted along the nullcline. In particular, they all intersect the nullcline eventually.
Finally, since the nullcline is also a line of slope $\frac{1}{2}$, any solution going through a point on it must pass from the region to the left of it to the region to the right of it, since at the point of intersection $\frac{dy}{dx} = 0 < \frac{1}{2}$. Therefore, all solutions which intersect the nullcline at all will pass through it exactly once, so they have exactly one critical point.
To summarize, solutions can have either zero or one critical point, and a solution has a critical point if and only if it lies above the linear integral curve $y = \frac{1}{2}x − \frac{1}{4}$ (has $y$-intercept $y_{0} > -\frac{1}{4}$). The picture also makes it appear that all of the critical points are minima.
Solution End.
Doubt: The problem I am facing is understanding this part of the solution ..."To show the other direction, use the geometry of the isoclines that we found - that these are parallel lines of slope $\frac{1}{2}$, of steadily increasing value equal to negative double their $y$-intercept."...
What does this line mean? I cannot understand what message they want to convey.
Answer: The solution of your differential equation is
$$y=\lambda e^{-2x}+\frac x 2-\frac 1 4$$
the solution has a critical point $x_0$ if
$$y'(x_0)=-2\lambda e^{-2x_0}+\frac 12=0$$
which gives $$x_0=\ln (4\lambda) $$
for $\lambda=y_0+\frac 1 4>0$.
the condition is then

$$y_0>-\frac 14$$
Comment: That may be true but I am not interested in the Analytic solution of the differential equation. I am interested in what the geometric solution is and how it behaves. Thank you for your response anyway.
Comment: I appreciate your response but I think you haven't read the entire description.
Comment: @SalmanQureshi It is too long.
Comment: At least read the end part. The bold doubt part.
Comment: They are asymptotes for solutions at $+\infty $.$e^{-2x} $ goes to zero.


Action has no declared type error

Question: I'm using Flex and Bison with my grammar for a very simple programming language. But I'm a beginner, so I'm not exactly sure about how to work with them.
Besides some basic operations (like arithmetic and logical operations, assignments, etc.) I also have a function that needs to be recognized by this language: this function is called "ftoc" and it takes one numeric argument.
In my flex .l file I have (among others) these definitions:
DIGITO [0-9]
PUNTO ["."]
CONST_REAL {DIGITO}+{PUNTO}{DIGITO}+
CONST_ENTERA {DIGITO}+
P_A ["("]
P_C [")"]

I also have this rule for the "ftoc" function:
"FtoC" { printf("%s\n", yytext);return FTOC;}

My bison .y file has this union to accept three data types:
%union {
    char *text;
    int integer;
    double real;
}

It also has these token definitions:
%token <integer> CONST_ENTERA
%token <real> CONST_REAL
%token <text> INTEGER
%token <text> REAL
%token <text> STRING
%token P_A P_C
%token FTOC

And the rules involving the "ftoc" function are these:
conversion:
    FTOC P_A constante P_C
;
constante:
    CONST_ENTERA
    | CONST_REAL
;

Now, I need to write a function that prints "ftoc" plus its argument every time the function is found. E.g., if the parser finds the function used as: FtoC(57.6) I need it to print "ftoc57.6".
My function to print this would look somewhat like this:
printFtoc(char* function, double argument){
    snprintf("%s, %f", function, argument);
}

My problem here is how exactly I should pass the parameters to this function. I tried with $n in the "conversion" rule, like this:
FTOC P_A constante P_C {printFtoC($1, $3)}

But then I get 2 errors in Bison (one for each $n), saying that "conversion" has no declared type.
I've been trying to read from Bison documentation but I don't really get what exactly I should be doing. From other questions and forums I get I might need to do something with %type or with %token, but I really don't know.
I just need to get the function name and the argument whenever they're found, but no clue on how to achieve that, since $n didn't work.
Answer: The error tells you exactly what is wrong -- you have a $3 use in a rule that corresponds to a constante, but you haven't declared a type for constante.  You probably need a declaration something like:
%type<real> constante

to tell bison that a constante is in the real field of the union.  You also have a problem with $1 in that action, because FTOC has no type.  You could fix that by either giving FTOC a type and modifying the lex rule to yylval appropriately, or by getting rid of the $1 and using a string literal like "ftoc" instead
Any given non-terminal can only have a single type, so you'll need to add actions to your constante rules.  With the above %type declaration, you would have:
constante: CONST_ENTERA  { $$ = $1; /* implicit int->double conversion */ }
         | CONST_REAL    { $$ = $1; /* simple assignment of a double */ }
;

Comment: Any given non-terminal can only have a single type -- see the above edit
Comment: Thanks, Chris!
About declaring a type for "constante", how should I take care of the fact that there are two rules for it (it can be "CONST_ENTERA" or "CONST_REAL", which represent an integer and a real types)?

    `constante:
    CONST_ENTERA
    | CONST_REAL`

Should I declare the type twice?
    `%type constante
    %type constante`

Action has no declared type error


How do I make my object conform to a protocol?

Question: <code>protocol LiveCellProtocol: class{
    var identifier: Int { get set }
}
public class CoreCellObject: NSObject, LiveCellProtocol {
    var identifier: String = "" //will be set during init.
    init() {
        self.identifier = NSStringFromClass(self.dynamicType) + ":" + NSUUID().UUIDString
    }
}
</code>
The error is that it does not conform to the protocol.
Answer: Your protocol defines a property named 'identifier' as an Int but youve implemented it as a String in your class. It has to be of the same type as defined in your protocol, thats why it doesn't conform
Comment: Thanks. Duh, simple mistake.


Bijectivity and Lipschitz continuity of a function on a Banach space

Question: I don't really know how to solve the following exercise, I need a little help:

a) Let $(X,\|\cdot \|)$ be a Banach space and $F\colon X \to X$ Lipschitz-continuous (i.e. $|F(x) - F(y)| \le L|x-y|$) with Lipschitz constant $L < 1$. Show that $G\colon X \to X$ with $G(x) = x + F(x)$ is bijective and its inverse function $G^{-1}\colon X \to X$ is Lipschitz-continuous with Lipschitz constant $\frac 1{1-L}$.
b) Use a) to show that there is a unique function $f \in C[0,1]$ for which the equation $$f(t) + \int_0^1e^{\tau+t-3}f(\tau)d\tau = 1 \quad \forall t \in [0,1]$$ holds. Determine $f$. Use the fact that $(X,\|\cdot \|_{\infty})$ is a Banach space.

In a) I think using the Banach fixed point theorem is the way to go in order to prove F is bijective. However, I don't know how to start or how to prove the Lipschitz continuity of $G^{-1}$.
For b) I don't know how to start, I'm thinking of the intermediate value theorem?
Comment: Isn't $X'$ in fact $X$?
Comment: Of course, I edited it.
Comment: Where is this exercise from? What book are you using?
Comment: It's from an exercise sheet we got from our University. I'm not using a specific book, just my professors script.
Answer:
The reverse triangle inequality yields $|G(x) -G(y)|\ge (1-L)|x-y|$. This gives the Lipschitz continuity of the inverse map, as soon as $G$ is shown to be surjective. For surjectivity, you are right to use the Banach fixed point theorem: the equation $x+F(x)=y$ has a solution for $x$  because the map $x\mapsto y-F(x)$ has a fixed point.
The supremum norm of $\int_0^1e^{\tau+t-3}f(\tau)d\tau $ is at most $$\|f\|_\infty \int_0^1e^{\tau+1-3} d\tau = \|f\|_\infty  (e^{-1}-e^{-2}) = L\|f\|_\infty$$ where $L = e^{-1}-e^{-2} <1$. This implies the existence and uniqueness of $f$, by virtue of $f$. To determine $f$, rewrite the equation as
$$f(t) = 1 - e^t \int_0^1e^{\tau-3}f(\tau)d\tau $$
which says that $f$ is of the form $f(t)=1-Ce^t$. Plug this in the equation to find $C$.
Comment: I tried a lot now and don't know how to get C. Can you help me?
Answer: The following result proves (a).
Proposition. Suppose that $X$ is a Banach space, and that $f \colon X \to X$ has the form $f(x)=x+r(x)$ where $\operatorname{Lip}(r)<1$. Then $f$ is a lipeomorphism and $\operatorname{Lip}(f^{-1}) \leq (1-\operatorname{Lip}(r))^{-1}$.
Proof. Pick $u \in X$ and define $\xi_u$ by $\xi_u(x) = u-r(x)$. Thus $f(x)=u$ if and only if $\xi_u(x)=x$. Of course $\operatorname{Lip}(\xi_u)=\operatorname{Lip}(r)<1$, and therefore there is a unique fixed point $x$ of $\xi_u$. In particular, $f$ is bijective. Moreover
$$
\begin{align}
\|f^{-1}(u)-f^{-1}(v) \| &= \|x-y\| \\
&= \|\xi_u(x)-\xi_v(y)\| \\
&=\|(u-r(x)-(v-r(y))\| \\
&\leq \|u-v\| + \operatorname{Lip}(r) \|x-y\| \\
&\leq \|u-v\| +  \operatorname{Lip}(r) \|f^{-1}(u)-f^{-1}(v)\|
\end{align}
$$
where $f(x)=u$ and $f(y)=v$. This proves that
$$
\|f^{-1}(u)-f^{-1}(v) \| \leq \frac{1}{1-\operatorname{Lip}(r)} \|u-v\|.
$$


Retrain random forest with important variables

Question: So I have a classification problem with around 2000 predictors. First I run a random forest model to get important variables. Then I only use those variables (let say the top 30) to run the model again. I got a substantial improvement in cross-validation accuracy and AUC. I am just wondering whether it is a good practice and there is any theoretical background behind this?
Comment: My main concern would be overfitting. Since what happens when you're fitting the second RF depends on the steps and decisions you made for the first RF, you've starting to wander in the Garden of Forking Paths.
Comment: With regard to @Sycorax's comment, you should cross-validate the whole procedure, repeating the selection of the top thirty in each fold.
Answer: You can consider this a regularization technique and in general it is a great idea to reduce your feature space to reduce overfitting. Moreover, since you are using random forests it increases the chances that each individual tree will get some important feature instead of "garbage" one which can be important if you don't construct a large number of trees. This is, however, a balancing act and you might want to experiment with number of top features you keep.


java.lang.NoSuchMethodError in jmeter for the methods inside the jar file

Question: I have a jar file where i have one java class.I add that to jmeter and call that jar in sampler.When the request is hit I face java.lang.NoSuchMethodError for one of the methods inside that java class.That method doesn't need any maven dependencies as I use default java functions inside it.I tried manually including that jar to jmeter lib folder but no luck.
Comment: show your class, method and your call
Answer: Which "sampler" and how do you "call" it?

Either there is a typo in your code i.e. you're trying to call the function which doesn't exist
Or there is a typo in your code in terms of passing parameters to the function, in case if it's overloaded the candidate is determined in the runtime depending on the argument types, like function expects an integer and you're passing a string to it or something like this

In JMeter you can use Java code in 3 ways:

in Java Request sampler
in JUnit Request sampler
write your own plugin
Comment: From my Java Maven framework,I have a baseclass where i have all my reusable functions.I convert this class into a jar file and load it in jmeter. I also convert my whole java project into a runnable jar file and laod in jmeter.Now in one of my sampler,I have my JSR233 Postprocessor.i write groovy script and call the method inside that jar where my whole java project is bundled.So when i run that sampler my http request is hit and after that my jar will execute..
Comment: Now everything looks good.But when the code reaches the line where i call my reusable function from my baseclass,i get Nosuchmethod error. The java  jar file is running properly in CMD and jenkins and also my java code is properly running in eclipse


How to know what notes will go together while improvising?

Question: This is 3 questions in one, so it might take a slightly involved answer, or some good links.
Edit--- tl;dr:

How can you learn which keys to hit to make the notes you hear in your head? I know what I want to play when I'm improvising, I can hear it in my head, but I don't know which keys correspond to those notes.
How can you learn which chords will sound good where? There are so many types of chords, how can you know when to play a certain one?
How can you learn to know when accidentals (notes outside the scale) will sound good?

I play piano fairly well, but I skipped theory entirely in my early days and learned to play by reading sheets and listening to better pianists online playing the same piece I was learning, then carefully emulating their sound.
But now I've made some friends who like to improvise together on the piano and do it extremely well, and I'm at a loss when I join in. They usually take the lower register and establish a beautiful rhythm, while I take the upper register and toy around with a melody.
I have no trouble keeping time with them, and I sometimes come up with very pretty melodies, but then here's what happens: I hit 2-3 notes and in my head I hear a melody continuing with the pattern of those 2-3 notes, but then I don't know what notes I'm hearing in my head (I don't have any sort of pitch, not even relative, I'm pretty much tone-deaf), so I can't continue the melody in real time because I don't know what keys to hit in order to create the notes I'm hearing in my head. How do you learn to know what notes to hit? Right now I just have to guess, and sometimes I get it, and sometimes I don't.
Problem two: while toying around with the melody, I'm pretty much trapped in single notes and octaves. Obviously in all the pieces I've played written by other people, there are a million different chords of 2, 3, 4, 5, even 6 notes, and they sound beautiful. But whenever I try to hit one, it just doesn't sound right. How can I learn which ones achieve what kind of sound and when they'll belong and when they won't?
Lastly: The way we improvise is my friend picks a key and shows me what the key is, then I'm careful to only hit notes in that key. For instance, if she said F major, she would show me that B is flat (because I don't know my scales by name), and then while improvising I would be careful not to hit any other black keys and not to hit B natural, which are not in the scale. But I know from all the other pieces I've played that you don't have to stay inside the scale in order for it to sound right-- obviously pieces have sharps and flats and naturals outside the scale all the time. But whenever I try to do it while improvising, it usually just sounds dead WRONG, instantly. But every now and again, by chance, it sounds so right. How do you know when it's okay to go outside the scale?
Sorry for long question!
Comment: You need practice to develop your ear.  There are no hard and fast rules that say "you cannot play this note here." -- IMHO anyway.
Comment: Marc Sabatella has a chord-scale table for jazz improvisation: http://www.outsideshore.com/1992/12/11/chordscale-chart/
Comment: Indeed there are very precise rules which tell you which notes will probably sound good and if you want to be a superior musician you you will to learn all the rules at some point. Which art forms don't require dedication, study and hard work?
Comment: You say you ask 3 questions here, but all 3 are really related. It all comes down to knowing the basics of the chord progressions and playing around that. See [**@Gauthier**'s answer](http://music.stackexchange.com/a/5827/249)
for details.
Answer: Learning improvisation is a long trip.
Most people start with one of two ways:

going by ear, just play something that fits. Try until you think it's good.
going by chords. Learn what tones fits the chords in the chart. Try until you think it's good.

Soon you notice that it's not either one way or the other, it's a combination of both. Good improvisers are able to go either ways.
If you want to go by ear, you need to know how the chords sound. You need to know the song's harmony by heart. Then you need to know how to play the notes that you are hearing in your head. To help you do that you can:

learn to play the melody by heart. The melody of a song is a good starting point for improvising, you can start by playing variations.
listen to the chord progression many times. Either with a play along recording, playing yourself, listening to known recordings. You must really have the chord progression everywhere in your brain.
listen a lot to known recordings of the song, and try to pick up phrases and licks that you like. Watch also closely on which chords these licks work.
train by singing short melodies first, then trying to play them on the piano.

If you want to be able to play by the written chords, you can:

learn to hear the chords by just reading them. Just as you can hear a melody by just reading the notes on a staff, you can learn to hear chords in your head by reading them. Play lots of chords, and concentrate on recognizing chord progressions. To do that you need to be able to play chords, but I'd say you need that anyway.
learn the theory. You have to know your scales by name. You need to know what scale is associated with what chord. You need to know the key signatures of scales. Luckily, different chords can be associated with one scale. For example, Fmaj7, F6/9, Gm7, Am7, C7, may all be associated to the F major scale. Learn that and next time you see the sequence Gm7, C7, Fmaj7 you'll know you can play F major.

When it comes to your second problem, do you mean improvising several tones at the same time? It would be wise to concentrate on improvising a monophonic melody first. That said, you need to learn how to spell chords (see above, learning what scale is associated with what chord) in order to know what combination of tones you can play on a given chord. It should be obvious, you need to know how to play the chord in order to play a chord based on it.

To your last question. It's good that you can improvise if given the current key (here F major). There several reasons for other notes than that of F major being played in a song in F major:

The current chord is not one of F major. Even if a song is in F, the chords do not need to be all based on this scale. For example if you take the song "Yesterday" in C: the first bar has a C chord, the second has Bm7, E7. The song is still in C, but the chords in the second bar have F#, C#, and G#. It could sound weird to play natural F, C or G in that bar (not that it's impossible, but still). In short, accidentals may be associated with the current chord, rather than the main tonality.
The notes are passing notes, not really in the chords but ok in the context. The tone sequence G C D D# E may be played over a C7 chord, although D# is not in the scale associated with C7 (this sequence is a transposed version of the song "Straight no chaser", a blues).
There are other ways to play notes that are foreign to the current chord, but I believe this is much more advanced (some people manage to play 4 bars of D major on a Cmaj7 chord and to get away with it, but you really need attitude).

Now that you can play in the key of F, you should ask your friend to play a blues in F. Ask her to show you the scales associated with a 12-bar blues (F7, C7, G7), train on these scales, learn in what order they come and how long they last. Play along with her while she plays the chords. Or ask her to play the F blues, listen to the chords many many times, listen to many blues based songs (there are incredibly many), and play to her chords by ear.
One good thing with blues is that you can play a single scale on the whole chord chart (the blues scale) and it sounds nice. But if you want to match chords, you can go on and learn which tones "fit" on one chord and not the other ones. Playing these tones at the right place makes things a bit more interesting.

As a side note, if you hear that some tones you play do not sound good, then you are not tone deaf.
Comment: "You need to know what scale is associated with what chord."  That's what I can't really figure out. I know all the boxes of the pentatonics  and know how to throw in some blues/myxl/whatever notes in some places. And I know I can bar chord whateve minor scale box 1 that I'm playing and that will sound good (because all the notes all the way down are in the scale its obvious), but I don't know how to find chords in other blocks or any other chords at all that will sound good with it.
Comment: I am not aware of the terms you are using, boxes and such, but does this help?http://en.m.wikipedia.org/wiki/Jazz_scale
Answer: You can get a lot of traction in this direction by learning  just the intervals (ie. just "relative" pitch). Train yourself to know the sound of a half-step (minor 2nd), a whole-step (major 2nd), minor 3rd, major 3rd, perfect 4th, augmented 4th/diminished 5th, perfect 5th, minor 6th, major 6th, dominant 7th, major 7th, and an octave. If you know what each "jump" sounds like and how to play it, well, that's a complete protein!
One of the shortcuts for educating your apparatus (your musical brain) in this ability is to pick out examples from the songs you know where that interval is emphasized. The typical example is "Here comes the bride" (demonstrating an upward jump across the interval of a perfect fourth). Or the beginning of Beethoven's 9th (demonstrating a downward jump across a major third). In psychology terms, you fill-in a catalog of recepts (organizing your existing percepts) to bolster the concept. Be sure to learn the names, too; so you can communicate about it.
You can learn the minor and major 9th and 10th, too. But melodies rarely jump even that far.
And remember the jazzers' motto: If you make a mistake, play it twice!

Another thing to practice that may help is, when you imagine a little melody, re-play it over and over several times until you have it in a loop or holding pattern. Then you can examine each note and its transition to the next without forgetting the very melody you're trying to analyze.
This is called harnessing the earworm.
Comment: If you've ever had a song "stuck in your head", then you have this ability (at least, potentially).
Answer: As an amateur musician, I find that for me these sorts of problems are commonly rooted in a confusion between theory and practice. Music theory is a technique for de-constructing music, but doesn't work so well for con-structing music. To me musical performance or improvisation should be much more of an experiental "in the moment" process, vs. an analytical one.
Of course I don't achieve that ideal as often as I'd like. My biggest obstacle is my impatience, because the only way to transform explicit analytical knowledge into "felt" implicit knowledge is practice, practice, practice.
With that said, I have found 2 approaches useful for getting better at improvising:

Pick a particular genre of music, and use your "analytical mind" to distill foundational patterns (scales, rhythms, chord progressions, melody, ...) via listening and/or research. Then practice these over and over until they become ingrained.
Play along with a random set of music from your genre (I use Pandora, so I won't know all the songs well, or at all). Here you use your ears, and try to decipher the melodies/chords you hear "in the moment" ... or play whatever sounds good to you.

Not sure if that is helpful?
Answer: I feel that the answers above are missing some important points.
I've been a jazz musician for close to 20 years now, I started in my early teens, studying on weekends at a top conservatory, later went to music school for college, and have worked on and off as a professional musician since. That said, I will never forget the day, when I was 16, when it all clicked, and I first felt comfortable playing a bebop solo. The choice of notes, in terms of which notes to play, should be obvious. For the safest notes, play only chord tones. Then start experimenting with scales and modes, choosing the ones that work with the given harmony. But THE REAL TRUTH is that it does not matter which notes you play while improvising. People are affected by the following things, in this order:
--Rhythm
--Timbre (and volume)
--Melody
As crazy as that may sound, it is true. In other words, it's much more important to have great rhythmic phrasing, and great touch on the instrument than it is to play the "right" notes. If you do have great note choices, that's good, you might even come up with a brilliant, memorable melody in the moment. But Ornette Coleman and Cecil Taylor would not have lived their lives selling sold out concerts if they were overly concerned about which notes they played.
An important exercise is to take a solo that you deeply enjoy, and copy it note-for-note. Then change all of the notes, and leave the rhythm the same. I promise the results will be mind-blowing
Comment: "Then change all of the notes, and leave the rhythm the same." I have to test this. Otherwise I hear you about tone choice being less important than most people think, and it's not the first time I hear that. But I just can't seem to make myself believe it (I just love the tension-release effect of playing out for a bar and then land in), so I'll have to test your exercise!
Answer: Here's three of my own experiences that may interest you:
I recently attended an improvisation workshop with Pete Churchill, a jazz musician. The main point that came across was how you need to be utterly grounded in the melody before you can improvise. Then, when you play or sing, the melody runs in your head in parallel automatically as your voice or fingers improvise. This is certainly my own experience.
I've gradually learnt to improvise by at first straying only slightly from the melody on songs that I know very deeply, such as "Happy Birthday", or very simple children's songs, like "Baa Baa Black Sheep". It's always better to sing first, then use an instrument.
It also sounds like your musical education as a child wasn't complete in all respects (mine wasn't), so some musicianship lessons from your local Kodaly Academy or Kodaly methodolgy teacher would really help embed a sense of pitch, leading on to deeper internalisation of intervals. Kodaly himself said, "A child who plays an instrument before he sings may remain unmusical for a lifetime. That is why we encounter so many skilful pianists who have no idea of the essence of music." I'm certainly not suggesting you are unmusical, only that you sound very accomplished in the formalities of piano yet a bit lacking in early grounding, so catching up on basics you missed earlier could really free the music within. I've been gradually treating myself to some teaching in rhe Kodaly method for a few years now and it's helped a great deal.
Comment: "The main point that came across was how you need to be utterly grounded in the melody before you can improvise. "

Exactly... because improvising is really riffing on melodies you already know ... exactly as an improv comic is never really improvising, they are mashing up what they already know.

Take Paul McCartney ... a melody machine ... and his bass playing reflects that ... it's highly melodic (when possible).

David Gilmore ... melodic. Most shredders ... not melodic ... Allan Holdsworth, yes, the guy is amazing but if he gets something melodic out of his flurry it's some luck.
Answer: Some more possibly helpful tips for soloing/improvising:

Train yourself to hit root notes, thirds or fifths that always sound good,
when you know there are chord changes. Good thing to practice this is the blues.
Similarly, when you break out of key or go chromatic, at least when you're learning, always return quickly.
Should be a like a flourish or accent.
Start with something simple (1 or 2 chords) then progress.
Build a vocabulary of "licks" in different styles - then experiment, hook them together in different ways, invent transistions,...
As you emulated the technique, why not try to emulate the soloing styles of other musicians?
Don't forget rhythmic variation and dynamics.
It should be obvious, learn theory.
Answer: The ear training is important. Additionally, one thing nobody mentions which is very important, is to learn how harmonize and reharmonize those passages - how to fit chords and substitute chords to the melody - and then to improvise using those chord tones.
There is also such a thing in music known as avoid tones, which is a fancy way of saying "tones that plumb don't sound right": see http://en.wikipedia.org/wiki/Avoid_note
The concept described in this article can be extended to apply to any type of chord, including altered chords, non-diatonic chords.
Answer: In addition to following the excellent answers here, you could get copies of David Baker's "How to Play BeBop" books. They provide a very structured way on how to improvise, that might suit you. They teach you what scales fit what chords (at least in the BeBop idiom), and what notes in the scales to play at which beat in the bar as well as how to handle non-scale notes. They also contain a lot of examples or "public domain" phrases that you can incorporate in your playing as a spring board to start off from.
For other styles of music than BeBop Jazz you might want to get other sources, but I believe these books still would be valuable ground to have covered.
Comment: Some would say BeBop is the *Ultimate* Jazz idiom. I, for one.
Answer: How to learn to improvise:
1) Learn every Major, Harmonic Minor, and Melodic Minor Scale.
2) Learn every chord in every Key. You don't have to play them well. Badly will do. But you need ear training and you should be familar with the mechanics of keys. There are 75 chords in C Major. 76 in A Melodic Minor and 63 in A Harmonic Minor. That's good start. Transpose them into all the other keys. And learn to play them all. Badly.
3) If you finished steps 1) and 2) you know what a key is. Next look at a chord score. Take the first chord and the second chord and ask yourself "Are these two chords in the SAME key or a DIFFERENT key."  For example I'm sure you are familiar with the chords C (Major) and Em. What key(s) are they in? If you answered "Either C Major or G Major", then good. Depending on whether or not you find and F or an F# in the melody you can "jam" (that means make it up and use your imaginatione like you did when you were 6) in either C or G Major, because as you are aware those notes make the difference between those keys. If there's no F of any kind at all you are free to use either of the scales.
4) Take the second and third chord and ask the same question. Let's say the first two chords are ambiguous but the third chord is Am. Well in this case we still can't decide from the chords alone which scale to use. Still C and G major.
5) Repeat 4) to the end. Let's say the Forth chord is D. Well now we are pretty sure, in the absence of an F note, the key for this block of chords is G Major. Use that scale to Jam on the entire block.
6) When you have determined all blocks of chords that are in the same key. also look for overlapping blocks where two or even three scales might be used.
7) If you are brave enough to tackle the key changes in Carlos Jobim songs, you will notice that often each chord is in a different key for the whole section. To resolve ambguities you must look at melody notes as before.
But in the absence of any clues all possible scales will do. If you see F# Ma7 for example, with unconnected keys on either side of that bar. You could Use F# Major, C# Major or A# Harmonic Minor over the chord.
8) Jazz songs were DESIGNED by competitive writers TO CONTAIN better and cleverer changes than the previous guys songs. After all Jazz rythm was monotonuos and the words said little or nothing at all, so what else to do? FOr this reason expect beaucoup key changes. Example "Girl from Ipanema". No of key changes in each full cycle = 16. Minimal No of distinct scales you will have to know to jam on this song = 13.
9) Use pentatonic scales whenever possible to tart it all up. See
(Soloing over major and minor mixed chords}
10) Once you get good at Diatonic Improvisation you can start looking at Using Blues Scales. THis is a really complicated subject that deserves several other posts.
Answer: As the others mentioned, you need to learn by ear. That's difficult without knowing what works in the first place. Marc Sabatella, author of A Whole Approach To Jazz Improvisation (published for free here), has a table of conventional chord-scale relationships that work:
CHORD/SCALE CHART

http://www.outsideshore.com/1992/12/11/chordscale-chart/

I recommend reading the whole book.
Answer: You are asking quite a lot of all of us.  It sound like you need a complete curriculum.  I will try to add to the proceedings with my experience as a musician and educator.
Based on what you have written it seems that you do play well, but I didn't see any mention of how long and whether you've had lessons.
Question 1: If you can play, whether by ear or sight reading, then connecting the notes in your head to a key on the piano should be straight forward.  I know a lot of classically trained music students have trouble playing without sheet music.  What has to happen is a connection between the expected note and the note you play needs to be developed and reinforced.  An easy and effective way to do this is to sing the note before you play it.  Tune your ear up by playing simple scales and arpeggios and sign along.  If you have no singing background this can be tough but the development of the ear is naturally connected to the voice so if you can develop the ability to sing what you are hearing in your head you will be able to play what you hear in your head.  My classical bass teacher used this technique to help with intonation problems.
Question2: As for what chords sound good... this is rooted in western harmony theory.  I see lots of gargantuan tables of chords and scales that I assume are all correct (or close to it).  This can be overwhelming and doesn't really provide a solid background for why these all work and how they relate to keys.  Before jumping into extended chords and jazz try reading through a basic music theory and harmony text.  One can harmonize any diatonic melody using just three chords (I, IV, V).  The movement of notes from one chord to the next is not just random (though it can be if you like it).  They serve a function which is to create meaningful and sensible movement and resolution.  When you ask which chords sound good this is a broad question.  They all sound good in a sense but I think what you really want is a rubric for making sensible choices and this is taught in basic theory and harmony.  Once you get an idea of which chords belong to a key, their proper place within the key, and their function, you'll be able to make these choices without a big table.  I refrain from tossing big tables up as an answer because it doesn't really teach anything.
Question 3:  This is a bit more subtle.  Accidentals are used all the time in music.  In some cases the use is pretty standard.  An example is using the melodic minor scale relative to a key.  The melodic minor has a sharp 6th and 7th relative to the natural minor and this helps create movement to the first note via a leading tone, and is used for creating a resolution.  In this case there is a functional use to the accidental and a formula for "correct" accidentals.  I've developed a bit of cynicism towards "accidental" as no note is really an accident (but I know better than that).  Another place where a chromatic passage is found is in the bebop scales, and/or blues scale.  In a nutshell this includes a diminished 5th.  Adding the diminished 5th to the minor pentatonic creates what is called "the blues scale" (though many treat the minor pentatonic as blues).  Lastly, it is common to play the minor third over a dominant 7th chord in blues. In my opinion this is the heart of blues, placing minor over major.  The minor third is frequently "resolved" by sliding it up to the major third (a classic blues cliche).
There is a principle at play in all these examples, that of "leading" into a chord or key tone.  So as long as such a principle is guiding decisions the result will make musical sense.  There are other uses of accidentals but I'm not going to list them all.
Another thing to consider is that improvisational styles of music are very much driven by cultural influence and not as much by music theory.  So the best way to learn "how to improvise" is to immerse yourself in a style of music and start figuring out whole phrases by ear.  You will start to discover that many of the greats use a hand full of phrases very well rather than just put scale patterns down.  Music is an art form and the expressive ingredients are phrases.  So start listening and imitating.  This will help with question 1, and start you o the path to understanding the other issues.
Answer: There's a lot of lengthy discussions here on how to find what notes go together. But if you're talking about finding what bass notes to go with melodic notes, it's a lot easier than you think!  Because the root notes or chords that can be used to play most melodies are chords I, IV, and V, you can use the following simplified scheme to apply this general rule:
1) For each melodic note you play on the main down beats, the root note is most likely to be at note intervals one, three, or five BELOW the melodic note.
2) Build and roll the chords by playing the bass note and the notes at 3, 5, 8, and 10 note intervals ABOVE the bass note.
And that is it! Of course, there are many exceptions, but you will be amazed how many songs you can play using this simple rule (plus slight variations) by simply mirroring whatever notes you are playing on the right hand! Using this method, you can play songs by ear, or make and improvise your own melodies, and with the focus purely on note intervals (not specific notes), you can play them all in any key.
When I figured out this simple scheme last summer, I played four or five traditional Christmas carols (and playing them all in the key of C or C minor) and was suddenly able to see and learn when to use specific melody-bass note intervals at different times and places within a song. Within one to two weeks, I was able to play most songs by ear and in any key, something I was never able to do (or imagined I would be able to do) over the last 40+ years of playing piano! No joke!
Answer: This question is probably no longer active, but should anyone look, here are some of the more detailed points that I have found.
Hertz

It is suggested that the human ear can have a sensitivity of up to 1 Hz. Good sounding chords are ones that have wavelengths that match sufficiently enough so that the ear cannot tell the difference. If you wanted to determine if two notes sounded good together you would first get the Hz of both notes. Take for example Middle C and E. The formula for Hertz goes as follows.

Hertz = 6.875*2^((3+MIDI_Pitch)/12)

What really matters is the ratio between them. E to C has an actual ratio of about 1.1224. The fractional difference is about 9/8 meaning that every 8 oscillations C will match E and every 9 oscillations E will match C(there is a difference). If the either the numerator or denominator of the perfect ratio is above ~13, then it will sound "bad". At that point there are two many waves between the crossovers for the ear to not hear it. Here is a really good site describing it in more detail.

http://
musicmasterworks.com
/WhereMathMeetsMusic.html
Standard Progressions

If your question isn't made in interest(i.e. you are just wondering) then skip this paragraph. This is intended if you for some reason or another needed an algorithm to determine music chord quality.

What you can do is look at popular songs chord progressions. A great site that looked at a few thousand songs and compared their progressions is http://www.hooktheory.com/trends#. Or if you are good at programming you could probably pretty easily make a program that could store the chord progressions of songs you give it until it can come up with a numerical value for each chords likelihood.
Genetic Algorithms

This is if you are really determined. It is unlikely that we will be ever to fully understand what makes good music good. However what you can do is use a genetic algorithm to make songs and thus determine what makes good songs good. Given a few hundred generations it would start having good sounding music.
Answer: Studying theory and learning your scales will help a lot but you also need to practice playing by ear.
Start by just trying to pick out the melodies of some of your favorite songs. At first you will struggle but, like anything else, with practice it will get easier.
As you get better at this try putting a music channel on the radio and just sit at the piano and try to play along, either follow the melody or improvise your own line that fits with the music.
At the same time do your research into theory, and try to mentally connect the theoretical concepts to the way they sound in practice. Eventually you will hear a particular musical effect and be able to say "that sounds like I vi ii V7 progression" or whatever.
Also in Jazz, as in all styles of music, there are many chromatic cliches which crop up over and over again (e.g I I7 IV iv I V7 I). Learning to recognize them and play them in any key will stand you in good stead.
There is a lot of really good material on the internet but I can particularly recommend the youtube channel of Julian Bradly who produces excellent Jazz tutorials. This particular one, nominally about the Altered Scale, gives a very clear insight into the world of jazz improvisation, at first some the theory will go over your head, but it should give you an idea of where to focus your studies.

Answer: Take an existing song.  The printed copy, with melody and chord symbols.  Play the melody.  Work out WHY that melody fits those chords.   Construct an alternative melody.  Start very simply, just one long note per bar.  The sort of thing a chorus might sing as background vocals.  Then try two notes per bar...
Software such as Band in a Box allows you to set up a chord sequence and play melodies on top.  Highly recommended.
Answer: ANSWER: Focus on identifying and learning the common note intervals between melodic notes and root notes played on the main down beats. Read on for more details...
Yes, learning music theory will help ultimately. The problem though is that music theory is primarily descriptive rather than prescriptive in function. Music theory is primarily used to describe and communicate what notes to play and the specific relationships between notes. As a result, music theory doesn't really tell you when to play specific root notes and corresponding chords to go with specific notes in a song's melody, for example.
And yes, you can certainly learn chords and common chord progressions to play on your left hand. But here we have a similar problem - how does one know which chord progressions go with what specific song at the time you want to improvise and play the song (without relying on sheet music or pure memorization)? How do you add chords to a melody that you are making up on the spot?
So here's what I do to begin learning and figuring out what to play on the left hand for whatever melody I'm playing spontaneously and by ear on the right hand. Focus on identifying the note intervals between the melodic notes played on the main down beats and the root notes! You can play a large majority of songs by ear using the following process.

Play ROOT note at 1, 3 or 5 intervals (+ 1 octave) BELOW melodic note played on (sometimes immediately after) main down beat with left pinky. Play intervals 1 or 5 for melodic note I, II, IV, V and 3 for II, VI, VII; 3 when melody progresses chromatically up & down; 2, 4, or 7 in melancholy or midsection of song.
Roll CHORD up & down notes at 1-3-5 or 1-5-8-to-10 intervals ABOVE root notes. Jazz up with 7-9. If you play the song in the key of C (minimizing use of black keys), you can for most of the time just freeze your hand into a three finger claw and roll the notes up from the root notes to play the chords with little or no thought.

Another suggestion: Play lots of songs off fake books that show only the melodic notes and the root notes (identified by the letters that specify the chords). As you play each song, play only the melodic and the root notes to help you quickly identify the number of intervals between the melodic notes played on the main down beats and the root notes. By doing this, you will quickly figure out (after playing just four or five songs) the common melody-root note intervals used to play certain types of songs and to play in various times and places within a song.
Once you figure out the patterns, you can read up on music theory to place the right words to describe and communicate to others what notes you are playing on the left hand, and to explore other options and ways to add left hand harmony.