How to evaluate Smooth L1 Loss, Huber Loss, etc.?

Question: I understand popular loss functions for regression tasks are Huber Loss, MAE, MSE, etc. For purposes of evaluation, popular evaluation metrics are only MAE and MSE (can you evaluate on huber loss, and does this make sense?). So for evaluating a model trained on huber loss, I am reporting both MAE and MSE as evaluation metrics. On the other hand, I could achieve better results if I just trained on MAE and MSE respectively since that is what I am evaluating the model on.
So that brings me to my main question - if I use huber loss during training, does it make sense to report MAE and MSE?
Comment: Of possible interest: https://stats.stackexchange.com/a/502836/247274.
Comment: thanks @Dave, that partially answers my question, that it is reasonable to use MAE/MSE for Huber Loss or Smooth L1 Loss. How do I know the correct choice though? and why not evaluate using MAE if trained on MAE?
Answer: Short answer: Yes, you can and should always report (test) MAE and (test) MSE (or better: RMSE for easier interpretation of the units) regardless of the loss function you used for training (fitting) the model.
Long answer:
The MAE and MSE/RMSE are measured (on test data) after the model was fitted and they simply tell how far on average the predictions were from the true values, i.e. they tell you how well the model performs and have nothing to do with the training itself. These two measures will almost always coincide (i.e. if a model returns lower MAE than another, it will mostly also return lower MSE). For classification you would use something else, like accuracy or AUC. Since in-sample measurement is not useful for comparing the goodness of 2 models these measures should always be measured out-of-sample, hence the well-identifyable names: test-MAE and test-RMSE.
The loss function on the other hand, is used for actually fitting a model and it can make a big difference which one to use. It has nothing to do with the test measures above, even if it can be the same one. For example, it is well-known that minimizing squared loss or equivalently MSE yields an estimate for the mean. Minimizing absolute loss or equivalently MAE yields an estimate for the median. If the goal is to estimate, for example, the mean, then using the MSE as a loss function should yield both lower test-MAE and test-RMSE than using the MAE as a loss function.
Another (extreme) example for clarity: say we want to do quantile regression, i.e. estimate an extreme quantile of the data like the 0.99 or 0.01 quantile and not the mean nor the median. Then, if we use the MAE or MSE as a loss function then they will give poorer test-MSE and test-MAE than if we used a quantile loss function (see last above). As you can see, either test evaluation metrics can be used.
In your case, Huber loss is a differentiable approximation for MAE, so I believe (without having further looked into it) that you should be getting a point-estimation for the median. So getting better test-MAE or test-MSE if you did train on MAE or MSE does not hold. It all depends on the data that you are trying to estimate. (In case you are using xgboost, note that there are some weird behaviors when using huber loss for xgboost)


Homeomorphism of graphs in infinite case.

Question: Sometimes it's still unknown for how to determine homeomorphism or isomorphism of graph in infinite case.
I have two problem that I don't know how to ask.
1) Consider two graphs $G$ and $H$. The first one is $V(G) = \{0,1,2,3\dots\}$ and $E(G)=\{ (i,i+1)\}_{i \in \mathbb{Z}_{\ge 0}}$. The second one is $V(H) = V(G)$ and $E(H) = \{(0,i)\}_{i \in \mathbb{N}}$
2) Consider the same graph $G$ and $M$, such as $V(G)=V(M)$ and $E(M) = E(G)/(1,2) \cup (0,2)$
Now we want to know if graphs are homeomorphic or not ?
I guess in first case the question is no. Their plane picture looks like line and infinite star. So we can't make even a isomorphism between them.
For a second part I have a doubt. They have so much in common, but this erasing of edge make me believe that make some sense. However there are subgraphs that $M' \cong G$ and $G' \cong M$.
Any help will be appreciated.
Comment: In question 1: the fact that the graphs look different does not prove that they are not isomorphic. Sometimes there are very surprising nontrivial isomorphisms between mathematical objects. These graphs really are not isomorphic, and one proof of this fact is that one graph has a vertex of infinite degree and the ither does not.
Answer: In the second case, the graphs are isomorphic.  The isomorphism exchanges $0$ and $1$ and leaves all other points fixed.
Comment: Okay. Thanks for this. What about first case ?
Comment: In the first case, you're correct.  Obviously, an isomorphism has to preserve vertex degrees, so there's no possible candidate in $G$ to map to $0$ in $H$.


How to see if an array of associative arrays is empty in php

Question: I have a fairly easy issue where I need to see if an associative array of arrays is empty in php. My array looks like this:
array (
  'person1' =>
  array (
  ),
  'person2' =>
  array (
  ),
  'person3' =>
  array (
  ),
)

In my case, the three array's for the three people holds nothing so I need a test whether this is empty. I have done this which works:
    if ( empty($form_values['person1']) && empty($form_values['person2']) && empty($form_values['person3'] ) ){
        echo 'values empty!!';
    }

But I was hoping something a bit more cleaner with using empty like the following:
if (empty( $form_values )) {
  echo 'HI!';
}

Comment: How is your array generated? It would be best to just not include the empty subarrays in the first place, then you could just check if `$form_values` is empty as you do. My only other suggestion would be to use a loop. `foreach($array as $a) { if(empty($a)) die() }`
Comment: @GrumpyCrouton Your loop dies if any of the values are empty, not if all of them are.
Comment: @Barmar Ah you're right
Comment: There is a significant volume of answers from [Check if array empty in php](https://stackoverflow.com/q/25100240/2943403) which will provide the desired outcome despite the sample input of that question being a flat array.  And here is a recursive page for more dynamic array structures: [How to check if all values in multidimensional array are empty](https://stackoverflow.com/q/19992280/2943403).
Answer: You can use array_filter() to filter all of the empty array elements. You can then use empty to check if the result is empty then.
I've shorthanded the arrays so it's a easier to read since the arrays are empty. array() will work the same.
$form_values = [
  'person1' => [],
  'person2' => [],
  'person3' => []
];

if (empty(array_filter($form_values))) {
    // empty
} else {
    // not empty
}

Answer: If you're looking for a one-liner then you could do something like:
$form_values = array (
  'person1' =>
  array (
  ),
  'person2' =>
  array (
  ),
  'person3' =>
  array (
  ),
);

if(array_sum(array_map(function($v){return !empty($v);}, $form_values)) === 0)
{
    // empty
}
else
{
    // not empty
}

Answer: Use a loop that tests each nested array. If none of them are non-empty, the whole array is empty.
$is_empty = true;
foreach ($form_values as $val) {
    if (!empty($val)) {
        $is_empty = false;
        break;
    }
}

Comment: Thank you! That should work as well as the other answer.
Comment: @raven This is currently the only answer on the page that is executing the best practice of short circuiting as soon as a false outcome is encountered.  For this reason, this will be the best performer of the lot.
Comment: @mickmackusa It's unfortunate that PHP doesn't have functions like JavaScript's `Array.prototype.every/some()` or Python's `all/any()`. So all the array composition methods must traverse the entire array.
Comment: There are two reasons why I haven't yet upped this answer. 1. `empty()` is an unneeded function call to make a falsey check on a variable guaranteed to be declared and 2. I haven't checked thoroughly for dupe targets.
Comment: 1. "Explicit is better than implicit". I particularly like to be explicit in example code.
Comment: `empty()` performs the same behaviour as `key_exists($val) === false || $val == false`.  However, the variable is unconditionally declared, so the `key_exists()` check is unnecessary work.  If you prefer to use a word instead of `!$val`, then `count($val) === 0` is explicit.  In this context it would also be explicit to use `$val === []`.
Answer: <?php

$data =
[
    'pig' => [],
    'hog' => [],
    'sow' => []
];

$all_empty = array_filter($data) === [];
var_dump($all_empty);

Output:
bool(true)

From the manual for array_filter:

If no callback is supplied, all empty entries of array will be
removed. See empty() for how PHP defines empty in this case.

Note that if an item was deemed as empty, like an empty string, it would still return true.  This test may not be strict enough.
More explicitly:
if (array_filter($data, function($v) {return $v !== []; }) === []) {}

Filter out all items that aren't the empty array.  What we'll be left with is an empty array if all items are an empty array.
Or search and compare:
if (array_keys($data, []) == array_keys($data)) {}

Check keys belonging to items containing the empty array match the keys of the array.  Or rather all items (if they exist) are the empty array.
Note that an empty array will also satisfy the three solutions above.


How can I pass data stored in the DOM to the controller using link_to, remote: true and jQuery?

Question: I would like to have the following link:
<%= link_to image_tag("#{@firstname.lastname@example.com_name}.jpg",
    alt: "#{@email@example.com_name}", class: "playerpic"),
    updatepts_path, :remote => true %>

provide data within the DOM to the controller using jQuery, for example:
<%= link_to image_tag("#{@firstname.lastname@example.com_name}.jpg",
    alt: "#{@email@example.com_name}", class: "playerpic"),
    updatepts_path, :remote => true,
    data: { matchupID: $('#matchup-id').data(matchupID)) } %>

where I've added data: { matchupID: $('#matchup-id').data(matchupID)) } to the link_to helper. Is this or something comparable possible to do? If so, how would I access the data from the controller, using params[:data][:matchupID]?
Thanks!
Answer: You could add a parameter to the updatepts_path for the matchupID in routes, and add the matchupid to the link url created by link_to.
That or just add something like ?matchupID=xxxx to the link if you don't mind the messy url.
Aferall link_to just makes a  tag in the end, its fully capable of being manipulated by javascript after rendering.


Como validar se é vogal sem escrever todas as letras do alfabeto

Question: Escreva a função vogal que recebe um único caractere como parâmetro e devolve True se ele for uma vogal e False se for uma consoante.
Note que
vogal("a") deve devolver True
vogal("b") deve devolver False
vogal("E") deve devolver True
Os valores True e False devolvidos devem ser do tipo bool (booleanos)
Dica: Lembre-se que para passar uma vogal como parâmetro ela precisa ser um texto, ou seja, precisa estar entre aspas.
vogais = ("a", "e", "i", "o", "u")
letra = ("b", "c", "d", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z")

def vogal():
    input(str("Digite uma letra: "))
    while letra == vogais:
        vogal = "a" or "e" or "i" or "o" or "u"
        return "True"
    else:
        return "False"

Não dá erro no código, mas não está no formato certo, o que eu posso fazer pra deixar mais simples?
Answer: Para isto estás longe de precisar de um while... ou de ter todas as letras do alfabeto.
Estás também a cometer o erro que não guardar o input numa variável, e não  precisas de o tranformar em string str(..) pois o input() já retorna uma string por default,

Os valores True e False devolvidos devem ser do tipo bool (booleanos)

então este retorno, return "True", não está correto, deves retornar sem as aspas senão devolves uma string e não Boolean.
Dito isto, podes fazer assim:
def vogal(letra):
    vogais = "aeiou"
    if letra.lower() not in vogais: # verificar se a letra digitada minuscula nao existe na nossa variavel vogais
        return False
    return True

letra = input("Digite uma letra: ")
print(vogal(letra)) # aqui imprime True ou False

Repara que  letra.lower() é para cobrir a hipótese de a letra digitada poder ser maiuscula, e aqui transformamos em minuscula pois as vogais que temos estão também em minuscula.
DEMONSTRAÇÃO
A função podia até ser reduzida (com a alternativa sem a função lower()) para:
def vogal(letra):
    vogais = "aeiouAEIOU"
    return letra in vogais

Comment: Obrigado pela ajuda
Answer: def isVogal(letra):
    vogais = 'aeiou'
    return letra.lower() in vogais

def vogal():
    print(isVogal(input("Digite uma letra: ")))

vogal()

Criei 2 metodos, onde o primeiro retorna True para vogal e False caso contrario, independente se Caixa alta ou não. O segundo recebe a entrada do usuário e imprime True, para vogais e False para consoantes.
Answer: def vogal(x):
    if x == "a" or x == "e" or x == "i" or x == "o" or x == "u" or x== "A" or x == "E" or x == "I" or x == "O" or x == "U":
        return True
    else:
        return False

Comment: Funciona, mas não é recomendado fazer assim em Python. O código fica difícil de ler e, consequentemente, difícil de manter. Busque sempre a solução *pythonica* do problema.


Show that the sequence $1+\frac{1}{2!}+\frac{1}{3!}+\cdots+\frac{1}{n!}$ is Cauchy

Question: Show that the sequence $1+\frac{1}{2!}+\frac{1}{3!}+\cdots+\frac{1}{n!}$ is Cauchy.
I'm not sure where to start with this problem, I know that if I can show that the sequence is convergent I can manipulate the inequality definition of the limit to have $|X_m-X_n|<\epsilon$ but I don't get how to prove the limit exists.
Comment: It converges by monotone convergence and boundedness, hence Cauchy.
Comment: Duplicate of [How to prove that $x\_n=1+\frac{1}{2!}+\cdots+\frac{1}{n!}$ is a Cauchy sequence?](http://math.stackexchange.com/questions/455997/how-to-prove-that-x-n-1-frac12-cdots-frac1n-is-a-cauchy-sequence). Also duplicates [this question](http://math.stackexchange.com/questions/498089/proving-that-a-sequence-is-cauchy-sequence-including-factorials/498092#498092), whose accepted answer just offers a hint.
Comment: @BrianM.Scott Sorry for posting a duplicate question. How can I remove my question?
Answer: Hint: Let $x_n=\displaystyle\sum_{k=1}^n\frac{1}{k!}$ and $m<n.$ Then $x_n-x_m=\displaystyle\sum_{k=m+1}^n\frac{1}{k!}\le\sum_{k=m+1}^n\frac{1}{2^k}$. This is a geometric sum.


Expectation of a fractional form of chi squared

Question: I have been trying to calculate or find a result for the expectation
$$\mathbb{E} \left[ \frac{w^\top D^2 w}{1 + w^\top D w}  \right] $$
where $$w \sim \mathcal{N}(0,I_N),$$
and $D$ is a diagonal matrix of size $N$.
As a matter of fact, I could not even find a result on the expectation
$\mathbb{E} \left[ x^2 / (1+x^2) \right]$ where $x\sim \mathcal{N}(0,1)$.
Is it indeed the fact that these quantities were not studied before or impossible to get closed form solutions?
Thanks a lot!
Answer: Writing $x^2=q$ with $q$ following a chi-square distribution with one degree of freedom we want to calculate
$$E\left(\frac {q}{1+q}\right) = \int_0^{\infty}\frac 1{\sqrt {2 \pi}}q^{-1/2}e^{-q/2}  \frac {q}{1+q}{\rm d}q  = \frac 1{\sqrt {2 \pi}}\int_0^{\infty}q^{1/2}(1+q)^{-1}e^{-q/2} {\rm d}q \;(1)
$$
In Gradshteyn & Ryzhik 7th ed., eq. 3.383(6), p. 348, we find that
$$\int_0^{\infty}q^{v-1}(\beta+q)^{-v+1/2}e^{-\mu q} {\rm d}q = 2^{v-1/2}\Gamma(v)\mu^{-1/2}e^{\beta\mu/2}D_{1-2v}(\sqrt{2\beta\mu})$$
where $D_v(x)$ is Whittaker's parabolic cylinder function.
This expression matches our integral if we set
$$v =3/2,\;\beta =1,\;\mu =1/2$$
and we obtain
$$E\left(\frac {q}{1+q}\right) = \frac 1{\sqrt {2 \pi}}\cdot 2\cdot \Gamma(3/2)\cdot \sqrt{2}\cdot e^{1/4}D_{-2}(1)= e^{1/4}D_{-2}(1) \tag{2}$$
In the same book we find (9.254(2), p. 1030) (note that G+R use the symbol $\Phi$ to refer to the Error function)
that
$$D_{-2}(1) = e^{1/4}\sqrt {\frac {\pi}{2}}\cdot \left[\sqrt{\frac {2}{\pi}}e^{-1/2}-\left(1-{\rm erf}(1/\sqrt 2)\right)\right]$$
where ${\rm erf}()$ is the Error function, which connects with the standard normal CDF $\Phi()$,${\rm erf}(x/\sqrt 2) = 2\Phi(x)-1$ , so
$$D_{-2}(1) = e^{1/4}\sqrt {\frac {\pi}{2}}\cdot \left[\sqrt {\frac {2}{\pi}}e^{-1/2}-\left(1-2\Phi(1) +1\right)\right] $$
$$ = e^{-1/4} -e^{1/4}\sqrt {\frac {\pi}{2}}\cdot 2\Phi(-1) \tag {3}$$
Inserting $(3)$ into $(2)$ we get
$$E\left(\frac {q}{1+q}\right) = 1 - \sqrt {2e\pi}\cdot\Phi(-1) \approx 0.344320458 \tag {4}$$
A quick simulation verifies this. Using $500,000$ draws
$$\begin{align}\\
  \text{Mean  }      &                  0.34433\\
  \text {Median  }     &                 0.31252\\
  \text{Minimum  } &             4.1420e-013\\
  \text{Maximum  }       &              0.96302\\
  \text{Standard deviation  }   &       0.26461\\
  \text{C.V.  }          &              0.76848\\
  \text{Skewness  }     &              0.31389\\
  \text{Ex. kurtosis  }   &            -1.1778\\
  \text{5% percentile  }   &         0.0038428\\
  \text{95% percentile  }   &           0.79284\\
  \text{Interquartile range  }  &      0.47709\\
\end{align}$$
Comment: Thanks a lot for the result and also for the source. This definitely matches my simulations too. Now I have a starting source for studying the other case. I really appreciate your knowledge.


Licenciamento de Jogos Indie

Question: Posso vender jogos feitos no Blender sem me preocupar com licenças?
Answer: Depende do que você chama de "um jogo feito no Blender". De um modo geral, dados produzidos/processados por um programa não têm relação alguma com o seu código. Se você escrever um texto no Word, por exemplo, os direitos autorais do mesmo não vão pra Microsoft... De modo que se você usar o Blender pra criar modelos, animações, etc, e usar isso no seu jogo, então não há a necessidade de se preocupar com licenças.
(Do ponto de vista do Blender, é claro - se você usar modelos de outras pessoas como base para os seus próprios, isso caracteriza uma "obra derivada", ou talvez "cópia". Nesse caso, você pode sim precisar negociar um licenciamento com o(s) autor(es) dos modelo utilizados.)
Agora, quando se fala num jogo, tem código envolvido no meio, então a coisa fica mais complicada. No caso do Blender, ele possui uma engine de jogos embutida. Isso significa que você pode criar um jogo completo simplesmente através de scripts, usando essa engine como "o programa" (há inclusive uma opção pra compilar para um executável). Nesse caso, pode haver restrições sobre a forma de você comercializar seu jogo. Por exemplo, como o Blender é software livre, do tipo copyleft (GNU GPL), isso significa que ao redistribuí-lo você deve fazê-lo em termos que a pessoa que recebe tenha as mesmas liberdades que você (obter o código fonte, modificá-lo à vontade, redistribuir pra quem quiser).
Como um jogo feito dessa forma (script da própria engine do Blender)  inclui boa parte do código do Blender, então não se pode dizer que ele é seu - e sim uma obra derivada do próprio Blender. A forma de licenciamento nesse caso é complexa, de modo que eu sugeriria consultar um advogado.
Answer: Quando você produzir modelos, animações, simulações físicas em um programa aberto como blender, você poderá exportar em formato mais usado como FBX. Segundo a licença, não poderá comercializar um arquivo que conter formato do blender senão é preciso rever conceito da licença, o blender é um software aberto e livre no termo de uso, não pode usar blender como software para ser comercializado e vendido, isso pode tirar vantagem de blender ser o software livre à todos os usuários. Contudo, ao importar FBX ao unity poderá configurar com todos os script em C# e Javascript e na UI, terá modelos, animações, tudo que foi criado partir de você, caso que não encontre as texturas a partir de FBX, é somente pegando as texturas e arrastando para pasta que tem no asset e integrar no material que é vinculado ao objeto de modelo.
Espero ter ajudado.

Licenciamento de Jogos Indie


What is replacement of SSL/HTTPS in drupal to encrypt login credentials

Question: I have one question, in my website i am not using ssl so my drupal login send id and password as plain text, then i have used the encrypt_sumissions module but that is use jcryption library but this is not useful, I want to know how can i encrypt login credentials without ssl/https.
Should I change in drupal core, I am new to this please provide me detailed information.
Thanks
Answer: Save yourself the headache and use TLS/SSL. Drupal won't, and isn't meant to, solve your problem. It isn't worth trying to cobble something together. If the cost of the certificate is an issue, go to https://letsencrypt.org/ and get a free cert.


Why is matcher.group giving me an error?

Question: I am trying to compile the following while loop, but I keep getting a red flag in eclipse next to the group.matcher("...") that says to remove the argument so i match group.
The error i am getting is the following:
The method group(int) in the type Matcher is not applicable for the arguments (String)
The method group(int) in the type Matcher is not applicable for the arguments (String)
The method group(int) in the type Matcher is not applicable for the arguments (String)
The method group(int) in the type Matcher is not applicable for the arguments (String)
The method group(int) in the type Matcher is not applicable for the arguments (String)
Here is the code:
while (matcher.find()) {
        if (matcher.group(TokenType.NUMBER.name()) != null) {
            tokens.add(new Token(TokenType.NUMBER, matcher.group(TokenType.NUMBER.name())));
            continue;
        } else if (matcher.group(TokenType.BINARYOP.name()) != null) {
            tokens.add(new Token(TokenType.BINARYOP, matcher.group(TokenType.BINARYOP.name())));
            continue;
        } else if (matcher.group(TokenType.WHITESPACE.name()) != null)
            continue;
    }

Comment: As error explain, group method require a int, and you pass it a String.
Answer: Since I assume that you use Java 6 or below, matcher.group takes only a int as parameter. If you want to use matcher.group(String) upgrade your project to Java 7. See http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#group(java.lang.String)
and
http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group(java.lang.String)
Comment: @Predator44 It probably uses whatever you have. Check the menu `Project>Properties`. The build path tab includes the JRE library used, and the Java Compiler tab, the compliance level. What do they show?
Comment: But i am using eclipse, and as far as i researched it uses java 7 by default
Comment: In Eclipse, go to Window, Preferences, Java, Compiler and see what's in compiler compliance level.
Comment: You are definitely right, it uses java 6, although i have java 8 installed on my mac, but i can't seem to find the package to select it
Comment: That's probably the difference between JRE and JDK. you probably have Java JRE 8 and a Java JDK 6
Comment: @JFPicard Project>Properties. The build path tab includes the JRE library used java se 1.6. Although i followed your recommendation and installed the JDK 8, but it does not appear in the window
Comment: @JFPicardI figured it out ! i had to create a new project. Thank your for your help


Enviar dados junto com evento

Question: Conforme me aventuro pelo jQuery algumas dúvidas e problemas surgem no meio do caminho, uma delas é: é possível enviar um dado através de um evento acionado por outro evento? Algo como isso:
jQuery
$(".seletor1").on("click", function(){
    $(".seletor2").trigger("click", dados);
});
//
$(".seletor2").on("click", function(dados){
    alert(dados);
});

Answer: Sim podes. Exemplo: http://jsfiddle.net/XBDrh/
$(".seletor1").on("click", function(){
    console.log('Clicado!');
    $(".seletor2").trigger("click", {animal: 'gato'});
});
//
$(".seletor2").on("click", function(evento, animais){
    alert(evento.type);
    alert(animais.animal);
});

Olhando para a documentação do jQuery a syntax esperada é:

.trigger( tipoEvento [, parametrosExtra] )
tipoEvento
Typo: String
Descrição: Uma string contento o nome do evento. Por exemplo 'click' ou 'submit'
parametrosExtra
Typo: Array or Objeto
Descrição: Parametros adicionais a passar com o evento.

Se quiser misturar esse click handler com um click verdadeiro pode criar um if para verificar se foi passado o objeto extra. Sugestão:
$(".seletor2").on("click", function (evento, animais) {

    if (!animais) {
        alert("Clicou no seletor2");
        return false;
    }

    switch (animais.animal) {
        case 'gato':
            alert("Clicou no seletor1");
            break;
        case 'cao':
            alert("Clicou no seletor1");
            break;
        case 'elefante':
            alert("Clicou no seletor1");
            break;
    }
});

Comment: @Patrick, evento é um objeto. Eu coloquei `evento.type` porque essa propriedade é por padrão o nome do evento, e é só para confirmar que é o nome certo. O segundo parametro é também um objeto cuja chave é "animal" e o valor é "gato".
Comment: @Patrick, ok, assim já percebo melhor o que quer. Quantas opções vai ter? se forem muitas eu sugeria algo assim: __http://jsfiddle.net/7euUL/1/__ (de qualquer maneira o problema é que o `animais` não está defenido no caso do clic no seletor2, e por isso ele dá erro quando quer saber o valor de `animais.animal`.
Comment: No caso `animal` é como se fosse um endereço para `'gato'`? Só não entendi a necessidade do `alert(evento.type);`.
Comment: @Patrick, já agora dá uma olhada no google a `console.log()`, bem melhor que o `alert()` e dá para ver objetos, coisa que o alert não dá.
Comment: @Patrick, pode colocar o código que está a usar no jsFiddle: http://jsfiddle.net/XBDrh/1/ para eu ver
Comment: @Patrick o erro está correto, pode explicar melhor o que quer fazer? pois quando clica no `seletor2` esse parametro `animais` não existe pois o `trigger` só é disparado quando carrega no `seletor1`
Comment: Então, minha intenção era dizer: "se o usuário clicar diretamente no `seletor2`, vá para o `default` e faça X, mas se ele clicar no `seletor1`, vá para `'gato'` e faça Y. Ao meu ver, *undefined* jogaria para o `default`.
Comment: @Patrick ótimo que funcionou! Boa ideia de juntar à resposta, fiz isso agora. Amanhã passo por aqui e limpo os comentários também.

Enviar dados junto com evento


Borders not covering background

Question: I've got a UILabel is using a border the same color as a background which it is half obscuring, to create a nice visual effect. However the problem is that there is still a tiny, yet noticeable, sliver of the label's background color on the OUTSIDE of the border.
The border is not covering the whole label!
Changing the border width doesn't change anything either, sadly.
Here's a picture of what's going on, enlarged so you can see it:

And my code follows:
        iconLbl.frame = CGRectMake(theWidth/2-20, bottomView.frame.minY-20, 40, 40)
        iconLbl.font = UIFont.fontAwesomeOfSize(23)
        iconLbl.text = String.fontAwesomeIconWithName(.Info)
        iconLbl.layer.masksToBounds = true
        iconLbl.layer.cornerRadius = iconLbl.frame.size.width/2
        iconLbl.layer.borderWidth = 5
        iconLbl.layer.borderColor = topBackgroundColor.CGColor
        iconLbl.backgroundColor = UIColor.cyanColor()
        iconLbl.textColor = UIColor.whiteColor()

Is there something I'm missing?
Or am I going to have to figure out another to achieve this effect?
Thanks!
EDIT:
List of things I've tried so far!

Changing layer.borderWidth
Fussing around with clipsToBounds/MasksToBounds
Playing around the the layer.frame
Playing around with an integral frame

EDIT 2:
No fix was found! I used a workaround by extending this method on to my UIViewController
func makeFakeBorder(inputView:UIView,width:CGFloat,color:UIColor) -> UIView {
        let fakeBorder = UIView()
        fakeBorder.frame = CGRectMake(inputView.frame.origin.x-width, inputView.frame.origin.y-width, inputView.frame.size.width+width*2, inputView.frame.size.height+width*2)
        fakeBorder.backgroundColor = color
        fakeBorder.clipsToBounds = true
        fakeBorder.layer.cornerRadius = fakeBorder.frame.size.width/2
        fakeBorder.addSubview(inputView)
        inputView.center = CGPointMake(fakeBorder.frame.size.width/2, fakeBorder.frame.size.height/2)
        return fakeBorder
    }

Comment: Try using `borderWidth = 6` or `borderWidth = 5.5`. That may fix it.
Comment: Thanks, but I've already tried that, and it doesn't change anything. I think borders are calculated from the edge, and created inwards.
Comment: Try removing `maskToBounds` or setting it to `false` perhaps?
Comment: Without that, then the label remains a square, with all four corners sticking out. That's how it knows to clip the edges off with cornerRadius. No dice.
Comment: Do you know the exact frame of the label? You may want to set it to the integral version (`CGRectIntegral`)
Comment: @Wain, I'm not familier with this. Is this as simple as changing my code to iconLbl.frame = CGRectMake(theWidth/2-20, bottomView.frame.minY-20, 40, 40).integral ? if so, then there are no changes
Comment: You can change `iconLbl.layer.frame` if that helps anyone, but it doesn't seem to effect it.
Comment: Thanks Charles, but still no cigar. I've got a feeling I'm gonna be putting this label in a larger view, instead of fussing around with a border, but it just feels so... wrong...
Answer: I believe this is the way a border is drawn to a layer in iOS. In the document it says:

When this value is greater than 0.0, the layer draws a border using the current borderColor value. The border is drawn inset from the receiver's bounds by the value specified in this property. It is composited above the receiver's contents and sublayers and includes the effects of the cornerRadius property.

One way to fix this is to apply a mask to a view's layer, but I found out that even if so we still can see a teeny tiny line around the view when doing snapshot tests. So to fix it more, I put this code to layoutSubviews
class MyView: UIView {

    override func layoutSubviews() {
        super.layoutSubviews()

        let maskInset: CGFloat = 1
        // Extends the layer's frame.
        layer.frame = layer.frame.inset(dx: -maskInset, dy: -maskInset)
        // Increase the border width
        layer.borderWidth = layer.borderWidth + maskInset

        layer.cornerRadius = bounds.height / 2
        layer.maskToBounds = true

        // Create a circle shape layer with true bounds.
        let mask = CAShapeLayer()
        mask.path = UIBezierPath(ovalIn: bounds.inset(dx: maskInset, dy: maskInset)).cgPath

        layer.mask = mask
     }
 }

CALayer's mask

Borders not covering background


Postgresql server will not start

Question: I'm on Windows 7. I restarted my computer. I then tried to connect to the database and got an error. I don't remember which one in particular but it was some connection issue. I decided to try to restart the server, so I clicked on "Restart server" from the start menu. This blocked. After a few minutes  I killed the process and tried again, only to get a "The service is starting or stopping.  Please try again later." message.
I rebooted the computer again, tried to start again, and got the same error. I killed the pg_ctl process and tried starting it manually, but that didn't work either:
C:\Users\DrClaud>cscript "C:\Program Files\PostgreSQL\8.3\scripts\serverctl.vbs"
 start wait
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

The PostgreSQL Server 8.3 service is starting...................................
.......................................
The PostgreSQL Server 8.3 service could not be started.

The service did not report an error.

More help is available by typing NET HELPMSG 3534.

The start command returned an error (2)

Any ideas?
Answer: You'll want to check your logs (either the PostgreSQL log in $PGDATA\pg_log or the Windows eventlog), and then you're better of reporting this issue on the pgsql-general mailinglist for a quick answer, unlesss the log messages make it clear to you what the problem is.
Comment: ty for the tips. i ended up reinstalling cause I had my DB backed up, heh.

Postgresql server will not start


Action script error while running flex web application in IE. Error #2044

Question: Error statement: An error has occurred in the script on this page. Line 110 char 446 Error: expected ':' code 0 URL http://clkads.com/adServe/static/btgen-ie-im3.html?tid=SWIM06
Do you want to continue running script on this page?
This error is shown for all the web applications. I am using flex builder 4.6
please help
Answer: Could be a problem with your HTML template file in your project. I don't know if I would classify that as an actionscript error though. If the error isn't there I am at a loss. If you dont find it in there, track down what line 110 char 446 (and everything around it) and post it back.


Why do we call a Fourier series a series of complex exponentials?

Question: Euler's formula is $$e^{{ix}}=\cos x+i\sin x$$
I have recently learned that a periodic function can be decomposed into an infinite series of cosines and sines. However, in the formulas that I've seen, this was a simple sum, without the imaginary number, i.e.
$$\sum_{i=0}^{\infty} a_i\cdot \cos(x)+b_i\sin(x)$$
There is no imaginary number here, unlike in the Euler formula where there is an imaginary number in the right hand side.
How then do we justify using complex exponentials in fourier series, given that this adds an imaginary number to a function that is real-valued?
Comment: use a Fourier series for the real part, and $i * $ a Fourier series for the imaginary part. $f(x) = \sum_{i=0}^{\infty} a_i\cdot \cos(x)+b_i\sin(x)$ + $i\sum_{i=0}^{\infty} c_i\cdot \cos(x)+d_i\sin(x)$
Comment: That is because $\mathbf C$ is the natural frame for trigonometry.
Answer: If the coefficients satisfy a simple relationship, the series will have a real value: since
$$ \cos{x} = \frac{e^{ix}+e^{-ix}}{2}, \qquad \sin{x} = \frac{e^{ix}-e^{-ix}}{2i} $$
(this comes from two instances of Euler's formula, for example), we have
$$ a_n \cos{nx}+b_n\sin{nx} = a_n \frac{e^{inx}+e^{-inx}}{2} + b_n \frac{e^{inx}-e^{-inx}}{2i} = \frac{a_n-ib_n}{2} e^{inx} + \frac{a_n+ib_n}{2} e^{-inx}. $$
In particular, one coefficient is the complex conjugate of the other. Inverting this, if we have a Fourier series
$$ \sum_{n=-\infty}^{\infty} c_n e^{inx}, $$
the series is real if and only if $c_{-n} = c_n^*$ (and we find $a_n = c_n+c_{-n} $, $ b_n = i(c_n-c_{-n}) $ ).
Why would we write it as complex exponentials? Firstly, $\int_{-\pi}^{\pi} e^{inx} f(x) \, dx$ is often easier to calculate than the trigonometric forms, secondly, we only have to do one integral instead of (often) three: one for the constant term, one for the cosine part and one for the sine part, and thirdly, many other important formulae are simpler written in terms of the $c_n$: for example, Parseval/Plancherel is
$$ \frac{1}{2\pi}\int_{-\pi}^{\pi} \lvert f(x) \rvert^2 \, dx = \sum_{n=-\infty}^{\infty} \lvert c_n \rvert^2 $$
instead of
$$ \frac{1}{2\pi}\int_{-\pi}^{\pi} \lvert f(x) \rvert^2 \, dx = \frac{a_0^2}{4}  +\frac{1}{2}\sum_{n=1}^{\infty} a_n^2 + b_n^2 $$
That's not to say the real form doesn't have its uses: if we want to keep everything real, we use it (particularly in applications like solving Laplace's equation, for example), or if the function is clearly odd or even, we only have to calculate one set of coefficients, and the work is effectively halved.
Comment: $i^2=-1$, so if $1/i=i$, $i \times 1/i = i \times i = -1 $, contradicting that $i \times 1/i$ should equal $1$. The square root function is not well-defined for any complex number: is the square root of $1$ equal to $1$ or $-1$? For positive integers there is a consistent answer to this question, but not for negative ones. Instead, $i$ is chosen arbitrarily (instead of $-i$) as the primary square root of $-1$, and then everything that follows has to be consistent with this choice. In particular, if $i^2=-1$, then $(-i) \times i = 1 $, so $-i$ is the multiplicative inverse of $i$.
Comment: Really? then what is wrong with the following? $1/i=1/\sqrt {-1}=\sqrt{1/-1}=\sqrt{-1}=i$
Comment: In the second line of equations, shouldn't the $-$ in front of the $ib_n$ be a $+$ in front of the $e^{inx}$, and the other way around in front of $e^{-inx}$?
Comment: I think it's right: $1/i=-i$, after all.
Answer: The Fourier series expansion of a periodic function can be expressed in trigonometric form as
$$f(x) = \frac{a_0}{2}+\sum_{n=1}^{\infty} a_n\cos(nx) + b_n\sin(nx),$$
and we can find the coefficients as below:
$$ \int_{-\pi}^{\pi}f(x) = \int_{-\pi}^{\pi}\frac{a_0}{2} dx +  \sum_{n=1}^{\infty}a_n \int_{-\pi}^{\pi}\cos(nx) dx +\sum_{n=1}^{\infty}b_n \int_{-\pi}^{\pi}\sin(nx) dx $$
where $\int_{-\pi}^{\pi}\cos(nx) = 0$ and  $\int_{-\pi}^{\pi}\sin(nx) = 0$. Then,
$$ \implies a_0 = \frac{1}{\pi} \int_{-\pi}^{\pi}f(x)dx.$$
Here, we also can find the formula for $a_n$ and $b_n$ through straightforward calculation as
$$ \int_{-\pi}^{\pi}f(x)\cos(mx) = \frac{a_0}{2}\int_{-\pi}^{\pi}\cos(mx) dx +  \sum_{n=1}^{\infty}a_n \int_{-\pi}^{\pi}\cos(nx)\cos(mx) dx \\+\sum_{n=1}^{\infty}b_n \int_{-\pi}^{\pi}\sin(nx)\cos(mx) dx $$
where
$$
 \int_{-\pi}^{\pi}\cos(nx)\cos(mx) dx  =
\begin{cases}
\pi & n = m \\
0 & n \neq m
\end{cases},
$$
$$ \int_{-\pi}^{\pi}\cos(mx) dx  = \frac{1}{m}\sin{mx}|_{-\pi}^{\pi} = 0,$$
$$ \int_{-\pi}^{\pi}\sin(nx)\cos(mx) dx  = 0$$
notice that here, $\sin(nx)\cos(mx)$, is an odd function. Then we have:
$$\implies a_n = \frac{1}{\pi} \int_{-\pi}^{\pi}f(x)\cos(nx)dx.$$
Also, the same procedure for $b_n$ leads to:
$$\implies b_n = \frac{1}{\pi} \int_{-\pi}^{\pi}f(x)\sin(nx)dx.$$
Now, for the Fourier series conversion from the Real form to the complex form we use the Euler's formula we have:
$$f(x) = \frac{a_0}{2}+\sum_{n=1}^{\infty} a_n [\frac{e^{inx}+e^{-inx}}{2}]+ b_n[\frac{e^{inx}-e^{-inx}}{2i}],$$
then we have
$$f(x) = \frac{a_0}{2}+\sum_{n=1}^{\infty} \frac{1}{2} [a_n -ib_n]e^{inx} +  \frac{1}{2} [a_n +ib_n]e^{-inx},$$
and finally we have:
$$f(x) =  \sum_{n=-\infty}^{\infty} c_n e^{inx} ,$$
where:
$$
 c_n =
\begin{cases}
\frac{1}{2} [a_n -ib_n] & n \geq 0 \\
\frac{1}{2} [a_{|n|} +ib_{|n|}] & n \leq 0 \\
\frac{1}{2} a_0 & n = 0
\end{cases},
$$
in which the coefficients $c_n$ are called the complex Fourier coefficients can be written in a closed form as
$$\implies c_n = \frac{1}{2\pi} \int_{-\pi}^{\pi}f(x)e^{-inx}dx.$$
As it is shown, the imaginary number you mentioned is somehow hidden inside the "$cosine$" and "$sine$" which comes out by using its expansion in terms of complex exponentials. Also, notice the difference of the range of summation in two formula!
For an orthonormal basis $\;\{\varphi_i\}\;$:
$$\langle f(x)\,,\,f(x)\rangle=\frac1{\pi}\int\limits_{-\pi}^{\pi}|f(x)|^2dx=\sum_{m=-\infty}^\infty\sum_{k=-\infty}^\infty c_m\overline{c_k}\langle \varphi_m\,,\,\varphi_k\rangle=\sum_{m=-\infty}^\infty|c_m|^2\\ \quad =\frac{a_0^2}{2}+\sum_{n=1}^{\infty} (a_n^2 +b_n^2)$$
where from the orthonormality conditions
$$\langle \varphi_m\,,\,\varphi_k\rangle=\begin{cases}1&,\;\;\;m=k\\{}\\0&,\;\;\;m\neq k\end{cases}.$$
this result is called Parseval's energy theorem (which is represented based on Fourier coefficients of two forms).
Furthermore, about the usage, based on the problem you can use suitable form to have more meaningful representation with easier calculations. For instance, the exponential representation has the same information as the other forms, however, it is preferred due to its less and simpler calculations. On the other hand, trigonometric form, can be easily visualized in terms of sum of cosine and sine functions.
As from trigonometric form, the Fourier series of an even function only
consists of cosine terms and an odd function only consists of sine terms.
From the signal processing viewpoint, by Fourier series representation, it is possible to write a periodic function in terms of "$\sin$" and "$\cos$"function from low to high frequency; here, $x = 2\pi \text{f}_0$ consists of the fundamental frequency, $\text{f}_0$, which signal can be written in terms of all its frequency components. A figure from Wiki is shown below. As it is noticeable from figure below, the low frequency components have the most essential part of the original periodic square wave; as the $n$ increases, means by adding higher frequencies, the Fourier series $\text{f}$ gets more and more similar to the original function, here $\text{F}$. Moreover, to reach the square shape, we need to add infinite terms to have the sudden changes or such instant discontinuities.
Reference for figure: https://en.wikipedia.org/wiki/Fourier_series
$\hskip2in$
Answer: The "only reason" to use complex numbers is that they are easier to handle, the drawback is they are more difficult to interpret.
Below I will show how you can make the transition from "a real Fourier transform" to the complex notation.
(forgive me if the expressions below are not correctly normalized)
The "real Fourier transform" looks like this:
$$a{\left(\omega\right)}=2\int_{0}^{\infty}x{\left(t\right)}\cos{\left(\omega t\right)}$$
$$b{\left(\omega\right)}=2\int_{0}^{\infty}x{\left(t\right)}\sin{\left(\omega t\right)}$$
In fact these are the coefficients of the Fourier series when the period becomes infinite.
The "inverse real Fourier transform" looks like this:
$$x{\left(t\right)}=\frac{1}{2\pi}\int_{0}^{\infty}\left(a{\left(\omega\right)}\cos{\left(\omega t\right)}+b{\left(\omega\right)}\sin{\left(\omega t\right)}\right)\ d\omega$$
This the Fourier series when the period becomes infinite.
The next expression nicely shows that you can interpret $\left(a{\left(\omega\right)}\cos{\left(\omega t\right)}+b{\left(\omega\right)}\sin{\left(\omega t\right)}\right)$ as a phase-shifted cosine:
$$x{\left(t\right)}=\frac{1}{2\pi}\int_{0}^{\infty}{c{\left(\omega\right)}\cos{\left(\omega t+\varphi\left(\omega\right)\right)}}\ d\omega$$
$$c{\left(\omega\right)}=\sqrt{{a{\left(\omega\right)}}^2+{b{\left(\omega\right)}}^2},\ \varphi\left(\omega\right)=atan2{\left(b{\left(\omega\right)},a{\left(\omega\right)}\right)}$$
Now we jump to complex numbers by replacing $cos()$ by its complex expression:
$$x{\left(t\right)}=\frac{1}{2\pi}\int_{0}^{\infty}{c{\left(\omega\right)}\frac{\left(e^{j\left(\omega t+\varphi\left(\omega\right)\right)}+e^{-j\left(\omega t+\varphi\left(\omega\right)\right)}\right)}{2}}\ d\omega$$
$$x{\left(t\right)}=\frac{1}{2\pi}\int_{-\infty}^{\infty}{c{\left(\omega\right)}\frac{\left(e^{j\left(\omega t+\varphi\left(\omega\right)\right)}\right)}{2}}\ d\omega$$
$$x{\left(t\right)}=\frac{1}{2\pi}\int_{-\infty}^{\infty}{c{\left(\omega\right)e^{j\varphi\left(\omega\right)}}\ \frac{e^{j\omega t}}{2}}\ d\omega$$
So the (inverse) Fourier transform expressed in complex numbers is just a formulation that is a lot easier to handle (to derive, integrate, sum, multiply) than an expression in sines and cosines.
It also allows squeezing two real numbers into one complex number: $a(\omega)$ and $b(\omega)$ are squeezed into one complex number $a(\omega) + b(\omega) i = c{\left(\omega\right)e^{j\varphi\left(\omega\right)}}$


How do I establish the differentiability of this function by definition?

Question: Given this function
$f(x) = (x^2 + 1)^{\sin(x)} $
How would I establish its differentiability over the entire function? I understand how to establish differentiability at a point $c$, by assessing the limit of the different quotient at $x = c$. But how would I establish the differentiability of the entire function?
Answer: Here's a plan:
(i) Prove that $x^2+1$ is differentiable.
(ii) Prove that if $\phi(x)$ is differentiable so is $\ln\phi(x)$.
(iii) Prove that $\sin x$ is differentiable.
(iv) Prove that if $\alpha(x)$ and $\beta(x)$ are differentiable so is $\alpha(x)\beta (x)$.
(v) Prove that if $\theta(x)$is differentiable then so is $\exp(\theta(x))$.
Conclude that your function, which is $\exp(\sin(x)\ln(x^2+1))$ is differentiable.
Comment: This is exactly what in my comment!
Comment: Not quite, you say $\ln(f(x))$ is differentiable by the product rule. But I was writing while you were commenting!
Answer: You shouldn't use the definition of derivative, instead you should use a tricky technique:
$\displaystyle f(x)=(1+x^2)^{\sin x} \implies \ln(f(x)) = \ln\left( (1+x^2)^{\sin x} \right) = \sin x \ln(1+x^2)$
$\displaystyle \implies \frac{d}{dx} \ln(f(x)) = \frac{d}{dx} \sin x \ln(1+x^2) \implies \frac{f'(x)}{f(x)} = \cos x \ln(1+x^2) + \sin x \frac{2x}{1+x^2}$
$\displaystyle f'(x)= f(x) \left( \cos x \ln(1+x^2) + \sin x \frac{2x}{1+x^2} \right) = (1+x^2)^{\sin x} \left( \cos x \ln(1+x^2) + \sin x \frac{2x}{1+x^2} \right)$
Comment: I understand that this is how I would find the derivative of g, but does this help establish that g is in fact a differentiable function?
Comment: You don't seem to have established the differentiability, just calculated what the value of $f'$ will be if it exists.
Comment: Let $g(x) = \ln(f(x))$, then as it can be shown $g$ is differentiable by the product rule. Since $h(x)=e^x$ is also differentiable, $(h \omicron g)(x)$ is differentiable by the chain rule. Hence $(h \omicron g)(x) = e^{\ln(f(x))} = f(x)$ is differentiable. Is it okay now?


The spectral projection of a positive operator

Question: Let $T_{n}\in B(H)$ be a positive operator on Hilbert space $H$ and $T_{n}\rightarrow 1_{H}$ in the strong operator topology. Now fix $\delta>0$ and let $P_{n}$ be the spectral projection of $T_{n}$ corresponding to the interval $[0, 1+\delta]$.

Can we verify $||T_{n}-1_{H}||\geq\delta P_{n}^{\perp}$?
Can we get $P_{n}\rightarrow 1_{H}$ in the strong operator topology?
Answer:
It is not clear what you mean by that inequality. Assuming you mean $\|T_n-1_H\|\,1_H$: Let $T_n=(1-1/n)\,1_H$. Then $P_n=1_H$ for all $n$. You have $\|T_n-1_H\|=1/n$, and so the inequality you want is
$$
\frac1n\,1_H\geq\delta P_N^\perp,
$$
which will fail for big enough $n$.
I think you can, but I would have to check my facts carefully. In any case, note that because all the operators involved are projections, WOT convergence implies SOT convergence.


Error Starting Xamarin Project

Question: i want to make a project with xamarin but in first place when i create a portable xamarin.forms blank project. I ran into this warnings and i do not know how to fix it

and when i update my visual it get even worst it's really making me angry
would you plz help me

and if you tell me any tutorials that i can use for learning xamarin i appreciate that .
Answer: Your current project target doesn't support some NuGet packages, so you must install the right Android SDK and Build Tools, and choose it in your project properties:

Download SDK and build tools

Change your project target:

Error Starting Xamarin Project


Why it is necessary to rejoin the domain after reverting the server from a snapshot?

Question: I am totally new to this, in my project i have seen that it's required to rejoin servers to the domain after reverting them from a snapshot.
Can anyone please explain why this is needed and how it will affect the server if this step is skipped?   Also can I safely install IIS without joining it to the domain.
Answer: The reason you need to rebind the server to the domain is most likely related to the 30 day password for computers.
When you restore a machine from snapshot, you're also reverting the password that machine knows and uses to authenticate to the domain. The domain will then refuse to service your computer. Re-adding it to the domain resets the password, and allows you to continue with business as usual.
Personally I would not install IIS until everything is 100%.
And most likely you want domain accounts for the services, which you can't set up until the machine has been joined.
Answer: You can also try to reset the computer account with the AD MMC. Or with Powershell
Reset-ComputerMachinePassword

or cmd
NETDOM RESETPWD /Server:<name of any domain controller> /UserD:<domain admin account> /PasswordD:<password>


Java Regular Expressions with Math Operators

Question: I have a conundrum, I need to separate a possible varied math string into separate entities to store in an ArrayList.
Input is read from a scanner could be any of the following.
Scanner input = new Scanner(System.in);
String read = input.nextLine();
ArrayList al = new ArrayList();

-5 + 10 //possible value of read
9--5   //possible value of read
-20* 10 //possible value of read

Basically I need to grab the first number and a potential negative sign, all ignoring leading or trailing whitespace and store it, then take the next character ignoring whitespace and store it (the operator of the problem), and then the next number with an optional negative sign, again ignoring whitespace.
I'm not very good with regex, and there's a lot of complicated possibilities here that I don't know how to tackle.
If I had to lay it out logically, I would say it thusly:
Get first non-whitespace character and end at last number digit that directly follows it.
Get next non-whitespace character
Get next non-whitespace character and end at last number digit that directly follows it.
Any pointers on syntax to accomplish that?
EDIT:  I'm not simply trying to evualuate the result of the expression in question, I need to break it up and store it in an ArrayList to manipulate later as part of a Fraction Class.
Comment: You should not be using regex for this, because it won't scale with nested arithmetic expressions.  Rather, you need a parser.
Comment: Do you have to use regex?  If not, check out this [answer](http://stackoverflow.com/a/36341949/4256677)
Answer: Not really elegant, but if you are looking for the Regex to grab numbers both positive and negative, you can use this regex
-?\d+|\*|\/|\+|\-
- looks for negative numbers
? makes it an optional search
\d looks for a digit
+ grabs everything until a whitespace
the pipes mean "or" so it will grab a positive negative number, or an *, or an /, or a + or a -


Find equation of tangent line

Question: Find the equation of the tangent line at parameter values $\theta=\pi/6$ and $\theta =5\pi/4$ to the cycloid given by
$$x(t)=r\theta-r\sin \theta$$
and
$$y(t)= r-r\cos \theta$$
with $\theta\in [0,2pi]$
At which parameter values is the tangent line to the cycloid given above horizontal? At
which values is it vertical? Write down the equations of all horizontal and vertical tangent lines.Is the cycloid concave up or concave down? Prove your answers.
Can anyone give me the basic information on how to solve these kind of problem. or suggest a website i can have a look at?
Answer: If you have a parametric equation $x=x(t)$ and $y=y(t)$, then
$$\frac{dy}{dx} = \frac{dy/dt}{dx/dt}.$$
In your case, you have $x(\theta)=r\theta-r\sin\theta$ and $y(\theta)=r-r\cos\theta$.  Therefore, $\dfrac{dx}{d\theta} = \ldots$ and $\dfrac{dy}{d\theta} = \ldots$, and hence
$$\frac{dy}{dx} = \frac{dy/d\theta}{dx/d\theta} = \ldots$$
Then you'll want to compute $\left.\dfrac{dy}{dx}\right|_{\theta=\pi/6}$ and $\left.\dfrac{dy}{dx}\right|_{\theta=5\pi/4}$ to get the slopes of the two tangent lines.  Once you have those, you'll be able to compute the tangent line equations like usual using point-slope form; in particular, your two tangent line equations will be
$$y=\left(\left.\dfrac{dy}{dx}\right|_{\theta=\pi/6}\right)(x-x(\pi/6)) + y(\pi/6)$$
and
$$y=\left(\left.\dfrac{dy}{dx}\right|_{\theta=5\pi/4}\right)(x-x(5\pi/4)) + y(5\pi/4)$$

To see where the tangent line is horizontal, you'll want to solve $\dfrac{dy}{d\theta}=0$.
To see where the tangent line is vertical, you'll want to solve $\dfrac{dx}{d\theta}=0$.
To see if the cycloid is concave up or down, you'll need to compute the second derivative:
$$\frac{d^2y}{dx^2} = \dfrac{d}{dx}\left(\frac{dy}{dx}\right) = \dfrac{\dfrac{d}{d\theta}\left(\dfrac{dy}{dx}\right)}{\dfrac{dx}{d\theta}}$$
and see where it's positive and/or negative.
I hope this provides you with enough information to at least start the problem.

Find equation of tangent line


How to map SQLSTATE values to their meaning?

Question: How do I map SQLSTATE values to their meaning in Java?
Comment: The concept of SQLSTATE isn't related to Java really. Do you mean using the JDBC API?
Answer: In the JDBC API, you can get the SQLSTATE of a database exception using SQLException.getSQLState().
Other Java APIs (for example JPA) don't know about the SQLSTATE as far as I know.
There is no API to get the meaning of a specific SQLSTATE. For that you will have to look up in the SQL specification, or even better in the database documentation, as it sometimes depends on the database type which SQLState you get for which exception.
Comment: No, I'm afraid not. Some databases have a central documentation for SQL states / exceptions codes and their meaning however - but typically that's online and not within the product itself.


Getting rid of Yellow black lines in Flutter

Question: Code:
  body: Column(
    children: [
      Expanded(
        child: StreamBuilder(
          stream: msg.snapshots(),
          builder: (context, snapshot) {
            return ListView.builder(
                itemCount: snapshot.data.documents.length,
                itemBuilder: (context, index) {
                  DocumentSnapshot doc = snapshot.data.documents[index];
                  if (doc["uid"] == widget.user.uid) {
                    isme = true;
                  } else {
                    isme = false;
                  }
                  return Row(
                       mainAxisAlignment: isme?MainAxisAlignment.end:MainAxisAlignment.start,
                      children: [

                        Column(

                          children: [
                            Container(
                                margin: EdgeInsets.all(8),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                color: isme ? Colors.red : Colors.blue,

                                ),

                                child: Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text("${doc['msg']}",style: TextStyle(fontSize: 20.0),),
                                      Text("${doc['Name']}",style: TextStyle(fontSize: 15.0,color: Colors.grey),),

                                    ],
                                  ),
                                )),

                          ],
                        ),
                      isme? Icon(Icons.delete,color: Colors.redAccent,):Text("")
                      ],
                    );
                });
          },
        ),
      ),
      //bottom textbar
      Padding(
        padding: const EdgeInsets.all(8),
        child: Row(
          children: [
            Expanded(
                child: CircleAvatar(
                    radius: 30,
                    backgroundImage: NetworkImage(widget.user.photoURL))),
            SizedBox(width: 5),
            Expanded(
              flex: 6,
              child: TextFormField(
                controller: chatmsg,
                minLines: 1,
                maxLines: 4,
                keyboardType: TextInputType.multiline,
                decoration: InputDecoration(
                    hintText: "Send message...",
                    border: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.blue),
                        borderRadius: BorderRadius.circular(20.0))),
              ),
            ),
            SizedBox(width: 5),
            Expanded(
                child: CircleAvatar(
              radius: 30,
              child: IconButton(
                  icon: Icon(
                    Icons.send,
                    color: Colors.white,
                  ),
                  onPressed: () {
                    sendmsg();
                    chatmsg.clear();
                  }),
              backgroundColor: Colors.green,
            ))
          ],
        ),
      )
    ],
  ),

Output
Answer: You just need to wrap your Column widget with Expanded inside your Row widget.
return Row(
  mainAxisAlignment: isme?MainAxisAlignment.end:MainAxisAlignment.start,
  children: [
    Expanded( // <------ HERE
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.all(8),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
              color: isme ? Colors.red : Colors.blue,
            ),
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("${doc['msg']}",style: TextStyle(fontSize: 20.0),),
                Text("${doc['Name']}",style: TextStyle(fontSize: 15.0,color: Colors.grey),),

                                ],
                              ),),
                            )),

                      ],
                    ),
                  isme? Icon(Icons.delete,color: Colors.redAccent,):Text("")
                  ],
                );
            });

Comment: Yes it worked, thanks but can u explain why?
Comment: I'm told the error message when you get an overflow points you at https://flutter.dev/docs/development/ui/layout . Even if it didn't, go read that.
Comment: The yellow & black lines show that your widget is getting overflowed. By using `Expanded` widget, you are specifying that your widget will fill to occupy the available space. If it gets overflowed, it will move the text to the next line.
Comment: Also, if you found this answer helpful, you can mark it as accepted or upvote it.


Find all files recursively by a certain date

Question: My site is compromised by an FTP brute attack and the cracker modified / created some files in my home directory.
Let's say the date of the malicious creation / modification is 2011-4-5 21:38:09. How can I find other files in public_html that is modified / created around that time?
Tried to search via Google but nothing helpful found. Can you please give me some examples? Like ls or find? Thanks!
Answer: You can:
touch -m -t 201104052138.08 /tmp/timestamp

find /dir -newer /tmp/timestamp

The initial touch creates a file with an mtime of one second before your required timestamp, and the find then uses that to find files modified (in terms of content) after that time.
You will also want to check permissions and group ownership.  You can't use the above technique to do that, since touch can only change the atime and the mtime.  So, you're better off determining what the correct permissions are, and just resetting them.  For example, if typically your web files are owned by root with group www-pub, and have permissions 0755 for directories and 0644 for files, you can use
find /dir \! -user root

to find files and directories not owned by root and
find /dir \! -group www-pub

to find files and directories not owned by www-pub
the -perm flag to find can be used to find files based on permissions, too, but you're better off just setting things to what they should be.
find /dir -exec chown root:www-pub {} \;
find /dir -type f -exec chmod 0644 {} \;
find /dir -type d -exec chmod 0755 {} \;

Answer: Use find
# find /home -ctime -2

That means "find files on /home that changed on last 48 hours". The 2 is multiplied by 24 hours so if you need 72 hours you use 3, and so on. If you need to find the files that changed at MORE than X days, use + instead of -.
You want to probably list the files so:
# find /home -ctime -2 -exec ls -l {} \;

Remember that ctime includes files created or changed in the last X hours.
Comment: Good point.  I keep forgetting that ctime is always updated whenever the file is modified.
Comment: Is that we always associate ctime with creation time, but it's change time, including the first change that is creation :)
Comment: I've cured myself of thinking of ctime as "create time", but forget that it's set by the kernel on any file op other than read().  I keep thinking it's only for inode modification (which it is, but mtime is part of the inode, which means that modifications update the inode, and therefore the ctime).  :)  One of these days, that will sink in.
Comment: @malcolm if it was easy it would be windows :P
Comment: started on unix myself, so Windows continues to look like a snarled mess to me.  Try programmatically determining the modification time of a hidden NTFS filestream without using third-party tools!  :)
Answer: find /dir -newerma "2011-xx-xx"

or you can look here
Answer: You can use the switch mtime to accomplish this task.
Answer: To find files on/around a specific date (as opposed to since a certain date) you will need to write a custom script. There are two options for this:

A script which finds the files
A script which tests a single file that you can embed into a find command

The first one is definitely more efficient. A very crude perl example would be:
#!/usr/bin/perl
use strict;
use warnings;

use POSIX();
use File::Find();

sub usage() { die "usage: finddate yyyy-mm-ddThh:mm:ss marginsecs dirs..." }

my( $mindate, $maxdate );
sub checkdate()
{
    my @data = stat($_);
    foreach my $idx ( 9, 10 ) # mtime and ctime
    {
        if( $data[$idx] >= $mindate && $data[$idx] <= $maxdate )
        {
            print "$File::Find::name\n";
            last;
        }
    }
}

# Main Program
{
    my $dtxt = shift(@ARGV);
    my $margin = shift(@ARGV);
    my $date;
    if( $dtxt =~ /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)$/ )
    {
        $date = POSIX::mktime( $6, $5, $4, $3, $2-1, $1-1900 );
    }
    else
    {
        usage();
    }
    $mindate = $date - $margin;
    $maxdate = $date + $margin;
    File::Find::find( \&checkdate, @ARGV );
}

Sample usage:
finddate.pl 2011-03-02T01:40:00 600 .

The single file test pretty much the same thing except:

it takes a single file instead of a list of directory arguments
The checkdate function takes a filename parameter instead of using $_
The checkdate function will return 1 if the check passes or 0 otherwise
The last line is now exit( !checkdate(@ARGV) );

You can then use this in a normal find command like
find dir -exec finddate.pl 2011-03-02T01:40:00 600 {} \; -print


Problem with refreshing GridLayout on Java Swing

Question: i have a problem with refreshing the values of my gridlayout.
So, i have a JPanel in a JFrame and in that JPanel , once i entered two values(one for rows and one for columns) and then by clicking on validate, i get a GridLayout with the previous values of JButtons.
So for exemple if I enter (2,2) i get a GridLayout of 4 JButtons and in each JButton i have an image.
So my problem here is, every time i wanna refresh the GridLayout by changing the values, it doesn't work, the GridLayout doesn't change, or if it change, the JButtons are inclickable.
I feel like every time i click on Validate, a new GridLayout is created on my JPanel, but the first one is still there.
I will upload two pictures, one with the normal functioning (entering values first time), and the second with the bug (entering new values).
Thanks guys.
First values
Second values
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.*;

    public class PagePrincipal extends JFrame implements ActionListener {

    JButton Valider;
    JTextField Columns;
    JTextField Rows;
    ArrayList<JButton> butt;

    public PagePrincipal(){

        getContentPane().setLayout(null); //this is not the panel that contains the GridLayout

        Columns = new JTextField();
        Columns.setBounds(219, 35, 197, 57);
        getContentPane().add(Columns);
        Columns.setColumns(10);

        Rows = new JTextField();
        Rows.setBounds(451, 35, 226, 57);
        getContentPane().add(Rows);
        Rows.setColumns(10);

        Valider = new JButton();
        Valider.setBackground(new Color(65, 179, 163));
        Valider.setForeground(Color.WHITE);
        Valider.setFont(new Font("Bookman Old Style", Font.BOLD, 20));
        Valider.setBounds(704, 15, 268, 81);
        Valider.setText("Validation");
        Valider.addActionListener(this);
        this.add(Valider);

        this.setResizable(true);
        this.setVisible(true);
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);

    }

    @Override

    public void actionPerformed(ActionEvent event) {

     if (event.getSource() == Valider) {
        int NbRows= Integer.parseInt(Rows.getText());
        int NbColumns=Integer.parseInt(Columns.getText());
        JButton button[] = new JButton[NbRows*NbColumns];
        butt = new ArrayList<>();

        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel botPanel = new JPanel(); //this is the panel that contains the GridLayout
        botPanel.setBounds(100, 200, 1000, 400);
        this.add(botPanel);

        botPanel.setLayout(new GridLayout(NbRows,NbColumns));

        for (int i=0; i<NbRows*NbColumns; i++){
                button[i]=new JButton();
                botPanel.add(button[i]);
                butt.add(button[i]);
        }
        this.setVisible(true);

    }

}
}

Comment: `setLayout(null);` That's the first thing that needs fixing. Always use layout managers.
Comment: That's the point -- you have already added this, `getContentPane().setLayout(null);`, but you *shouldn't* as it is the layout equivalent of shooting yourself in the foot. Is this your own code or is it found code?
Comment: You also will want to post a minimal code example, one with enough code to compile and illustrate your problem but without all the other code that only complicates and confuses us, a [mre]. Please read the link that explains this most useful tool.
Comment: I'm sorry but i did not understand, where do i have to add setLayout(null)?
Comment: Yes, this is my code.  getContentPane().setLayout(null) is for the first panel which contains my validate button ect. The panel that contains my buttons and the gridlayout is botPanel, i just changed the code so it can be more clear. Thanks!
Comment: You're still running into huge problems due to your use of null layout for the contentPane. No, it's not the component that you see the problem with, but it is contributing to the problem. Again, don't use null layouts. Nest JPanels, each using its own layout manager. Also, when changing the contents of any container, call `revalidate()` and `repaint()` on the container.
Answer: Again, avoid null layouts if at all possible, since they force you to create rigid, inflexible, hard to maintain GUI's that might work on one platform only. Instead, nest JPanels, each using its own layout to help create GUI's that look good, are flexible, extendable and that work.
Also, when changing components held within a container, call revalidate() and repaint() on the container after making the changes. For example, the following GUI:

Is created with the following code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

public class PagePrincipal2 extends JPanel {
    public static final int MAX_ROWS = 40;
    public static final int MAX_COLS = 12;
    private JButton validatorButton = new JButton("Validate");
    private JSpinner columnsSpinner = new JSpinner(new SpinnerNumberModel(2, 1, MAX_COLS, 1));
    private JSpinner rowsSpinner = new JSpinner(new SpinnerNumberModel(2, 1, MAX_ROWS, 1));
    private List<JButton> buttonsList = new ArrayList<>();
    private JPanel gridPanel = new JPanel();

    public PagePrincipal2() {
        JPanel topPanel = new JPanel();
        topPanel.add(new JLabel("Columns:"));
        topPanel.add(columnsSpinner);
        topPanel.add(Box.createHorizontalStrut(10));
        topPanel.add(new JLabel("Rows:"));
        topPanel.add(rowsSpinner);
        topPanel.add(Box.createHorizontalStrut(10));
        topPanel.add(validatorButton);

        JScrollPane scrollPane = new JScrollPane(gridPanel);

        int gridWidth = 1000;
        int gridHeight = 600;
        scrollPane.setPreferredSize(new Dimension(gridWidth, gridHeight));

        setLayout(new BorderLayout());
        add(topPanel, BorderLayout.PAGE_START);
        add(scrollPane, BorderLayout.CENTER);

        validatorButton.addActionListener(e -> validateGrid());
    }

    private void validateGrid() {
        int nbRows = (int) rowsSpinner.getValue();
        int nbColumns = (int) columnsSpinner.getValue();
        gridPanel.removeAll();
        buttonsList.clear();
        gridPanel.setLayout(new GridLayout(nbRows, nbColumns));
        for (int i = 0; i < nbRows * nbColumns; i++) {
            int column = i % nbColumns;
            int row = i / nbColumns;
            String text = String.format("[%02d, %02d]", column, row);
            JButton button = new JButton(text);
            button.addActionListener(e -> gridButtonAction(column, row));
            buttonsList.add(button);
            gridPanel.add(button);
        }
        gridPanel.revalidate();
        gridPanel.repaint();
    }

    private void gridButtonAction(int column, int row) {
        String message = String.format("Button pressed: [%02d, %02d]", column, row);
        String title = "Grid Button Press";
        int type = JOptionPane.INFORMATION_MESSAGE;
        JOptionPane.showMessageDialog(this, message, title, type);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            PagePrincipal2 mainPanel = new PagePrincipal2();

            JFrame frame = new JFrame("GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Note that the gridPanel, the one holding the buttons, is placed into a JScrollPane:
JScrollPane scrollPane = new JScrollPane(gridPanel);

Note that the main JPanel that holds everything is given a BorderLayout, and then 2 components are added, a topPanel JPanel that holds labels, buttons and fields for data input, added at the BorderLayout.PAGE_START, the top position, and the JScrollPane is added to the main JPanel at the BorderLayout.CENTER position:
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);

When the old buttons are removed from the gridPanel, and then new buttons are added, I will call revalidate() and repaint() on the gridPanel, the first method to get the layout managers to layout the new components, and the second method call to remove any dirty pixels that may be present:
private void validateGrid() {
    int nbRows = (int) rowsSpinner.getValue();
    int nbColumns = (int) columnsSpinner.getValue();
    gridPanel.removeAll();
    buttonsList.clear();
    gridPanel.setLayout(new GridLayout(nbRows, nbColumns));
    for (int i = 0; i < nbRows * nbColumns; i++) {
        int column = i % nbColumns;
        int row = i / nbColumns;
        String text = String.format("[%02d, %02d]", column, row);
        JButton button = new JButton(text);
        button.addActionListener(e -> gridButtonAction(column, row));
        buttonsList.add(button);
        gridPanel.add(button);
    }
    gridPanel.revalidate();
    gridPanel.repaint();
}


Sign of eigenvalues of a 2 x 2 matrix

Question: How can see what the signs of the eigenvalues of the matrix $\begin{pmatrix} 198 & 261 \\ 486 & 261 \end{pmatrix}$ are directly without calculating the roots of the characteristic polynomial? Both entries in the second diagonal aregreater than those in the main diagonal, can we use that?
Comment: What is the sign of the determinant? What do you learn from that about the signs of the eigenvalues? Note that you don't even need to calculate the determinant to answer this question, thanks to the special form of the second column.
Answer: We can use Descartes's sign-rule.
The characteristic polynomial has the form $$x^2+ax+b$$ with negative $a$ and negative $b$ because the trace is obviously positive and the determinant negative (Can easily be seen)
The signs are $+,-,-$
We have one sign-change, so we can conclude that exactly one root is positive.
If we replace $x$ by $-x$ , we get $$x^2-ax+b$$
Now, the signs are $+,+,-$
Again, we have one sign change , so we have exactly one negative root as well.
Comment: What do you mean by sign-change?
Comment: We look at the signs of the coefficients of the polynial (zeros are not considered). Descartes's rule states that the number of positive roots is either the number of sign changes or an even number smaller (considering multiplicity)
Answer: Hint: The Determinant is clearly negative.
Comment: @egreg You're right. I was too focused along the lines of "but what about non-diagonalisable matrices?" but apparently there are none with negative determinant.
Comment: @Arthur Yes, it shows there are two eigenvalues: a polynomial $x^2+ax+b$ with $b<0$ has positive determinant. Moreover, the roots must have different signs (Viète's formula).
Comment: @egreg plus the $\Delta$ must be greater than $4 \times 486 \times 261$ a priori.
Comment: @Arthur As I said, not when the determinant is negative.

Sign of eigenvalues of a 2 x 2 matrix


Is it possible to force redirection from PayPal to the website after successful payment?

Question: I'm using PayPal WPS with Ubertcart, and want to track the conversions using Adwords.
Is there any way to force true redirection back to the website within Ubercart?
The redirection in PayPal settings is already set to "On", however the users are still being asked to click to go back, or proceed to their PayPal settings page.
This results in losing the conversions.
Any ideas how to force the clients back directly to the website via Ubercart / custom module?
Thanks!
Answer: The answer is unfortunately no.
PayPal will always display this as an option to the client, so you can't force the redirection back after the payment has been completed.


How do I add a model binder in asp.net mvc from a method called by Application_Start?

Question: I have a modelbinder being added during Application_Start like this:
    protected void Application_Start()
    {
        XmlConfigurator.Configure();

        // Model Binding
        ModelBinders.Binders.Add(typeof(SessionUser), new SessionUserModelBinder());
        ////////////////

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

I would like the Application_Start method to call a separate method to add my custom model binder to the list like:
namespace NewNameSpace
{
    public class TestStartClass
    {
        public static void AppStart()
        {
            ModelBinders.Binders.Add(typeof(SessionUser), new SessionUserModelBinder());
        }
    }
}

The problem is that when I try this, Binder in ModelBinders.Binder returns an error which says:
Error 1 'System.Web.Mvc.ModelBinders' does not contain a definition for 'Binder'

I am using System.Web.Mvc. What am I missing that's preventing this from working?
Comment: Are you using `ModelBinders.Binder` (which doesn't exist) instead of `ModelBinders.Binders` somewhere? The error message suggests you are.
Answer: It looks like you must have a typo in your code.  The error message is saying you are trying to reference a class member like ModelBinders.Binder.  You need that to be ModelBinders.Binders.Add().
ModelBinders.Binders Property MSDN Reference
Answer: The error message says ModelBinders does not have a Binder property and that's correct.  It has a Binders property (note the s).


Including Custom Classes

Question: I've just installed Symfony 2 and I'm looking at including my own classes into my project, but am having trouble getting the results I am after.
I'd like a controller to be able to call "MyClass.php" and run functions from it without the use of includes. After a bit of searching, it seems that classes need to be placed within a specific folder for them to be picked up automatically and used by the 'app'. I currently believe it to be the "lib" folder within the project bundle root.
At the moment my project sits within src/Bundle/ProjectBundle.
I have tried storing the Test class within Test.php inside ProjectBundle/lib, and have tried naming it 'Test.php' and Test.class.php, but my controller is still unable to find the file/class.
Where do I place my class files?
How should I name my class files? (aside from the standard naming conventions)
Am I barking up the wrong tree completely?
edit: The class to be called.
<?php
class Test
{
    public function callMe()
    {
        return "FUNCTION 1 SUCCESSFULLY CALLED";
    }
}
?>

Answer: You can do the following. Place the class in a sub-directory of your project and in the controller use use to register the namespace like this:
// the last part is the class name you want to include
use Vendor\BundleNameBundle\Utility\Factory;

The class would be located in: src/Vendor/BundleNameBundle/Utility/Factory.php.
Comment: You have to set the namespace in your class `test` as well - right before `class Test`. According to my example it would be: `namespace Vendor\BundleNameBundle\Utility;`
Comment: Thanks so much. Got it all up and running mate thanks to you.
Comment: It's a step closer, but now I'm getting "It's found the file, but there is a problem with the class definition"

i've updated the post to contain the class definition.

Including Custom Classes


Change defaultCloseOperation() in Netbeans?

Question: I need to set to open a different JFrame as the defaultCloseOperation of the JFrame that I'm currently working.
Can I do that in Netbeans ?
Comment: Add a `WindowListener` to the first frame that makes the second frame and use `DO_NOTHING_ON_CLOSE`.
Comment: sidenote - Netbeans is just an IDE. your question is about java programming language and not restricted to IDE scope.
Comment: yeah, I'll remove that tag for you.
Answer: http://docs.oracle.com/javase/7/docs/api/java/awt/event/WindowListener.html
Add a WindowListener to the first frame and when it closes, make the seconds frame and close this first frame. Then set defaultCloseOperation to DO_NOTHING_ON_CLOSE.
Non-working code just so you get the idea:
public class FirstFrame extends JFrame implements WindowListener {
    (other stuff)
    @Override
    public void windowClosed(WindowEvent e) {
        //make second frame
        dispose();
    }
}

Comment: Thanks for the response ! I added implements WindowListener part to code and set defaultCloseOperation to DO_NOTHING_ON_CLOSE but it didn't work the new NewFrame().setVisible(true) inside windowClosed method
Comment: @Override
    public void windowClosed(WindowEvent e) {
        //make second frame
        dispose();
        new NewFrame().setVisible(true);
    }
Comment: @HarinLakmal so the new frame just doesn't appear?
Comment: @HarinLakmal try putting a `System.out.println` in the `windowClosed`.  Does it print?
Comment: I tried that too. More click on the close button Frame remains like solid rock nothing happens.
Comment: In FirstFrame's constructor, add `addWindowListener(this);`
Comment: added implements WindowListener to NewFrame class & created addWindowListener(this); too


C++ Memory Leak new operator

Question: I need to identify which objects are destroyed AND if there is any memory leaks on this code.
  void myfunc()
  {
    Photo a(1, 2);
    Photo* pt = new Photo(2, 3);
    throw runtime_error("to test the exception");
  }

My answer was
the object is destroyed after the function end
, by automatically calling the destructor of the class Photo.
There is a memory leak.
We did not delete pt that is dynamically allocated with new operator.
So we need to add delete pt;  at the end of function.
Is my anwer is correct?
Comment: @chris The question is very oddly worded but I think the answer is right and your comment is wrong.
Comment: @MooingDuck, I was most specifically talking about putting `delete pt;` at the end. AFAIK, that won't execute when an exception is thrown before that line.
Comment: Your answer is wrong. This is why smart pointers were invented.
Comment: @chris good call, I overlooked that part
Comment: Oh smart pointer... can anybody show the example with the smart pointer?
Comment: @asd213sasdd2254121: `std::unique_ptr pt(new Photo(2, 3));`
Answer: You are wrong. try this:
void myfunc()
{
   Photo a(1, 2);
   Photo* pt = new Photo(2, 3);
   throw runtime_error("to test the exception");
   delete pt;
}

compile and run under valgrind. you will get a leak - delete pt; is never reached.
Comment: Then should I put delete pt; before the throw line??
Comment: If you must use `delete` here you would need to place it before the throw in order for it to be executed. If you don't need to use `delete` use smart pointers (`std::unique_ptr`). Scope Based Resource Management (SBRM) wants to be your friend.
Comment: no. no. that will not help in the general case. you should use RAII - that is, smart pointers, as chris and Captain Obvlious noted in their comments. if that's impossible, use `try` and `catch (...) { delete pt; throw; }`.
Comment: @CaptainObvlious, I've never heard that specific term, but I do like it better than RAII. It's a shame the first thing that comes up when I search SBRM is The Santa Barbara Rescue Mission.
Comment: Apparently I have a word association problem today...that should read Scope _Bound_ Resource Management. SBRM and RAII are the same thing. Member variables are scoped to the class they are declared in just as local variables are scoped to a function. This is called automatic storage duration since they are automatically created and destroyed. Resources which are allocated and release through `new` and `delete have dynamic storage duration and need to be managed manually.
Comment: @CaptainOblivious: Umm, smart pointers are there so that resources with dynamic storage durations don't need to be managed manually.

C++ Memory Leak new operator


Docker ngix/traefik 301 redirecting http to https in localhost

Question: This is a follow up to Turn off https in Docker with some more information. I still haven't figured it out.
I asked in the Docker slack group and they are convinced it's coming from the nginx or traefik config.
In Firefox there is a SSL_ERROR_UNRECOGNIZED_NAME_ALERT error, and in Chrome it's the similar ERR_SSL_UNRECOGNIZED_NAME_ALERT. I'm not finding out much about either of those by searching.
My nginx config:
user                                    nginx;
daemon                                  off;
worker_processes                        auto;
error_log                               /proc/self/fd/2 debug;

events {
  worker_connections                  1024;
  multi_accept                        on;
}

http {
  include                             /etc/nginx/mime.types;
  default_type                        application/octet-stream;
  fastcgi_buffers                     16 32k;
  fastcgi_buffer_size                 32k;
  fastcgi_intercept_errors            on;
  fastcgi_read_timeout                900;
  include                             fastcgi_params;
  access_log                          /proc/self/fd/1;
  port_in_redirect                    off;
  send_timeout                        600;
  sendfile                            on;
  client_body_timeout                 600;
  client_header_timeout               600;
  client_max_body_size                256M;
  client_body_buffer_size             16K;
  client_header_buffer_size           4K;
  large_client_header_buffers         8 16K;
  keepalive_timeout                   60;
  keepalive_requests                  100;
  reset_timedout_connection           off;
  tcp_nodelay                         on;
  tcp_nopush                          on;
  server_tokens                       off;
  upload_progress                     uploads 1m;

  gzip                                on;
  gzip_buffers                        16 8k;
  gzip_comp_level                     2;
  gzip_http_version                   1.1;
  gzip_min_length                     20;
  gzip_types                          text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/x-icon application/vnd.ms-fonto
  gzip_vary                           on;
  gzip_proxied                        any;
  gzip_disable                        msie6;

  add_header                          X-XSS-Protection '1; mode=block';
  add_header                          X-Frame-Options SAMEORIGIN;
  add_header                          X-Content-Type-Options nosniff;

  map $http_x_forwarded_proto $fastcgi_https {
      default $https;
      http '';
      https on;
  }

  map $uri $no_slash_uri {
      ~^/(?<no_slash>.*)$ $no_slash;
  }

  upstream backend {
      server php:9000;
  }

  include conf.d/*.conf;
}

My nginx.conf.default:
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

My docker-compose.yml is unchanged from the previous question.
I've looked for anthing resembling traefik config and can't find anything.
Things I've tried so far:

swapping things round inside the map $http_x_forwarded_proto $fastcgi_https i.e. default $http; http on; https '';
deleting that whole map block
removing the references to https in line 140 of docker-compose.yml
removing line 143 from docker-compose.yml
removing line 147 from docker-compose.yml
creating a self-signed certificate for localhost
sackcloth and ashes

I'm genuinely at a loss, any help appreciated.
Comment: Judging by the logs from the previous post, redirect comes from `index.php`. If it was `nginx` or `traefik` the request wouldn't come to PHP service, i.e. you wouldn't have got this line in logs: `php_1      | 172.29.0.8 -  13/Apr/2021:14:51:24 +0000 "GET /index.php" 301`
Comment: So you have the issue when using the simple Nginx configuration you posted here (HTTP to HTTPS), with only index.html and HTTP server? Can you paste the logs in this case, as in your previous post there is PHP involved? What you want is to disable HTTPS, and so use HTTP only on your localhost right?
Comment: Do you accept an answer if you can get it working with https with a locally signed cert? if so i can post a answer
Comment: What ever happened to creating a [minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve)? :-)  It seems like there is plenty of room for simplification as a first step to tracing problems here.  The redirect seems to come from nginx or PHP, my guess is maybe Drupal (?) redirecting http to https?  What does `index.php` look like?  If you add a plain text `index.html` can you access that? Administrative request - please don't create duplicate questions. Now this one has the bounty you should close the first and copy all the info from there here.
Comment: Sorry folks, should have mentioned this is Drupal, not a plain HTML page.
Comment: @Mtxz yes you're correct. I want to disable https. I'm setting up on a new laptop and it was http on the old laptop and for all my colleagues.
Comment: @mahen3d yes I will, definitely.
Comment: @DerekJohnson do you also get redirected when using a simple HTML file? and the Nginx config you posted (:80 only)? If so, I would first try to clear browser cache or try with another browser: they can cache the redirection, and so remember that once your domain redirected from HTTP to HTTPS (mostly cause of PHP) and so continue to do so. If not, we'll continue investigate :)
Comment: @Mtxz the redirect occurs after clearning the browser cache. It does not happen when I put a test html file in docroot e.g. localhost/test.html
Comment: So the redirect comes from PHP. What are you using as PHP scripts? Simple scripts? Framework? We need details about the PHP side, as it seems the redirect comes from it.
Comment: @Mtxz it's Drupal
Comment: Ok. Do you have any htaccess file? Is the base_url of drupal HTTP? Is there any in-database URL configured with HTTPS?
Comment: Check your drupal settings.php to see if any URL is hardcoded with HTTPS, or that the HTTPS configuration is ON.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/231505/discussion-between-derek-johnson-and-mtxz).
Answer: After more tests from OP, and other user's comments: it seemed that the redirection  (HTTP to HTTPS) was occurring after Nginx handled the request.
OP also tested using a single index.html file and was not redirected to HTTPS: confirming that the redirection came from PHP (or at least not from Nginx).
The next steps were to look into Drupal configuration, and/or htaccess configuration. OP changed some Drupal configuration (about redirections), and successfully got the drupal setup page working with HTTP only.
Best in those case is always to try to pin-point the where the issue come from:

Make your Nginx configuration minimal: simple index.html
Clear browser cache regularly: they sometimes cache the redirection
Check/remove htaccess to see if behavior changes
Finally, if Nginx is "clean" from any issue, and htaccess doesn't seem to be the issue: it's mostly "after", so the issue may come from "to who Nginx is sending the request"
From "large" frameworks/CMS like Drupal, Woocommerce, Laravel... Redirection is usually handled "easily" from configuration files or DB settings.
When you have custom code handling redirections: it'll need debugging


Como ordenar um data.frame por colunas no R?

Question: Suponha um data.frame com valores numéricos e strings:
 set.seed(1)
dados <- data.frame(w=rep(c("A", "B"), 2), x= rep(c("D", "C"), 2), y= rnorm(4), z=rnorm(4),
                    stringsAsFactors=FALSE)
dados
 w x          y          z
1 A D -0.6264538  0.3295078
2 B C  0.1836433 -0.8204684
3 A D -0.8356286  0.4874291
4 B C  1.5952808  0.7383247

Como faço para ordenar o data.frame por uma coluna? E como faço para ordenar com mais de uma coluna, e cada uma com ordens diferentes (algumas em ordem crescente, outras em ordem decrescente)?
Answer: Pode também utilizar o pacote plyr para a ordenação.
library(plyr)
arrange(dados,desc(z))
  w x          y          z
1 B C  1.5952808  0.7383247
2 A D -0.8356286  0.4874291
3 A D -0.6264538  0.3295078
4 B C  0.1836433 -0.8204684

O arrange também funciona para texto sem precisar da função auxiliar xtfrm
arrange(dados,desc(w),z)
  w x          y          z
1 B C  0.1836433 -0.8204684
2 B C  1.5952808  0.7383247
3 A D -0.6264538  0.3295078
4 A D -0.8356286  0.4874291

Outra opção interessante é usar o pacote sqldf. O default de sql é ordem ascendente.
library(sqldf)
sqldf("SELECT w,x,y,z
      FROM dados
      Order BY x, desc y")
  w x          y          z
1 B C  1.5952808  0.7383247
2 B C  0.1836433 -0.8204684
3 A D -0.6264538  0.3295078
4 A D -0.8356286  0.4874291

Answer: Da para fazer isso direto no order, basta informar multiplos parâmetros.
set.seed(1)
dados <- data.frame(w=rep(c("A", "B"), 2), x= rep(c("D", "C"), 2), y= rnorm(4), z=rnorm(4),
                    stringsAsFactors=FALSE)
dados[order(dados$w, dados$x, dados$y, decreasing=c(TRUE, FALSE, TRUE)), ] # No caso, ordena de acordo por w em ordem alfabética inversa, x em ordem alfabética e y em ordem decrescente. Se quiser que tudo seja na mesma ordem, basta um TRUE ou FALSE, que valerá para todos.

  w x          y          z
4 B C  1.5952808  0.7383247
2 B C  0.1836433 -0.8204684
1 A D -0.6264538  0.3295078
3 A D -0.8356286  0.4874291

Comment: Para você ver como sempre dá para aprender mesmo em coisas simples, não sabia que o `decreasing` aceitava vetores!
Answer: Você pode usar a função order. Para ordenar o data.frame pela coluna z em ordem decrescente, por exemplo:
dados[order(dados$z, decreasing=TRUE),]
  w x          y          z
4 B C  1.5952808  0.7383247
3 A D -0.8356286  0.4874291
1 A D -0.6264538  0.3295078
2 B C  0.1836433 -0.8204684

Para ordenar de maneira diferente para cada coluna, há dois pontos a serem observados. Se as colunas forem numéricas, você pode colocar um menos antes do vetor para inverter a direção desta coluna, por exemplo, order(dados$z, -dados$y, decreasing=TRUE) organiza de ordem decrescente em z e depois em ordem crescente em y (que neste caso não faz diferença pois não há empates em z).
Já com colunas de caracteres é preciso utilizar uma função auxiliar xtfrm. Por exemplo, para ordenar os dados de forma "decrescente" (alfabeticamente) no vetor w e, após, crescente no vetor z:
dados[order(-xtfrm(dados$w), dados$z),]
  w x          y          z
2 B C  0.1836433 -0.8204684
4 B C  1.5952808  0.7383247
1 A D -0.6264538  0.3295078
3 A D -0.8356286  0.4874291


Can only access asp.net app on the server

Question: I'm trying to get an asp.net application set up on IIS on a Windows Server 2008 machine. I can hit the app from localhost, no problem. I can access the app using the server's domain name locally on the server but not from another machine on the network.
when trying to access the application from another PC across the network it just times out and and says
"The server at x.xxx.x.xxx is taking too long to respond"
<code>http://xxx.xxx.x.xxx:[some port number]/MyApplicationWebAppName
</code>
Looking at the event log I'm getting the following errors? I've goggled these and its talking about sharepoint which is installed on the server but this shouldn;t stop me being able to access the app across the network

WebHost failed to process a request.
   Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/33711845
   Exception: System.ServiceModel.ServiceActivationException: The service '/SecurityTokenServiceApplication/securitytoken.svc' cannot be activated due to an exception during compilation.  The exception message is: Exception has been thrown by the target of an invocation.. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: The farm is unavailable.
Comment: Sounds like a firewall issue. Do you know if your network allows HTTP traffic to flow inside of it?
Comment: Not 100% sure how would I check?
Comment: Ok cool I've just found thats the issue, thanks for the pointer :-) If you post it as an answer I will accept it, it was the sharepoint permission on the firewall which were the issue, HTTP traffic was allowed
Comment: Glad that helped! Reposting it now.
Answer: Sounds like a firewall issue. Do you know if your network allows HTTP traffic to flow inside of it?