Puzzle with some sort of math meaning to it?

Question: This picture was posted in the math building at my college! So there has to be some sort of math puzzle/meaning behind it. Here is the picture of the puzzle and the instructions.
I have tried this several times and still cannot get it.

Here are the instructions

Let me know what you guys come up with!
Thanks!
Comment: By brute force computation, I have confirmed @fretty's answer: $\text{start} \to A \to B \to C \to D \to E \to F \to K \to T \to
V \to \text{star} \to \text{frown} \to V \to T \to K \to F \to
E \to D \to I \to J \to R \to S \to Z \to Y \to X \to W \to O \to
L \to G \to B \to A \to G \to L \to O \to W \to X \to Y \to Z \to
\text{frown} \to \text{star} \to \text{goal}
$.
Comment: It would be a long wait until August, 2330 to get the answer.
Comment: For a systematic approac, you might convert this to a "simpler" puzzle with twice as many nodes (say $X$ is replaced with $X_r$ and $X_y$) and an arrow $X_r\to Y_y$ if there is a red arrow $X\to Y$ and an arrow $X_y\to Y_r$ if there is a yellow arrow $X\to Y$.
Comment: I think this puzzle is impossible...if you trace back from the goal then you find you must get to $L$ in order to solve. However tracing back further you find that to get to $L$ you must have got to $L$ earlier.
Comment: I vaguely remember seeing something like this graph, but it was for testing divisibility by (some certain number). Does anyone now what I'm referencing/forgetting?
Comment: @fretty:  but on the return to $L$ you are on the other color arrow, so it is not obvious it is a problem.
Comment: Good point, I have found the optimal solution then, it is ABCDEFKTV(Z1)(Z2)VTKFEDIJRSZYXWOLGBAGLOWXYZ(Z1)(Z2)
Comment: Found this by tracing backwards and noticing that only one route doesn't land you in a loop...or in an uneccessary repetition of letter/colour pair
Comment: @fretty do you know what the author means when he says... "Can you find the least amount of edges needed to solve the maze?"
Comment: Isn't it obvious? He means to find the shortest route through the maze...
Comment: @fretty He calls them edges, so that was kind of confusing. He could have simply said, "Find the shortest route".
Comment: Well I have no bearing on that, I don't know the guy that made the puzzle...
Answer: Hint:  no math magic, just informed trial and error.  These are often easier if you work backwards from the goal.  You have only one path for the first eight steps backward, then a guess.  One of the options brings you back to where you were, but having arrived from the other color.  That should give you confidence that it is the correct path, as constructors of puzzles like things like that.  I find a solution that has $40$ steps.
In reverse, I get $\def\ot{\gets}\text{GOAL}\ot * \ot \otimes\ot Z\ot Y\ot X\ot W\ot O\ot L\ \\
\ot G \ot A \ot B \ot G \ot L \ot O \ot W \ot X \ot Y\\
\ot Z \ot S \ot R \ot J \ot I \ot D \ot E \ot F \ot K \\
\ot T \ot V \ot \otimes \ot * \ot V \ot T \ot K \ot F \\\ot E \ot D \ot C \ot B \ot A \ot START$
I suspect this is the intended solution because of the two big loops retracing steps.
Comment: How can you go from C->D->I
Comment: @fretty:  good point.  Working on it.
Comment: @RossMillikan did you come up with anything?
Comment: @Christopher23:  Yes I have updated it.  My solution agrees with fretty's.
Comment: No force (brute or other) is needed to see this is the shortest solution. Up to the first $L$ there is no choice. Then the option $L\gets M\gets P\gets O\gets L$ is useless (parity preserved), so the journey continues as indicated to the first $K$. There continuing to $J$ would again make a parity-preserving loop, so the sequel up to $D$ is necessary. From there the $4$ step endgame is clearly optimal. Other slutions (visiting $N,Q,H$) do exist.


Validação de dados no JavaScript

Question: Eu criei alguns campos na minha pagina e estou tentando fazer a validação desses dados usando js, porem por algum motivo ele não está funcionando, fiz apenas um teste no primeiro campo.
Segue o meu código no html e js, o name=contrato está sendo usado para retornar os dados que foram inseridos nos campos do formulário, o id=estilo esta sendo usado para formatar o formulário no css, mas esses dados acredito eu n fazem diferença nesse erro. Agora o onsubmit="return validar(this)" está sendo usado para chamar a função que foi criado no meu javascript.

function validar(formDados) {
    if (formDados.primeiro.value == "") {
        alert("Digite um valor para o campo \"Nome\".");
        formDados.primeiro.focus();
        return false;
    }
}

function enviar() {

    var primeiro = document.contrato.primeiro.value;
    var segundo = document.contrato.segundo.value;
    var terceiro = document.contrato.terceiro.value;
    var quarto = document.contrato.quarto.value;
    var quinto = document.contrato.quinto.value;
    var sexto = document.contrato.sexto.value;
    var text_area = document.contrato.comentario.value;
    var valor = document.contrato.oitavo.value;

    //retornando o dia e o ano atual
    var dNow = new Date();
    var localdate = "Jundiai, " + dNow.getDate() + " de maio de " + dNow.getFullYear();

    //trocando o ponto pela virgula
    var troca = parseFloat(valor.replace(".", ","));

    //calculando o valor do acrescimo de 10%
    valor = (10 / 100 * troca + troca);

    //usando um 'modo' que o valor retornado fique no formato BR
    pt_br = Number(valor).toLocaleString('pt-BR', { style: "currency", currency: "BRL" });

    //chamando a tag 'estilo' do css
    var form = document.getElementById("estilo");

    //escondendo o formulario, pois ele apareceria 2x
    form.style.visibility = "hidden";

    //pegando id do body da pagina para manipula-lo
    var corpo = document.getElementById('body');

    //criando uma nova div no body para armazenar os dados retornados
    var div = document.createElement("div");

    //atribuindo um novo id=estilo para a div, assim deixando-a formatada
    div.setAttribute('id', 'estilo')

    //adicionando os dados retornados na pagina
    div.innerHTML =
        `${localdate}

         CONTRATANTE (Tomador(a) de Serviços): Sr(a) ${primeiro}

         Brasileiro(a), residente e domiciliado(a) na Rua: ${segundo}

         N° ${terceiro}

         Cidade de: ${quarto}

         Estado: ${quinto}

         CPF ou CNPJ: ${sexto}

         Referente a Prestação de Serviços do tipo: ${text_area}

         Valor: R$ ${pt_br}`

    //adicionando a div criada ao body da pagina
    body.appendChild(div);

    return true
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="css/main.css">

    <form name="contrato" id="estilo"  onsubmit="return validar(this)">

                Contrato de Serviços

                CONTRATANTE (Tomador(a) de Serviços): Sr(a).
                <input type="text" name="primeiro">

                Brasileiro(a), residente e domiciliado(a) na Rua
                <input type="text" name="segundo">

                N° <input type="number" name="terceiro">

                Cidade de: <input type="text" id="quarto">

                Estado: <input type="text" name="quinto">

                CPF ou CNPJ: <input type="text" name="sexto">

Referente a Prestação de Serviços do tipo:

                    <textarea name="comentario" rows="10" cols="40"></textarea>

                Valor: <input type="number" name="oitavo">

            <input type="button" name="" id="bt" value="enviar" onclick="enviar();">

    </form>

Comment: Fundamental nestes casos reduzir o problema a um [exemplo mínimo, completo e verificável](https://pt.stackoverflow.com/help/minimal-reproducible-example) antes de postar.
Comment: Ola @Giovanni, Bem vindo ao SOpt, não esqueça de fazer nosso [Tour] para entender como a comunidade funciona =D
Answer: Pelo teste que eu fiz está tudo funcionando. O único detalhe é que seu botão para envio de formulário não é do tipo submit. Esse botão também chama uma função chamada enviar, caso essa função esteja fazendo o submit via JavaScript, então de fato da maneira que você fez não irá funcionar, pois o evento onsubmit disparado pelo JS não é capturado. Se for esse o caso, chame a função de validação dentro da função enviar.

function validar(formDados) {
    if (formDados.primeiro.value == "") {
        alert("Digite um valor para o campo \"Nome\".");
        formDados.primeiro.focus();
        return false;
    }
}
<form name="contrato" id="estilo" onsubmit="return validar(this)">

      Contrato de Serviços

      CONTRATANTE (Tomador(a) de Serviços): Sr(a).
      <input type="text" name="primeiro">

      Brasileiro(a), residente e domiciliado(a) na Rua
      <input type="text" name="segundo">

      N° <input type="number" name="terceiro">

      Cidade de: <input type="text" id="quarto">

      Estado: <input type="text" name="quinto">

      CPF ou CNPJ: <input type="text" name="sexto">

Referente a Prestação de Serviços do tipo:

        <textarea name="comentario" rows="10" cols="40"></textarea>

      Valor: <input type="number" name="oitavo">

    <input type="submit" name="" id="bt" value="enviar">

</form>
Answer: O código esta funcionando, o problema e que seu botão esta como button e não submit e esta tentando chamar uma função enviar() que no código que você publicou não esta definida
Após atualização da pergunta
O seu input[type='button'] foi alterado para input[type='submit'] e o atributo onclick="enviar();" foi removido, deixando seu input como mostrado abaixo:
<input type="submit" name="" id="bt" value="enviar">

Alterei a função que esta sendo chamada no onsubmit do form para onsubmit="return enviar(this)".
Sua função validar() agora retorna true caso o formulário esteja válido e false caso ele seja inválido.
Sua função enviar() agora recebe o formulário como parâmetro e a primeira coisa que ela faz é executar a função validar() e verificar o resultado retornado para saber se deve continuar a execução.
No final da função enviar() você estava retornando true isso vai fazer o formulário ser enviado, como você não definiu os atributos method="" e o action="" ele vai enviar para a url atual por get, ou seja, a pagina será recarregada e sua url ficará +/- assim: http://minhapagina.com/?primeiro=abc&segundo=dfg..... Agora olhando sua função enviar() me parece que esse não é seu objetivo, pois você esta adicionando elementos na tela, então eu troquei seu return true no final da função por return false para o formulário não ser enviado.
Como nesse dentro da sua função enviar() você tem acesso aos dados do formulário, você pode utilizar uma outra forma de envio se assim desejar, como por exemplo enviar os dados por ajax.

Como as coisas estão executando agora?
  Quando o usuário clicar no botão enviar o evento onsubmit será disparado, isso porque o botão agora e do tipo input[type='submit']:

O evento onsubmit irá chamar a função enviar();
A função enviar() vai checar se o formulário foi bem preenchido (esta válido) para isso ela vai utilizar a sua função validar()

Se não (não foi bem preenchido): para a execução retornando false para o evento onsubmit e o formulário não será enviado.
Se sim (foi bem preenchido): continua a execução do seu script normalmente.

Se tudo ocorrer bem seu script vai adicionar elementos na tela e vai retornar false para o evento onsubmit para o formulário não ser enviado e a pagina não ser recarregada (como expliquei acima).

function validar( formDados ) {
    if (formDados.primeiro.value == "") {
        alert("Digite um valor para o campo \"Nome\".");
        formDados.primeiro.focus();
        return false;
/// ;          ^ indica que a validação falhou
    }

    return true;
/// ;      ^ indica que o formulario foi validado
}

/// ; Mudei a função para ela receber o elemento form
function enviar( formDados ) {

    /// ; O primeiro passo aqui dentro será executar a
    /// ; função validar, pegar o seu retorno e verificar
    /// ; se esta função pode continuar a executar

    if( !validar( formDados ) )
    {
        /// ; Validação falhou, para a execução.
        return false;
    }

    /// ; Continua com a execução do seu codigo;

    var primeiro = formDados.primeiro.value;
    var segundo = formDados.segundo.value;
    var terceiro = formDados.terceiro.value;
    var quarto = formDados.quarto.value;
    var quinto = formDados.quinto.value;
    var sexto = formDados.sexto.value;
    var text_area = formDados.comentario.value;
    var valor = formDados.oitavo.value;

    //retornando o dia e o ano atual
    var dNow = new Date();
    var localdate = "Jundiai, " + dNow.getDate() + " de maio de " + dNow.getFullYear();

    //trocando o ponto pela virgula
    var troca = parseFloat(valor.replace(".", ","));

    //calculando o valor do acrescimo de 10%
    valor = (10 / 100 * troca + troca);

    //usando um 'modo' que o valor retornado fique no formato BR
    pt_br = Number(valor).toLocaleString('pt-BR', { style: "currency", currency: "BRL" });

    //chamando a tag 'estilo' do css
    var form = document.getElementById("estilo");

    //escondendo o formulario, pois ele apareceria 2x
    form.style.visibility = "hidden";

    //pegando id do body da pagina para manipula-lo
    var corpo = document.getElementById('body');

    //criando uma nova div no body para armazenar os dados retornados
    var div = document.createElement("div");

    //atribuindo um novo id=estilo para a div, assim deixando-a formatada
    div.setAttribute('id', 'estilo')

    //adicionando os dados retornados na pagina
    div.innerHTML =
        `${localdate}

         CONTRATANTE (Tomador(a) de Serviços): Sr(a) ${primeiro}

         Brasileiro(a), residente e domiciliado(a) na Rua: ${segundo}

         N° ${terceiro}

         Cidade de: ${quarto}

         Estado: ${quinto}

         CPF ou CNPJ: ${sexto}

         Referente a Prestação de Serviços do tipo: ${text_area}

         Valor: R$ ${pt_br}`

    //adicionando a div criada ao body da pagina
    body.appendChild(div);

    return false;
    // return true;
    /// ; Se retornar true o formulario vai ser enviado
    /// ; e a pagina sera redirecionada.
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="css/main.css">

    <form name="contrato" id="estilo"  onsubmit="return enviar(this)">

                Contrato de Serviços

                CONTRATANTE (Tomador(a) de Serviços): Sr(a).
                <input type="text" name="primeiro">

                Brasileiro(a), residente e domiciliado(a) na Rua
                <input type="text" name="segundo">

                N° <input type="number" name="terceiro">

                Cidade de: <input type="text" id="quarto">

                Estado: <input type="text" name="quinto">

                CPF ou CNPJ: <input type="text" name="sexto">

Referente a Prestação de Serviços do tipo:

                    <textarea name="comentario" rows="10" cols="40"></textarea>

                Valor: <input type="number" name="oitavo">

            <input type="submit" name="" id="bt" value="enviar">

    </form>

Comment: obrigado cara, vc me ajudou muito, eu n gosto de ficar copiando as coisas dos outros, eu fiquei uns 20 minutos analisando para entender a logica e entendi, como sou novo em java script estou tendo um pouco de dificuldades, mas agradeço muito a atenção e a ajuda !!!!
Comment: eu troquei o button pelo submit e deu certo, a função enviar que esta sendo chamada é de outro arquivo js que esta recebendo essa função e retornando os dados, porem na hora de validar o nome, dps q eu clico em ok, mesmo eu nao tendo colocado o nome, ele parte para a tela de exibição, vc sabe como eu posso resolver isso ?
Comment: eu comentei o resto do código, se vc tiver duvida da uma olhada
Comment: @GiovanniManganotti, alterei a resposta, fiz outras alterações talvez te ajude. =D

Validação de dados no JavaScript


what is the best practice of changing base object properties from inherited class

Question: I want to set "person" properties of student1 to person1. Is this possible doing it with assigning or any way without setting properties one by one ?
static void Main(string[] args)
{
  var student1 = new Student {Id = 1, Name = "kaya", Class = "3b", Number = "156"};
            var person1 = new Person { Id = 2, Name = "hasan" };

        }

    public class Person
    {
        public int Id { get; set; }
        public String Name { get; set; }
    }

    public class Student : Person
    {
        public int Number { get; set; }
        public String Class { get; set; }
    }

Comment: Considering the number of ways to go about this you may want to add information about the context in which you are trying to do this.

Why the copy is needed, for what purpose, etc. That way people can give solution that's best for the situation.
Answer: Well you could do it with reflection - but I personally wouldn't. You could add a CopyTo method in Person:
public class Person
{
    public int Id { get; set; }
    public String Name { get; set; }

    public void CopyTo(Person other)
    {
        other.Id = Id;
        other.Name = Name;
    }
}

Another option would be to use composition instead of inheritance, such that a Student had a Person property instead of deriving from Person. It really depends on the bigger picture though - do you actually want a Student to be a specialized Person, or was it just a simple way of getting the data in there?
This sort of question comes up every so often, but I rarely find myself wanting to do it in my own code... I'd be interested to see the design of code which requires this, to work out how I'd have designed it instead. It's not clear to me whether this is just a matter of me not doing the kind of work which encourages this pattern, or whether I use alternative designs to solve the same problem.
Comment: Jon, I have a feeling there are many more properties involved and Sessiz does not want to manually "connect the dots".
Comment: @Kris: That makes the argument for composition even stronger, IMO.
Answer: Have you looked at AutoMapper?  If you used half way decent conventions you end up writing almost zero code -
http://automapper.codeplex.com/
I recently used AutoMapper to map my POCOs with Subsonic.


On button click run function that add stuff to body

Question: Sorry for noobish question, i am new to html/javascript.
Lets say i have a from:
<form id="pass" >

            Password: <input type="password" name="password" >
            Username: <input type="text" name="username" value="User">

            <input type="submit" value="Send" class=btn> <input type="Reset" class=btn>

    </form>

And when button is pressed. I want to run function in script.js file, that for example clear the body.
What is the right way to do it?
Many thanks!
Comment: include script.js , and onclick="name of function"
Comment: clear the body or clear the form's value?
Comment: Not so important. Clear the  for example.
Answer: Add a code in your form tag as onsubmit="javascript: function_name();" example:
<form name="name" id="name" onsubmit="javascript: function_name();">
    // your code
</form>

Now in your JS, write:

Comment: `javascript:function_name();` in an `onsubmit` is misleading; `onsubmit` doesn't point to a URI, and `javascript:` is acting as a label. Just use `function_name();`, and remember to return a value to cancel as appropriate – or, even better, add a listener dynamically. It looks better and is more reliable.
Answer: Download, include and use jQuery.
Give the button an id (for example, DoSomething) in your markup and call it like this:
$('#DoSomething').click(function() {
    alert('my button works');
});

Comment: Please use the `submit` event of the form.


visible hidden no form no javascript

Question: quero que quando coloque o login, o outro form apareça mas ele aparece por um frame de segundo e desaparece, por que ?? alguém me ajuda por favor ?

    <form onsubmit="return Verifica(this)">
         Login:<input type="text" value="" name="usuario" id="login" >
         Senha: <input type="password" name="senha" value="" id="senha" >
        <input type="submit">
    </form>

    <form action="cad.php" method="post" name="form">
        <input type="text"  id="tipo" name="tipo" value="" style="visibility: hidden;" >
        <input type="text"  name="raca" value="" style="visibility: hidden;">
        <textarea name="area" style="visibility: hidden;"><input type="text" name="descricao" value=""></textarea>
        <input type="submit" name="submit" value="submit" style="visibility: hidden;">
    </form>

Comment: Recomendo estudar mais um pouco e analisar o código. Tem muita coisa estranha. Um input dentro de um textarea? Dados de Login no Javascript? Por que não oculta/mostra o formulário todo em vez de cada elemento dentro dele? O problema não é que o segundo form está "aparecendo e sumindo rápido", é porque vc está submetendo o primeiro e a página está sendo recarregada.
Comment: realmente tinha muita  coisa estranha, muito obrigado eu re-li tudo e concertei tudo =)
Answer: Olá, a sua tela 'pisca' porque os elementos se tornam visíveis e então o form é submetido (enviado), então página é recarregada e tudo volta ao estado original.
Para impedir que isso ocorra é necessário fazer com que o evento pare e não envie o formulário. Para isso pode utilizar o método .preventDefault() do evento.
<form onsubmit="return Verifica(this, event)">
     Login:<input type="text" value="" name="usuario" id="login" >
     Senha: <input type="password" name="senha" value="" id="senha" >
    <input type="submit">
</form>
<form action="cad.php" method="post" name="form">
   <input type="text"  id="tipo" name="tipo" value="" style="visibility: hidden;" >
   <input type="text"  name="raca" value="" style="visibility: hidden;">
   <textarea name="area" style="visibility: hidden;"><input type="text" name="descricao" value=""></textarea>
    <input type="submit" name="submit" value="submit" style="visibility: hidden;">
</form>

Tentei modificar o mínimo possível do seu código para que fique mais próximo do seu exemplo.
Na tag form adicionei a invocação do método mais um parâmetro, o event.
Alterei a função Verifica para aceitar o evento como parâmetro e logo da primeira linha da função invoco event.preventDefault() isso evita o envio do formulário ao clicar no botão de submit.
Na sua função Visible alterei a linha para document.getElementsByName("submit")[0].style.visibility. O método getElementsByName retorna um array, assim pego a primeira posição do array para evitar erros.
O código ainda pode ser melhorado, mas já é um começo. Espero ter ajudado com o problema

visible hidden no form no javascript


How to perform logistic regression with lasso using GLMSELECT?

Question: I am trying to perform logistic regression with lasso. For the logistic regression part I am using PROC LOGISTIC but I am not sure how to do lasso with PROC LOGISTIC. I searched online  and found that PROC GLMSELECT allows us to do lasso. But I am not sure how to do logistic regression with lasso using PROC GLMSELECT.
Note: I posted this question in the SAS Discussion Forum.
Comment: I don't think you can: GLMSELECT only does linear models. If you are willing to use R or Matlab, there is the glmnet package.
Comment: @Simon Byrne +1 for R and glmnet.  Glmnnet can handle logistic regression with both the lasso and the elastic net. It's also an extremely fast implementation of the algorithm, and I suggest trying it out if you know any R.
Answer: Code the outcome as -1 and 1, and run glmselect, and apply a cutoff of zero to the prediction. For a reference to this trick see
Hastie Tibshirani Friedman-Elements of statistical learning 2nd ed -2009
page 661
"Lasso regression can be applied to a two-class classifcation problem by
coding the outcome +-1, and applying a cutoff (usually 0) to the predictions."
It's a quick and dirty trick.
Lasso penalty can be applied to logistic regression, but it's not implemented in sas. In that case you have to try the R packages.


Two-sample $t$-test vs Tukey's method

Question: Even if the $F$ statistic in an ANOVA test is significant, we may need to do further testing before drawing conclusions. The most common method for doing this involves the use of a multiple comparisons procedure. I am trying to understand why Tukey's method is used over the two-sample $t$-test. I read the following below which suggested that doing all the pairwise tests (presumably it means two-sample $t$-tests) can lead to false positives (Type I errors). Why should this happen conceptually?

Tukey's procedure allows us to conduct separate tests to decide
  whether $\mu_i = \mu_j$ for each pair of means in an ANOVA study of
  $k$ population means. Like all multiple comparison procedures, Tukey's
  method is based on the selection of a "family" significance leve,
  $\alpha$, that applies to the entire collection of pairwise hypothesis
  tests. For example, when using the Tukey procedure with a significance
  level of, say, 5%, we are assured that there is at most a 5% chance of
  obtaining a false positive among the entire set of pairwise tests,
  That is, there is at most a 5% chance of mistakenly concluding that
  two population means differ when, in fact, they are equal. This is
  very different from simply conducting all the pairwise tests as
  individual tests, each at $\alpha=0.05$, which can result in a high
  probability of finding false positives among the pairwise tests.
Answer: It's simply that if (under the null hypothesis of no effects) there's a 5% chance, say, of a false positive in each one of 20 tests, say; there's a greater than 5% chance of a false positive in any one of those 20 tests.  If the tests are independent, the change of getting a false positive in none is $95\%^{20}=35.8\%$, and so the chance of a false positive in at least one is $64.2\%$—this is the family-wise error that multiple comparisons tests control. Of course pairwise comparisons of all means after ANOVA are not independent, and Tukey's test takes this into account.

Two-sample $t$-test vs Tukey's method


Webform Protected Downloads

Question: I am trying to figure out how to use this module.
I've downloaded it, installed it, etc. However, when I try to set up a webform, I'm not seeing anywhere where I can upload files and redirect to a link programmatically.
Where do I set this up?
I found this online, but I don't see "protected" anywhere.

Configurations on my site:

Installed the modules (Webform Protected Downloads, Private Upload)
Changed 'Default Upload Privacy Setting:' to 'Public' under 'admin/settings/private_upload'
Created a Webform > attached a file
Under 'File attachments' selected 'Public'
Enabled 'Protected' under 'Protected Downloads'.
Enabled 'view uploaded files' permission for anonymous users under 'admin/user/permissions'
Comment: Have you added a File field to your webform to allow users to upload files? This module will not do that; it only adds enhancements to webforms that already allow uploads.
Comment: A file field is supported, yes, but I don't see any "protected" section, only a private section. Nor do I see where it is supposed to link the user/redirect.
Answer: The D6 version of the module doesn't support filefield. You must use the drupal upload module. On the node edit form: Attach a file, set it to private. Switch to the tab "Protected downloads" and specify your settings there.
If you don't see the tab "Protected downloads" then it might be a bug. Consider opening an issue for this on the issue queue for the module on drupal.org.
Comment: Your're welcome. Small addition for other users that might find this question: Remember to grant the permission  "administer webform protected downloads", otherwise the tab "Protected downloads" is not available.

Webform Protected Downloads


How to report a P-value?

Question: I am writing the results of my thesis, and I have a few questions on how to report P-values.

When is it appropriate to give the exact P-value, instead of writing e.g. P<0.05 (also in case of non-significant P-values)?
If I have a P-value of e.g. 0.016, should I report it as P=0.01 or P=0.02? Or if it was 0.0167, should I write 0.016 or 0.017?
When I have a very small P-value, e.g. 0.00000013, is it appropriate to report it as P<0.000001, or is it better to stop at e.g. P<0.001?
Answer:
When is it appropriate to give the exact P-value, instead of writing e.g. P<0.05 (also in case of non-significant P-values)?

As a general guideline you want to convey as much information about your results as possible. When you report a p-value as p=0.016 instead of as p<0.02 then the readers will have a more precise view of the results. Often it is also helpful to report the statistic along with it. For instance you can encounter sentences like: "There was a positive effect of X with a coefficient $\beta_X = 0.5$, which was significant ($t = 2.6$, $p = 0.017$)".
The reporting of only $p<0.05$ can be done when one is only interested in strict cut-off levels (but often the cut-off levels are arbitrary). It is also common in graphs or tables where significance is denoted with superscripts like $^\star: p < 0.05$, ${^\star}{^\star}: p < 0.01$, ${^\star}{^\star}{^\star}: p < 0.001$ and in that case it is used as abbreviation to prevent cluttered graphs and tables that become difficult to read.
Instead of p-values, it is also increasingly more popular to report confidence intervals instead. Then the sentence above would become "There was a significant positive effect of X with a coefficient $\beta_X = 0.5$ (95% confidence interval [0.099,0.901] )".

If I have a P-value of e.g. 0.016, should I report it as P=0.01 or P=0.02?

Rounding off p-values might give a false idea. However, you could round up and use an inequality sign like $P<0.02$.

When I have a very small P-value, e.g. 0.00000013, is it appropriate to report it as P<0.000001, or is it better to stop at e.g. P<0.001?

The precision that is appropriate will depend on the application.
Often more precision than below $0.001$ is not needed. Also a better precision can be deceptive because the computation depends on several assumptions and the p-value is an estimate that can be computed with high precision, but does not truly have that high precision because of uncertainty in the assumptions underlying the computation. The computation with some model can be performed with a high precision, but that doesn't mean that the result of that computation should be considered as precise (the potential errors due to a wrong model should be considered as well).
In exact sciences like physics where high precision measurements are possible and a strong theoretical framework is present it is more common to see high precision p-values. For instance in some fields of physics one desires the significance to be below above $5\sigma$ which is equivalent to  $p < 0.00000057$.
Comment: @Galen I am not referring to computational errors. The computation is often very precise (and that is actually the problem). The problem is that filling in numbers/data into a very precise formula, which gives you a very precise number, does not mean that your research was equally precise. For instance, your formula might have been using the assumption that data is normal distributed, and if that assumption is wrong then the p value might be wrong as well. If we report low precision p values then such systematic errors are less important.
Comment: @Galen This very issue has come up in the context of bootstrapping a p-value (or using a permutation test), because the reported p-value has an inherent binomial uncertainty related to the length of the simulation.  In effect, such p-values are computed only with two or three significant digits of precision.
Comment: I have yet to see someone try to work out the numerical error of their p-value from their [machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon), or perform a grid search of levels of [arbitrary precision](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic) to obtain a stable calculation out to some number of digits. But these approaches could hypothetically be taken to account for the numerical imprecision of p-values. But it would definitely add to the labour of the analysis.
Comment: I see my interpretation was off, which more careful reading could have prevented.
Comment: Re "does not truly have that high precision". Since a p-value is a likelihood of a result under a model, might a highly precise p-value truly be precise but just for the wrong model? Analogous to the idea of [type 3 error](https://en.wikipedia.org/wiki/Type_III_error), the error might not be with the precision of the p-value but rather with answering the wrong question. Is that what you are considering, or something else?
Comment: Another considerations: Others reading the results might want to do things with them (e.g. meta-analyze them) that would be best done by having e.g. test statistics or standard errors. If you provide just something like p<=0.05 that makes their life really hard, so if you can provide a reasonable variety of information e.g. always confidence intervals in addition to the p-value (which due to style requirements might end up being rounded to 3 or 4 decimals resulting in things like "difference of 17.1 mmol/L (95% CI 15.3 to 26.5; p<0.001)".
Answer:
In practice, people report the exact p-value then declare whether the hypothesis test is statistically significant. Most statisticians don't advocate this. if the goal is hypothesis testing then reporting the p-value is moot because it doesn't make the test more significant, on the other hand the exact p-value matters if the result of the analysis doesn't boil down to a decision theoretic approach. So if the audience is not statisticians, they would probably expect you to do it the wrong way.

The significant digits on a p-value matters. First, you have to follow whatever style guide there is for your thesis or publication. If there are no rules, you need to consider the variability of the analysis. In general, it's hard to say how "stable" a p-value is without simulation or bootstrapping, but you'll often find that even with a huge analysis, a p-value is only really stable out to two decimal places - hence reporting 3 decimal places conveys a level of precision that is not present in the analysis. Secondly, if there is a pre-specified "alpha" level, you need to show enough precision for the reader to know whether p < alpha. In other words, p=0.05 requires two decimal places of precision if p = 0.04 or lower, but borderline cases get awkward. Do you say p = 0.049994 or p = 0.05 but it was statistically significant.

Don't cheat the incidental precision of the analysis. Use the prespecified precision following the rules above, and report out to the smallest decimal. Other aspects of the analysis should convey how striking the result is, a "really small p-value" in and of itself means nothing. And never never report p = 0.00.
Comment: Re "if the goal is hypothesis testing then reporting the p-value is moot:" not at all! The main point to reporting it is to *enable other users to conduct significance tests with their own thresholds* rather than having to accept your test sizes.  I would be surprised to see any real evidence that "most statisticians don't advocate this."
Comment: I am not saying that.  I am pointing out that your *readers* might have chosen *a priori* a level they view as more appropriate than your 0.05 (or whatever) level.  For instance, many might have adopted a recent suggestion to rely only on p-values less than 0.005.  Anyone who censors their reporting by writing "p < 0.05" is thereby making their results almost worthless. They also make multiple comparisons corrections nearly impossible to perform, again a disservice to knowledgeable and thoughtful readers.
Comment: @whuber that's a ludicrous thought to me, because you don't choose an alpha level at the point of analysis, you choose it at the point of design and it consequently informs sample size, design, number of tests, and overall feasibility. Nobody chooses the alpha after all that is said and done.
Comment: Re "if the goal is hypothesis testing then reporting the p-value is moot": Perhaps some types of meta-analysis can be performed more precisely if p-values are reported precisely. Otherwise reporting whether a test was significant at some $\alpha$ still allows the use of [interval arithmetic](https://en.wikipedia.org/wiki/Interval_arithmetic) by first inferring the interval $p \in [0, \alpha)$, which is less precise but not necessarily useless.
Comment: I disagree with the common convention that p values below 0.001 are not reported. False positive test results with such p values are actually far more common than we like to think. False positives with low p values occur because of selective reporting and because each publication may contain many p values.
Comment: Thank you for your answers. I am still a bit confused about to what point a P-value can be rounded off? So referring to my second question
Comment: @balzy it's easiest to follow the style guide if it covers this. In most cases, it's 2 or 3 places. The bigger 3 might be justified for really big analyses like genomic assays or epidemiologic surveys with, e.g. 10,000 observations or more. Again, nothing here is universal, but will largely align with what's in the literature.

How to report a P-value?


Are left hand chord patterns influenced by the time signature?

Question: Does the time signature dictate what chord pattern you use on the left hand?
For example, in "row your boat" a 6/8 time, I'll repeat the chord twice. So if I'm playing the 3 notes of the chord and play it twice I'll get to 6 notes which matches the time signature.
And in "london bridge" which is a 4/4 time I play the chord using two notes (say the 1 and the 5), and I'll play these twice 1 5 1 5 so they match each beat.
So the chords tones in the left hand essentially match the beat (or go between) the beat. Therefore the time signatures have a direct influence on the chord patterns you play on your left hand. Does this sound right?
Answer: That doesn't sound right.
The left hand pattern may be influenced by the time signature however it is completely up to the composer/performer what chords are written/played.
For example. There is nothing stopping the chord tones from being played/notated as triplets in 4/4. In fact that might make more sense to a reader rather than changing the melody line to dotted crotchets.
Time signature is simply notation, or a method or writing something down. It does not really have any effect on the 'music' or the way the 'music is'. As long as the writer understands how to write what he intends or is imagining and the reader understands what he is reading, time signature doesn't restrict chord patterns in any way.

Same key signature but different rhythm, threes, vs twos. It would be possible to write exactly the same rhythms in 6/8 or any other key signature really. 6/8 or compound time might be more effort than it is worth. Anything else might be a little unclear. (Imagine writing that in 5/4 or some silliness)
As a player who is improvising or comping it might be easier to do what you're describing but there is no reason why it has to be like that at all. As you improve you might choose to employ polyrhythms, or any number of more 'interesting' comping patterns.
Answer: Time signature does three things in western classical music: it tells how many beats are in each measure, it tells which beats are strong, and it tells whether the beats are divided into two or three parts.
In chord-structured harmony the bass lines often follow the structure provided by the time signature. Generally, lower notes provide more grounding and heaviness to the line, so they are placed on the strong beats.
Thus, in a 3/4 time there will usually be a low note on beat one and higher notes on beats 2 and 3. In the example axerotolerant gave above, even in the triplets, the low note is on the beat and the higher notes are on the weak parts of the beat. In 4/4 time, the strong beats are 1 and 3, so lower notes will be on those beats and higher notes on beats 2 and 4. In 6/8 time, the strong pulses are on the 1st and 4th eighth notes.
To go against this pattern creates syncopation because the heaviness of the low note will bring attention, and thus an accent of sorts, to a normally weak beat or part of a beat.


Controle de visualização via autorização com AngularJS + WebAPI

Question: Estou trabalhando em um aplicativo construído com AngularJS e ASP.NET Web API. Por enquanto, usando o ASP.NET Identity já consegui implementar autenticação e autorização na API usando OAuth 2.0 e autorização baseada em tokens.
Testei com a api separadamente da interface e já pude ver que tudo funciona como esperado. Ainda estou com dúvida, porém, em como fazer com a parte AngularJS. Estou pensando agora na autorização.
O problema que eu tenho é o fato de nem todas as rotas serem permitidas e o fato da seleção de páginas não consultar o servidor, sendo feito diretamente por javascript. Dessa forma, apesar de eu ser capaz de bloquear o acesso a um controller no servidor eu não sei como fazer para bloquear o acesso as telas correspondentes no aplicativo JS.
A minha ideia foi basicamente criar um serviço capaz de escolher as rotas para o usuário e então retornar um array com os objetos correspondentes que poderia ser iterado e registrado no angular. Basicamente seria algo do tipo:
opcoes = {
    type: 'GET',
    url: 'servidor/api/rotas'
};

$.ajax(opcoes).then(function(dados) {
    angular.module('app').config(function($routeProvider) {
        // itera pelos dados e para cada objeto adiciona a rota
    });
});

O problema é que não sei se essa é uma boa solução e de qualquer forma, parece que ela só iria servir pra definir as rotas certas, não sei se ainda haveria brechas de segurança.
Essa é uma boa solução para autorização no AngularJS? Existem jeitos melhores de se fazer isso, ou essa abordagem é suficiente?
Comment: Aqui na empresa nós colocamos toda a autenticação na webapi e enviamos uma lista de menus ou páginas disponíveis para o usuário. Caso algum usuário consiga acessar qualquer página que não deveria, o server deve retornar um 401 e o App vai redirecionar o usuário para tela de login ou home (dependendo do projeto).
Answer: Acho que o caminho é por aí mesmo. Recentemente implementei algo parecido  (mas com KnockoutJS em vez de AngularJS), e nem me preocupei muito com essa questão de acesso, já que o bloqueio que importa mesmo estava devidamente implementado na WebAPI.
Como estamos falando de colocar as rotas diretamente no Javascript, é sempre importante lembrar que a "segurança" é relativa, já que qualquer pessoa pode olhar o seu código. Da forma como entendo, o que você quer fazer é apenas criar uma forma mais "amigável" de tratar acessos inválidos, correto?
Se sim, dê uma olhada nisso aqui, acho que pode ser útil. Me lembrou bastante o que você está pensando em fazer:
Authentication in Single Page Applications With Angular.js
Comment: Obrigado @MichaelSiegwarth. Esse artigo ajudou a dar umas ideias. É um pouco diferente do que eu estou fazendo, porque no meu caso as rotas em si realmente dependem do usuário, mas já deu uma ideia de como fazer.
Answer: Existem várias maneiras de implementar controles de processo e visibilidade. A implementação atual nos aplicativos com os quais trabalho é a seguinte:

Criação de um endpoint para obtenção das permissões client-bound

A idéia é fornecer à aplicação Angular as permissões públicas do usuário - algumas, restritas para uso no back-end, são ignoradas. O resultado final é similar ao seguinte exemplo:

http://localhost/aplicacao/framework/auth/identity

Com o seguinte resultado sendo retornado:
{
    "Id":"324c915c-a59d-45f7-8005-03eac6d74b28",
    "Locator":"fakeuser",
    "Email":"firstname.lastname@example.com",
    "Name":"Fake User",
    "permissionsKeys":[
        "USR",
        "ADM",
        "MSG",
        "AUDIT"
    ]
}

Parse da lista, e controle de visualicação de conteúdo client-side

Utilizando de uma biblioteca para checar a presença de uma dada permissão, é fácil implementar controle de visualização:

Auditor


Why are the two calculations of $ \int \frac{1}{\sqrt{x(1-x)}} \mathrm{d} x $ give two distinct answers?

Question: One of the calculations:
$$
\begin{aligned}
\int \frac{1}{\sqrt{x(1-x)}} \mathrm{d} x &=\int \frac{1}{\sqrt{1-(\sqrt{x})^{2}}} \cdot \frac{1}{\sqrt{x}} \mathrm{~d} x \\
&=2 \int \frac{1}{\sqrt{1-(\sqrt{x})^{2}}} \mathrm{~d}(\sqrt{x})=2 \arcsin \sqrt{x}+C .
\end{aligned}
$$
The other:
$$
\int \frac{1}{\sqrt{x(1-x)}} \mathrm{d} x = \int \frac{d\left(x-\frac{1}{2}\right)}{\sqrt{\left(\frac{1}{2}\right)^{2}-\left(x-\frac{1}{2}\right)^{2}}} = \arcsin \frac{x-1 / 2}{1 / 2}+C=\arcsin(2x-1)+C
$$
Comment: The formula for $\cos{2u}=2\cos{u}^2-1$ can be used to get a relation between the two forms of arcsin appearing in the results and thus show both answers are equivalent.
Comment: There is no problem: the functions on the r.h.s. are the same except for an additive constant
Answer: The answers are actually the same.
$\begin{align*}
\theta = 2\arcsin \sqrt x &\implies \sin \frac \theta 2 = \sqrt x \\
&\implies \sin^2 \frac \theta 2 = x \\
&\implies \frac{1-\cos \theta}{2} = x \\
&\implies \cos \theta = 1-2x \\
&\implies \sin(\theta+\pi/2) = 2x-1 \\
&\implies \theta = \arcsin(2x-1) - \pi/2
\end{align*}$
And $\pi/2$ gets absorbed into $+C$
Answer: Because the integral is indefinite.
If you differentiate the first form,
$${d2\arcsin{(\sqrt{x})} \over dx}=2{1 \over \sqrt{1-(\sqrt{x})^2}}\cdot {1 \over 2\sqrt{x}}={1 \over \sqrt{x(1-x)}}$$
As for the second one,
$${d\arcsin{(2x-1)} \over dx}={1 \over \sqrt{1-(2x-1)^2}}\cdot 2={1 \over \sqrt{x(1-x)}}$$
Therefore, the both forms are correct.
Answer: They are both correct. Let $y=2 \arcsin \sqrt x$. Then $x=(\sin (\frac  y 2))^{2}$. So $2x-1=2(\sin (\frac  y 2))^{2}-1=\sin (y+\frac {\pi} 2)$. So $y=\sin (2x-1)-\frac {\pi} 2$.


Apache Pivot - SerializationException when launching application

Question: I started trying out Apache Pivot as I want to create java GUI's with XML.
I followed their Hello BXML tutorial using a maven project on their web site.
These are the files that I'm using:
HelloBXML.java
package za.co.iriesoft;

import org.apache.pivot.beans.BXMLSerializer;
import org.apache.pivot.collections.Map;
import org.apache.pivot.wtk.Application;
import org.apache.pivot.wtk.Display;
import org.apache.pivot.wtk.Window;

public class HelloBXML implements Application {
    private Window window = null;

    public void startup(Display display, Map<String, String> properties) throws Exception {
        BXMLSerializer bxmlSerializer = new BXMLSerializer();
        window = (Window) bxmlSerializer.readObject(HelloBXML.class, "hello.bxml");
        window.open(display);
    }

    public boolean shutdown(boolean optional) {
        if (window != null) {
            window.close();
        }

        return false;
    }

    public void suspend() {
    }

    public void resume() {
    }
}

hello.bxml
<?xml version="1.0" encoding="UTF-8"?>
<Window title="Hello BXML!" maximized="true"
    xmlns:bxml="http://pivot.apache.org/bxml"
    xmlns="org.apache.pivot.wtk">

</Window>

App.java
package za.co.iriesoft;

import org.apache.pivot.wtk.DesktopApplicationContext;

public class App {

    public static void main(String[] args) {

        DesktopApplicationContext.main(HelloBXML.class, args);

    }
}

When I run the application I get an exception:
Exception: An error occurred at line number 4 in file /C:/Apps/java/java-ws-client/target/classes/za/co/iriesoft/hello.bxml:
org.apache.pivot.serialization.SerializationException: An error occurred at line number 4 in file /C:/Apps/java/java-ws-client/target/classes/za/co/iriesoft/hello.bxml:
    at org.apache.pivot.beans.BXMLSerializer.logException(BXMLSerializer.java:1516)
    at org.apache.pivot.beans.BXMLSerializer.readObject(BXMLSerializer.java:514)
    at org.apache.pivot.beans.BXMLSerializer.readObject(BXMLSerializer.java:684)
    at org.apache.pivot.beans.BXMLSerializer.readObject(BXMLSerializer.java:639)
    at org.apache.pivot.beans.BXMLSerializer.readObject(BXMLSerializer.java:600)
    at za.co.iriesoft.HelloBXML.startup(HelloBXML.java:14)
    at org.apache.pivot.wtk.DesktopApplicationContext$2.run(DesktopApplicationContext.java:666)
    at org.apache.pivot.wtk.ApplicationContext$QueuedCallback.run(ApplicationContext.java:1690)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: org.apache.pivot.serialization.SerializationException: java.lang.ExceptionInInitializerError
    at org.apache.pivot.beans.BXMLSerializer.processStartElement(BXMLSerializer.java:829)
    at org.apache.pivot.beans.BXMLSerializer.readObject(BXMLSerializer.java:493)
    ... 20 more
Caused by: java.lang.ExceptionInInitializerError
    at org.apache.pivot.wtk.Component.installSkin(Component.java:807)
    at org.apache.pivot.wtk.Window.<init>(Window.java:472)
    at org.apache.pivot.wtk.Window.<init>(Window.java:467)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at org.apache.pivot.beans.BXMLSerializer.newTypedObject(BXMLSerializer.java:1697)
    at org.apache.pivot.beans.BXMLSerializer.processStartElement(BXMLSerializer.java:827)
    ... 21 more
Caused by: org.apache.pivot.wtk.ThemeNotFoundException: A theme could not be located.
    at org.apache.pivot.wtk.Theme.<clinit>(Theme.java:77)
    ... 31 more
org.apache.pivot.serialization.SerializationException: java.lang.ExceptionInInitializerError
    at org.apache.pivot.beans.BXMLSerializer.processStartElement(BXMLSerializer.java:829)
    at org.apache.pivot.beans.BXMLSerializer.readObject(BXMLSerializer.java:493)
    at org.apache.pivot.beans.BXMLSerializer.readObject(BXMLSerializer.java:684)
    at org.apache.pivot.beans.BXMLSerializer.readObject(BXMLSerializer.java:639)
    at org.apache.pivot.beans.BXMLSerializer.readObject(BXMLSerializer.java:600)
    at za.co.iriesoft.HelloBXML.startup(HelloBXML.java:14)
    at org.apache.pivot.wtk.DesktopApplicationContext$2.run(DesktopApplicationContext.java:666)
    at org.apache.pivot.wtk.ApplicationContext$QueuedCallback.run(ApplicationContext.java:1690)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: java.lang.ExceptionInInitializerError
    at org.apache.pivot.wtk.Component.installSkin(Component.java:807)
    at org.apache.pivot.wtk.Window.<init>(Window.java:472)
    at org.apache.pivot.wtk.Window.<init>(Window.java:467)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at org.apache.pivot.beans.BXMLSerializer.newTypedObject(BXMLSerializer.java:1697)
    at org.apache.pivot.beans.BXMLSerializer.processStartElement(BXMLSerializer.java:827)
    ... 21 more
Caused by: org.apache.pivot.wtk.ThemeNotFoundException: A theme could not be located.
    at org.apache.pivot.wtk.Theme.<clinit>(Theme.java:77)
    ... 31 more
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: Could not initialize class org.apache.pivot.wtk.Theme
    at org.apache.pivot.wtk.Component.installSkin(Component.java:807)
    at org.apache.pivot.wtk.TextArea.<init>(TextArea.java:603)
    at org.apache.pivot.wtk.ApplicationContext.defaultUncaughtExceptionHandler(ApplicationContext.java:2134)
    at org.apache.pivot.wtk.ApplicationContext.handleUncaughtException(ApplicationContext.java:2155)
    at org.apache.pivot.wtk.DesktopApplicationContext$2.run(DesktopApplicationContext.java:669)
    at org.apache.pivot.wtk.ApplicationContext$QueuedCallback.run(ApplicationContext.java:1690)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Does any one know what could be the problem? I been struggling the whole day trying different IDE's and searching Google and their bug database for an answer, but to no avail.
I am running on Windows 10, Java SDK 1.8.0_152
Comment: I just want to add, in addition to @rwhitcomb answer below. The way I went wrong was to copy and paste the first Pivot maven dependency

`
org.apache.pivot
pivot
2.0.5
pom
`

So just changed the artifactId's for the others (pivot-charts, pivot-core, pivot-wtk-terra).

With this I left the *pom* attribute on all of them, and this caused maven not to read/include these additional dependencies. So for the other dependencies, do leave out the 'type' attributes.
Answer: I'm guessing you don't have the "pivot-wtk-terra...jar" file in your classpath.  The underlying error seems to be "A theme could not be located."  That theme is this "...terra...jar" file.
Comment: The other thing I should point out is that the code in "main" in your "App" class can (and should) be moved into the "HelloBXML" class.  If you look into the other examples this is the way Pivot applications normally work.


existence or count of children in file resource?

Question: The files resource, which is returned by the files.list and other methods, includes a list of parents for each file.  It would be extremely helpful if files also included some indication of children.  An integer property with the count of children would be best, but a Boolean flag indicating whether children exist would be fine.  Could that be added to the API, Google folks?
I ask because I'm writing an application that displays an expandable tree of the user's Google Drive contents.  The tree initially displays the top level of their drive with all folders collapsed.  As the user expands folders, new queries are sent to the GD API to get the contents of each one.  However, empty folders are to be displayed without an expansion icon at all.  In order to do that, as the list of children in a folder is processed, if a child is a folder, another query must be run for that specific folder to discover whether it has children.  It would be so much better if the files resource included a count of its children or a flag indicating their existence.  It would reduce the number of queries, network traffic, and processing time.
Answer: I doubt very much it will happen. The issue is that there could be thousands of children and to include an array of that size within the file object would break and time out.
The children feed https://developers.google.com/drive/v2/reference/children/list is there for that specific purpose, and supports pagination.
Comment: That makes sense.  Even though the `children` resource is small (only four properties), it could represent a lot of data if there are many of them.  Since what I'd like to know is whether a file has children, I will edit my question.
Comment: No harm putting in the feature request, and I understand the use case. I do something similar. I wouldn't hold your breath for a change to the API since I suspect this particular change would require a significant amount of Drive infrastructure processing to derive the count of children in realtime, or a data redesign to maintain a running count in the File object.
Comment: Sure.  Maybe the count of the children could be a problem.  A Boolean flag should be ok, though.  I hope to get an official response from one of the Google Drive team members, like @AliAfshar or the others.
Comment: @pinoyyid It still puzzles me why the server can't return a number of items found (for any list query) without/before returning the list. I assume the total number of found items must be known to the server before any pagination takes place. And it would be helpful to the requesting app in order to build a progress bar, for instance.
Comment: @seanpj I agree with your use case. I guess this is all massively distributed, so I doubt there is any one server that could authoritatively marshal the query results. The best workarounds I can think of are (a) run with maxresults 1000 and fields=items/id to get a long, skinny list, or (b) run a proxy on appengine that does the fetch-pagination and returns a count to the client.
Comment: Thanks, (a) is exactly what I'm doing now. I use title instead of id, since it seems 'skinnier'. But it still takes a longer than a single number. It was just an idea that the 'proxy solution' could be build into the SDK. But I know I'm pushing it.
Answer: Various work-around I found were all based on a looping solution over the children items count returned by each API call. Next API call must be then updated with the nextPageToken received from each response. A maxResult may be set to 1000 (max allowed).
Examples:

https://stackoverflow.com/a/16299157/490589 (C# version)
https://stackoverflow.com/a/17743049/490589 (Java version)


hibernate 4.x unable to load super class entity column names if calling class uses lombok @Data annotation

Question: Hi I'm using lombok api with entity class having @Data annotation which extends audit class (common columns) which is simple abstract class with @MappedSuperclass annotation. But when hibernate-jpa loads, it is not picking up the column names but instead its picking up actual member variable names.
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "TEST_TYPES", schema = "TESTER")
@EqualsAndHashCode(callSuper = false, of = {"id"})
public class TestEntity extends AuditEntity {
    @Id
    @Column(name = "TYPE_ID")
    private Short id;

    @Column(name = "NAME")
    private String name;
}

    @MappedSuperclass
public abstract class AuditEntity implements Serializable {
    private static final long serialVersionUID = 3487394229267512541L;
    private String createdBy;
    private Date createdDate;

    @Column(name = "CREATE_ID", length = 40)
    public String getCreatedBy() {
        return this.createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "CREATED_DATE", length = 7)
    public Date getCreatedDate() {
        return this.createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

}
Problem:
Hibernate throwing this error..
Caused by: java.sql.SQLSyntaxErrorException: ORA-00904: "TESTPROJJU0_"."CREATEDBY": invalid identifier
Expected:
hibernate should pick the column name ie "CREATED_BY" but it is picking up "createdby"
I appreciate any suggestion/help.
Answer: This might have something to do with JPA's naming strategy. Setting the property
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

should take the actual column names you provided.
Comment: thanks for your response. But your suggestion supports for hibernate 5.0 and above. But i'm using hibernate4.x
Comment: ok, better add it to your question, others might also suggest hibernate5 stuff
Answer: You are not specifying the name using @Column annotation.
Comment: Hi Niver I'm using @Column annotation on getters which is fine.
Comment: `@Column(name = "CREATE_ID"` shouldn't this be `@Column(name = "CREATED_BY"`?


How to read all the files of the same type of an arborescence in Python?

Question: I am using the TUH EEG Seizure corpus and I would like to get easily with Python all the files with the same extension. I saw that post but I don't know if it can be applied to an overall hierarchy.
Thanks in advance
Answer: glob allow to automatically select a pattern in a single directory. os.walk is the tool to use for browsing a full hierarchy, but it has no provision for filtering file names on a specific pattern, so you have to apply the filtering by hand. You could do:
import os.path

# enter your real data here
top_folder = ...
extension = ...

# and let's browse:
for folder, sub_folders, files in os.walk(top_folder)
    for file in files:
        if file.endswith(extension):
            full_path = os.path.join(folder, file)
            # apply your processing to full_path


Lower bound for Adjusted Rand Index?

Question: From the original paper, it's not clear whether the adjusted rand index has a lower bound.
Does it? If so, what partition yields the bound?
If now, how can I construct partitions with arbitrary low ARI?
A naive try gave
ARI([0, 1, 0, 1], [0, 0, 1, 1]) = -.5
(written as cluster assignments).
Answer: ARI equation is
$$\dfrac{\sum_{i,j}{n_{ij} \choose 2} - \sum_{i}{n_{i.} \choose 2}\sum_{j}{n_{.j} \choose 2} / {n \choose 2}}{\frac{1}{2}[\sum_{i}{n_{i.} \choose 2}+\sum_{j}{n_{.j} \choose 2}]-\sum_{i}{n_{i.} \choose 2}\sum_{j}{n_{.j} \choose 2} / {n \choose 2}}$$
To minimize ARI, $\sum_{i,j}{n_{ij} \choose 2}$ is minimized.
In a contingency table, all entry has 1 or 0, $\sum_{i,j}{n_{ij} \choose 2}$  = 0.
So numerator is negative, we need to minimize denominator.
To minimize $\sum_{i}{n_{i.} \choose 2}+\sum_{j}{n_{.j} \choose 2}$, all entry in a contingency table is evenly distributed.
Therefore I think that ARI is minimum when all entry in a contingency table has 1. When all entry in 2x1 contingency table is 1, ARI is 0. When all entry in 2x2 contingency table(your case) is 1, ARI is -0.5. When all entry in 2x3 contingency table is 1, ARI is -0.36. When 3x3, ARI is -0.33 and so on.
So I think lower bound of ARI is -0.5. :-)
-Haesun Park
Comment: Thanks :) I have to think about whether this constitutes a proof or what parts are missing to make it one.
Answer: Look at the rand index and adjustment equation. Don't look at a single example.
Obviously, to find the lower bound, you need to construct the worst possible clustering. This depends very much on your input data (e.g. cluster sizes, data set size), so there is not a general rule.
Comment: Well I looked at the equation and a lower bound was not obvious to me.
Comment: If I remember correctly, the worst case are balanced binary problems (otherwise, true negatives help), with minimal agreement. Essentially the case you already have in your question.
Comment: But if your data set has more classes, or is not balanced, the minimum may in fact be larger up to the point where the adjustment for chance makes little difference.

Lower bound for Adjusted Rand Index?


How to make a data frame selecting shiny app in R?

Question: I have a data frame with three columns:
x = data.frame(group=c("group1", "group2", "group3","group1","group3", "group4", "group2"),
               user=c("user1", "user3", "user5", "user9", "user14", "user18", "user24"),
               erro=c("error1", "error2", "error4", "error3", "error2", "error1", "error3")
               )
x

I need to create a shiny app that shows in data table a list of rows from that table which have only error2 and error3. As a control widget I need a filter of group type. How could i built it? I'm new in shiny.
Comment: @EdZ there really are a number of ways you could approach this, and more details would be helpful. Take a look at 'selectInput` which offers `multiple` option, or `checkboxGroupInput` for checkboxes, or `DT` library for `datatable` that can be filtered with `regex` to handle various complex filters. Based on inputs you can make a `reactive` expression to handle what rows are displayed in your data table based on these input selections. If you haven't already look at the [gallery](https://shiny.rstudio.com/gallery/) of examples or view a tutorial to get ideas.
Comment: hi, I can only invite you to read some [tutorials](https://shiny.rstudio.com/tutorial/written-tutorial/lesson1/) on R shiny, it will be more efficient than asking questions on StackOverflow. Also, several similar questions have already been asked on this topic, you should search online and if you don't find any information, then ask what you're looking for on StackOverflow
Comment: @bretauv well stackoverlow is handy in case if your code doesn't work and also there's not much of a questions like this here so it would be useful to add some case
Comment: the most unclear part for me here is filtering data by group(control widget)
Comment: well if you want to ask a question, you should add a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). For a question about R shiny, you should add the code necessary to reproduce your app, i.e the ```ui``` and ```server``` part. Try to reduce this code as much as possible because not all components are necessary. Also, making the effort of simplifying our problem is a great way to find the solution on our own
Comment: code example would be nice though
Comment: @EdZ almost every option proposed by Ben are in the tutorials I talked about in the first comment, you should really follow them
Answer: Here's a start:
library(shiny)
library(dplyr)

x = data.frame(group=c("group1", "group2", "group3","group1","group3", "group4", "group2"),
               user=c("user1", "user3", "user5", "user9", "user14", "user18", "user24"),
               erro=c("error1", "error2", "error4", "error3", "error2", "error1", "error3")
)

ui = fluidPage(
  selectInput("grType", "Select group type", x$group, multiple = TRUE),
  tableOutput("myTable")
)

server <- shinyServer(function(input, output, session) {
  output$myTable <- renderTable({
    req(input$grType)
    x %>% filter(group %in% input$grType,
                 erro %in% c("error2", "error3"))
  })
}
)
shinyApp(ui = ui, server = server)

Comment: thanks, is it possible also to choose all groups simultaneously in control widget?
Comment: @EdZ sure, add ```multiple = TRUE``` in ```selectInput```
Comment: We also need to change filtering method to ```group %in% input$grType``` if we want multiple inputs. I added that to my respons


Permutation matrices

Question: Let $\mathscr{M}$ be the set of all $n\times n$ matrices having entries $0$ and $1$ in such
a way that there is one $1$ in each row and column.
(a) If $M\in\mathscr{M}$, describe $AM$ in terms of the rows and columns of A.
(b) If $M\in\mathscr{M}$, describe $MA$ in terms of the rows and columns of A.
I don't understand this question properly. So I want some help on what this question is exactly asking. I forgot to add this point before . Apologies for that.
Comment: Have you tried to do this for, say, a small $3\times 3$ matrix $A$ and a permutation matrix $M$?
Comment: The simplest test case is $$M=\pmatrix{0&1\cr1&0\cr}.$$ Surely you have checked what happens when you multiply a generic $2\times2$ matrix by that from left or right? It amounts to an elementary row (resp. column) operation of a certain type :-)
Comment: Hint: write the product on an example, with the usual setting ($A$ on the left of product $AB$, $B$ on top of it), to help visualize. A $4\times4$ example should be enough to understand.
Comment: Are you sure that should be an "I" (the letter $I$) and not just a "1" (the number $1$)?
Comment: @Omnomnomnom, Thanx, you are right, I just missed that. I edited the question !!
Answer: Let $A_1,\dots,A_n$ be the columns of $A$, and $M_1,\dots,M_n$ the columns of $M$.  Note that each $A_i$ is one of the standard basis vectors, $\{e_1,\dots,e_n\}$, where $e_i = (\overbrace{0,\dots,0}^{i-1},1,0,\dots,0)^T$.  Note the following two things:

For any matrix $M$ and $A$ as above, we can state that
$$
MA = M \pmatrix{A_1 & \cdots & A_n} = \pmatrix{MA_1 & \cdots & MA_n}
$$
For any basis vector $e_i$, we have
$$
M e_i = \pmatrix{M_1 & \cdots & M_n} \pmatrix{0\\\vdots\\1\\ \vdots \\0} = M_i
$$

That should be enough to figure out what $MA$ looks like.  For the other case, note that $(AM)^T = M^TA^T$.

Permutation matrices


Rails distinct user records, sorted by time

Question: So I have a query to get the latest post from each user I follow. Like so:
query = Post.select("DISTINCT ON (user_id) *")
      .includes(:likes).includes(:comments)
      .where(user_id: followings)
      .where(silently_deleted: false)
      .order(user_id: :desc, created_at: :desc)

Problem is that the posts won't order by date. And I can't really do sort_by because we're paginating.
Is there a way to order by created_at while still being to preserve the uniqueness?
Comment: Can you share the SQL output? Also some sample data and desired output? "It doesn't order by date" isn't very helpful. http://stackoverflow.com/help/mcve
Answer: Try with this:
query = Post.select("DISTINCT ON (user_id) *")
  .includes(:likes).includes(:comments)
  .where(user_id: followings)
  .where(silently_deleted: false)
  .order(user_id: :desc)
  .order("posts.created_at DESC")

You need to add the table name explicitly because likes and comments tables also have the column name created_at
Answer: You might use a self-join to select the last post for each user.
For each post, this LEFT JOINs all posts by the same user, that are created later (have a higher id) than the current post. The following where condition then selects only those records which have NO later post, i.e. effectively selecting the last post for each user.
Refer to this blog post for other possible solutions. The best solution depends largely on the posts table size.
query = Post
  .joins("left join posts p on p.user_id = posts.user_id and p.id > posts.id")
  .where("p.id is null")
  .includes(:likes).includes(:comments)
  .where(user_id: followings)
  .where(silently_deleted: false)
  .order(user_id: :desc, created_at: :desc)

Answer: Use group + having:
Post.group(:user_id).having('posts.created_at=MAX(posts.created_at)')


Error while accessing network state

Question: I want to connect my app to the internet so i put in the permission check for connecting to the internet and accessing network state:-

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MovieManiac">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

<user-permission android:name="android.permission.INTERNET"/>
<user-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<user-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
</manifest>

I have tried all the solutions previously posted like adding user-permission again and also clean build but nothing seems to work. I use API 22. I would really appreciate some help.The error i get is this:-
FATAL EXCEPTION: main
Process: com.example.archit.moviemaniac, PID: 4638
java.lang.SecurityException: ConnectivityService: Neither user 10105 nor current process has android.permission.ACCESS_NETWORK_STATE.
at android.os.Parcel.readException(Parcel.java:1546)
at android.os.Parcel.readException(Parcel.java:1499)
at android.net.IConnectivityManager$Stub$Proxy.getActiveNetworkInfo(IConnectivityManager.java:964)
at android.net.ConnectivityManager.getActiveNetworkInfo(ConnectivityManager.java:610)
at com.example.archit.moviemaniac.MovieManiac$1.onClick(MovieManiac.java:41)
at android.view.View.performClick(View.java:4789)
at android.view.View$PerformClick.run(View.java:19881)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

Comment: try doing a clean build
Comment: i have already tried that but that does not help. :(
Answer: Replace
<user-permission android:name="android.permission.INTERNET"/>
<user-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

With
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

In Android manifest you are using user-permission  instead of uses-permission  .

Error while accessing network state


Source-based routing on Cisco 3750 switch?

Question: I have this Cisco 3750 switch which handles many VLANs. It has an IP interface on some of them, and it does routing for those computers connected to those VLANs which use the switch's IP addresses as their default gateway.
The switch has a default gateway, too; this is needed because one of those VLANs is connected to an Internet router, so every outgoing connection which is not directed to any specific internal subnet needs to go there.
The switch itself also has another IP address, which we use for management; this address is attached to one of the VLANs. Traffic from/to this address needs to go through another route.
The question: I want any outgoing IP connection which comes from the switch to go through a different route than its default gateway. But this should only apply to packets which originates from the switch itself; those packets which come from any device connected to any VLAN on the switch should go through the default route.
Source-based routing is what I need here; i.e. I want a static route which only applies to packets originating from the switch itself.
Can this be done on a Cisco 3750 switch?
How?

Edit: why I want this
This is a test environment, where the default gateway is a Linux firewall which at any given time might be down; our workstations are on the other side of this firewall, and there's also some other routing in the middle.
The switch has a management IP on a subnet which is linked to our main network, where a gateway could allow it to talk with us without going through its default gateway.
And of course we don't want to lose connectivity to the switch if the test area is not fully working.
But, at the same time, the switch's default gateway has to be that one, because the switch itself also acts as a router for the (many) subnets which form this test area.
So I need to route through an alternate gateway all the traffic that comes from the switch, but only it.

Edit: show version
Cisco IOS Software, C3750 Software (C3750-IPBASEK9-M), Version 12.2(25)SEE1, RELEASE SOFTWARE (fc1)
Copyright (c) 1986-2006 by Cisco Systems, Inc.
Compiled Mon 22-May-06 08:51 by yenanh
Image text-base: 0x00003000, data-base: 0x01026AEC

ROM: Bootstrap program is C3750 boot loader
BOOTLDR: C3750 Boot Loader (C3750-HBOOT-M) Version 12.2(25r)SEC, RELEASE SOFTWARE (fc4)

SW-TEST uptime is 5 weeks, 1 day, 16 hours, 22 minutes
System returned to ROM by power-on
System image file is "flash:c3750-ipbasek9-mz.122-25.SEE1/c3750-ipbasek9-mz.122-25.SEE1.bin"

Answer: If you want to direct or tag the traffic originating from the switch or router (will work on IPBASE) I'm guessing you already succeeded but if not.
conf t

access-list 1 any

route-map pbr permit 10

 match ip address 1

 set ip next-hop 22.214.171.124

exit

ip local policy route-map pbr

end

wr

Note that ip local policy is specified in global configuration, not under an interface. And you might want to have a more detailed ACL
This is only for traffic that originates from the device, not traffic that passes through it.
Comment: I have notice your forgot to map policy to source Interface like this `ip policy route-map pbr` on `Interface`
Answer: Cisco 3750s support "Policy-Based Routing" which will allow you to make routing decisions based on a standard ACL. Here is the PDF explaining it:
http://www.cisco.com/en/US/docs/switches/lan/catalyst4500/12.2/25sg/configuration/guide/pbroute.pdf
Out of curiosity, why? It seems to me like what you want to achieve might be possible another way.
From the PDF:
The following example illustrates how to route traffic from different sources to different
places (next hops). Packets arriving from source 22.214.171.124 are sent to the next hop at 18.104.22.168;
packets arriving from source 22.214.171.124 are sent to the next hop at 22.214.171.124.

access-list 1 permit ip 184.108.40.206
access-list 2 permit ip 184.108.40.206

! interface fastethernet 3/1
ip policy route-map Texas
! route-map Texas permit 10
   match ip address 1 set ip next-hop 184.108.40.206
! route-map Texas permit 20
   match ip address 2 set ip next-hop 126.96.36.199

Though in your case instead for fastethernet 3/1 you would put the vlan interface that you want the source routing to occur. If you copy and paste this code into a text editor and change the IPs and the interface to what you need you can paste it right into config mode on the switch
Comment: Looks promising, but also quite complex; can you give some sample configuration?
Comment: updated accordingly.
Comment: Seems exactly what I was looking for, I'm going to try it on Monday. Thanks.
Comment: Tried, but it doesn't work; when I try to give the command "ip policy route-map X" to a given interface (physical or VLAN), it just doesn't accept the keyword "policy". WTF?!?
Comment: It is possible that your version of IOS doesn't support these commands. can you post the output of `show version` in your original question?
Comment: Done. *SomeRandomTextToFulfillThe15CharactersLimit.*
Answer: As per einstiien's answer, the right thing to do is to use PBR. Unfortunately, you're using an IP Base feature set and the PBR functionality is not available in that feature set, so you'd need to buy PBR instead.
Would it be possible to simply make the management uplink part of the managemenet VLAN and provide routing to the management station? That would allow all other VLANs access to the management station via that route, but that may be fixable by providing traffic-blocking ACLs further down the line (or, possibly, on the switch itself, I can't say I recall exactly what you can and cannot do with ACLs on switch ports right now).
Comment: That's what we are doing now; but it's a bad solution for various reasons, and PBR would be a lot better.
I'll see if we can do a IOS upgrade; what feature set is actually needed?
Comment: The lowest I can find is "IP Services".


Angular - Can I use $mdDialog in Http Interceptor Service?

Question: I'm using http interceptor to handle errors. Is it possible to use md-dialog to pop up a window showing error messages once some certain errors are captured. A circular dependency error occurs when injecting $mdDialog into the service. Where should I bind errorMsg if $mdDialog can be used in this service?
interceptor:
.factory('httpInterceptor', ['$q', '$mdDialog', function($q, $mdDialog){
   return {
        'response': function(res) {
            var status = res.data.status;
            var errorMsg = res.data.payload.message;
            if(status === 'fail') {
              $mdDialog.show({
               // controller: ???,
               // scope: ???,
                templateUrl: 'error.html',
              })
              return $q.reject(res);
            }
            return res;
        }
     }
}])

Answer: Yes you can display the $scope variable using a controller and resolve,
 $mdDialog.show({
      controller: function($scope, $mdDialog){
        // do something with dialog scope
      },
      template: '<md-dialog aria-label="My Dialog">'+
                    '<md-dialog-content class="sticky-container">{{test}}' +
                    '</md-dialog-content>' +
                    '<md-button ng-click=close()>Close</md-button>' +
                    '</md-dialog>',
      controller: 'modalCtrl',
       resolve: {
        test: function () {
          return 'test variable';
        }
      }
    });

Controller:
app.controller('modalCtrl', function($scope, $mdDialog, test) {
  $scope.test = test;
});

DEMO
Comment: i think his problem is if he can use it inside a httpInterceptor that is declared on the configure path of angular
Comment: You've got `controller` twice in `$mdDialog.show()`
Comment: Yes @PauloGaldoSandoval
Comment: @PauloGaldoSandoval use a controller as above and get the data from the service


SQL Server 2012 - Two Table query

Question: Using SQL Server 2012 Express
I have two tables, groupsmembers1 and groupsmembers2.
Both tables contain four columns: groupname, membername, memberaddress, ID.
The tables are populated with group and member data from AD (1) and Domino (2).
The desire is to compare the groupname(s) and memberaddress(es) (between the two tables) to identify where a group and/or groupmember does/does not exist in either directory.
Both tables look similar to below:
ID      GroupName  MemberName   MemberAddress
4033    group1     membername1  memberaddress1
4034    group1     membername2  memberaddress2
4035    group1     membername3  memberaddress3
4036    group1     membername4  memberaddress4
4037    group2     membername22 memberaddress22
4038    group2     membername23 memberaddress23
4039    group2     membername24 memberaddress24
4040    group2     membername25 memberaddress25

My difficulty is building a query that will show me every group, from both tables, with each member even if one table does not have that exact entry.
I have tried this (and variations) from tons of posts I have read related to combining table data, joining tables and the like.
select a.GroupName, a.memberaddress, d.groupname, d.memberaddress
from [groupsmembers1] a
join [groupsmember2] d on a.groupname = d.GroupName
where a.groupname like '%somegroupname%'

The query above gives me 49 rows of data like this (when table groupsmembers1 has 9 rows and table groupsmembers2 only has 7 rows for %somegroupname%:
groupname     memberaddress     groupname       memberaddress
somegroupname memberaddress1    somegroupname   memberaddress1
somegroupname memberaddress2    somegroupname   memberaddress1
somegroupname memberaddress3    somegroupname   memberaddress1
somegroupname memberaddress4    somegroupname   memberaddress1
somegroupname memberaddress5    somegroupname   memberaddress1
somegroupname memberaddress6    somegroupname   memberaddress1
somegroupname memberaddress7    somegroupname   memberaddress1
somegroupname memberaddress1    somegroupname   memberaddress2
somegroupname memberaddress2    somegroupname   memberaddress2
somegroupname memberaddress3    somegroupname   memberaddress2
somegroupname memberaddress4    somegroupname   memberaddress2
somegroupname memberaddress5    somegroupname   memberaddress2
somegroupname memberaddress6    somegroupname   memberaddress2
somegroupname memberaddress7    somegroupname   memberaddress2

I am new at this and realize my table design is probably part of my issue.  Can anyone suggest a query that could help me?
Desired results:
groupname1    memberaddress1    groupname2      memberaddress2
somegroupname memberaddress1    somegroupname   memberaddress1
somegroupname memberaddress2    somegroupname   memberaddress2
somegroupname memberaddress3    somegroupname   memberaddress3
somegroupname memberaddress4    somegroupname   memberaddress4
somegroupname memberaddress5    somegroupname   memberaddress5
somegroupname memberaddress6    somegroupname   memberaddress6
somegroupname memberaddress7    somegroupname   memberaddress7
somegroupname memberaddress8    null            null
somegroupname memberaddress9    null            null

Thank you for your time and any assistance you can provide.
Comment: `FULL OUTER JOIN` will solve your problem
Answer: Your table structure does have some issues.  Check out third normal form.
You really should have separate tables for Member, Address, and Group.  Along with the appropriate join tables to relate all of those together.
Having said that, I think this will help:
select a.GroupName, a.memberaddress, d.groupname, d.memberaddress
from [groupsmembers1] a full outer join [groupsmember2] d
    on a.GroupName = d.GroupName
        and a.MemberName = d.MemberName
where a.groupname like '%somegroupname%'

Comment: Thank you for the reply and the pointer to better table design. I will definitely redesign the tables prior to the next run of this.

when using the query above, it only returns the 7 rows where the membernames match, leaving the two that do not match, out.  Is there a way to show all members for each group, even if there isn't a match in the other table?
Comment: I figured it out!!  Thank you so much for the assistance.

SQL Server 2012 - Two Table query


How to change color dynamically on a circle programmatically

Question: Update: Thx for the answers, problem solved.
Yes code is missing, I am using Mapsforge library.
It had nothing to do with anything else than a bad comparison in a sqlite lookup
which resulted no calling of toggleColor(). Now it works just fine!
Hi I am having trouble changing the color of a circle drawn on a canvas. The other color represents a different state of the circle.
It works fine with onTap i.e when I tap the circle on the screen, but when I try to do it programmatically like
circle.toggleColor() and then
circle.requestRedraw() nothing happens.
How can I make this work programmatically?
<code>@Override
public boolean onTap(LatLong geoPoint, Point viewPosition, Point tapPoint) {
        if (this.contains(viewPosition, tapPoint)) {
                toggleColor();
                this.requestRedraw();
                return true;
        }
        return false;
}
@Override

private void toggleColor() {
        if (this.getPaintFill().equals(LongPressAction.GREEN)) {
                this.setPaintFill(LongPressAction.RED);
        } else {
                this.setPaintFill(LongPressAction.GREEN);
        }
}
</code>
Comment: `requestRedraw` there is no such method in any class in the SDK
Comment: You should paste all code relevant to your question here.Otherwise it's hard to find the reason.
Answer: Thx for answering
Yes code is missing in the snippet, I am using Mapsforge library.
It had nothing to do with anything else than a bad comparison in a sqlite lookup which resulted no calling of toggleColor(). Too much time spent on chasing that stupid mistake...
Now it works just fine!


Dividing an amount proportionately among unequal amounts

Question: I have \$100000. I want to divide the amount proportionately to 300 employees.  I want the money divided inversely from the top down. So, the top earner get \$0 and the lowest paid employee(s) get the most.  If there are 10 employees at the lowest pay rate, they all get the same amount. Is there a formula or program I can create to create this?
Comment: Two questions: 1) How is the distribution of ranked enployees? (v.g. Do you have 290 employees at each own ranking and the bottom 10 employees sharing a 291th rank?)  2) By inversely, do you have some pattern? (v.g. lineal, harmonic, geometrical?)
Comment: Distribution is not linear.  There may be 1 that makes 100000 so he gets 0 but there may be 5 that make 50000 and 3 that make 100.  By inversely I mean the highest paid gets no increase and the lowest paid gets the most, going from 0 at the highest salary to the max. amount for the lowest paid.
Comment: Okay, let's say we have tree employees, each one earns respectively `$`100,000 , `$`50,000 and `$`10,000.  Now, you have a $9.000 bonus.  In this simpler problem do you have an idea of how to distribute?  `$`0; `$`3,000; `$`6.000? `$`0; `$`1.500; `$`7.500?  `$`0; `$`4,000; `$`5,000? (each one of these sample distribution has it's own logic)
Comment: Yes I understand what you're saying.  So it cannot be solved linearly?  I would want it linearly if possible.
Comment: Actually the `$`0, `$`4,000, `$`5,000 example is an inverse linear distribution, taking as variable how less each employee has to get the top salary (respectively `$`0, `$`40,000, `$`50,000) and have a direct linear relationship between this variable and how much each one gets.
Comment: You'll get the most sensible results if you open excel, fill column A with the number of people in each income group, fill column C with Ai*Bi and fiddle with column B until SUM(C:C) is exactly \$1000000.
Comment: What is Ai and Bi?
Comment: What if there are 10 making 40,000?
Answer: According to conversation in the comment session, employees are ranked by the salary group and the distribution of the \$100,000 bonus should be distributed inversely.  (If it is proportionally inversely, then top earner will get slightly more than \$0.)
So, let $a_i$ for $i=1,2,\dots,300$ be the salary of each employee, and $A=\max a_i$ be the salary of the top earner.  One posibility is to have an inverse linear distribution using the variable $x_i=A-a_i$, and have each bonus $b_i$  proportional to $x_i$.
In this case we know that $b_i=\alpha x_i$, and that
$$\sum_{i=1}^{300}b_i=100000.$$
Replacing $b_i$:
\begin{align}
\sum_{i=1}^{300}\alpha x_i&=100000 \\
\alpha\sum_{i=1}^{300} x_i&=100000 \\
\alpha\sum_{i=1}^{300} A-a_i&=100000 \\
\alpha\left(\sum_{i=1}^{300} A-\sum_{i=1}^{300}a_i\right)&=100000 \\
\alpha\left(300A-\sum_{i=1}^{300}a_i\right)&=100000
\end{align}
Where $\sum a_i$ is sum of all salaries: the total wage package $W$.  So, from hear we have:
\begin{align}
\alpha(300A-W)&=100000 \\
\alpha&=\frac{100000}{300A-W}
\end{align}
So the bonification of each employee will be:
\begin{align}
b_i &= \alpha x_i\\
b_i &= \frac{100000}{300A-W} x_i\\
b_i &= \frac{100000}{300A-W}(A-a_i)\\
\end{align}

If you prefer an inverse proportional distribution, the distribution variable would be $x_i=\frac1{a_i}$.  However in this distribution the top earner will have a part of the bonus (although a smaller part than the other employees).
A fix to this distribution is to make $x_i=\frac1{a_i}-\frac1A$.

I have treated each salary independently, however if you have only a few possible salaries you can adopt a different strategy:
Let $A_1,A_2,\dots,A_n$ with $n\ll 300$ be the possible salaries and let's assume that $A_1>A_2>\dots>A_n$ (salaries are ordered).
Let $k_i$ be the number of employees that earn $A_i$.
So the total number of employees are $\sum_{i=1}^{n}k_i=300$ and the total wage package is $\sum_{i=1}^{n}k_iA_i=W$.
We define the distribution variable $X_i$ with some inverse criteria, v.g. $X_i = A_1-A_i$ (for the lineal distribution), $X_i=\frac1{A_i}$ (for the inverse proportional distribution), $X_i=\frac1{A_i}-\frac1{A_1}$ (for the shifted inverse proportional distribution), $X_i=i-1$ for a ranked distribution, etc.
Let $B_i$ be the bonus for each salary rank, and have it proportional to the distribution variable $B_i=\alpha X_i$
Now, you have:
$$\sum_{i=1}^{n}k_iB_i=\alpha\sum_{i=1}^{n}k_iX_i=100000,$$
so
$$B_i=\alpha X_i=X_i\frac{10000}{\sum_{i=1}^{n}k_iX_i}.$$
The result of $\sum_{i=1}^{n}k_iX_i$ (or $\sum_{i=1}^{200}x_i$) depends on your criteria for choosing $X_i$.
Comment: Instead of solving this mathematically you can use Excel, as suggested by @KarolisJuodelė.  So write in cell `A1` the salary $A_1$, in `A2` write $A_2$ etc. In `B1` write how many employees earn $A_1$, same for `B2`, etc. In `C1` write $X_1$ according to the formula, v.g. `=A1-A$1`, if you copy this to `C2` you will have `=A2-A$1`, etc. In `D1` write `=B1*C1`. Copy down the column. Then at `D301` have `=SUM(D1:D300)` and have `C1` set to `=C1*100000/D$301` (copy in the next cells)
Comment: you mean E1 set to C1*10000/d$301 in las sentenece?
Comment: Right.  `E1` set to `=C1*100000/D$300`.
Comment: To play with other distributions of $X_i$ you can write other formulas in `C1:C300` such as `=1/A1`, `=1/A1-1/A$1`, `0` (when dragged `C2` will be set to `1`, `C3` to `2`, etc.), or any arbitrary values.
Comment: when i do this in excel the sum of bonuses (I made a column F) does not equal 100000
Comment: You should create `F1` with `=B1*E1`, then the sum of `F1:F300` should be 100000.  That is because `E1...` contains how much you pay to each employee in that salary group, while `F1...` will be the sum of the payments to that salary group.
Comment: I've rechecked it and it doesn't add up.  It's close but not exact.
Comment: Finally! I had typos in my Excel sheet.  It worked great!


Is there a way to automatically cancel an account after 14 days?

Question: I'm working on a website where we are offering trial access and I want a way to automatically cancel an account after the account is more than 14 days old EXCEPT if they have submitted a feedback form in which case they get an additional 7 days (for a total of 21 days).
I think there ought to be a way to do this using Rules or cron but right now I'm stuck.
Answer: Sure you can do this, using the Rules module (and the Webform module for your form). Here is a blueprint about how to do so:
1. Rules Component to block a user
Create a (rather basic) Rules Component to "block" a user, whereas you use a "User" entity as parameter for it.
2. Rule to cancel an account
Create a (rather basic) rule like so:

Rules Event: Before saving a user account
Rules Conditions: None (feel free to add whatever fits)
Rules Action: Schedule the execution of the Rules Component (from step 1), to be executed after 14 days. For this you need to have the "Rules Scheduler" (a sub-module of Rules) enabled. Make sure to use an "id" for this scheduled task that includes the user's uid (you'll need it in Step 3).

Refer to my answer to "How to send an email notification reminder based on a user's date of entry field?" for a sample of a rule that is pretty close to what your rule should look like (especially Step 3 of it).
3. Rule to delete the scheduled rule
Use the Webform Rules module to create a rule like so:

Rules Event: After a webform has been submitted
Rules Conditions: Check the webform Id (to ensure it's the form you want to consider).
Rules Action: Delete the Scheduled rule from Step 2, and Reschedule it to be executed 21 days after there account activation date. For this you'll need the id of the Scheduled task, but if you used the user's uid for that, this should be no problem.

PS: I'm assuming this is about D7 ...
Answer: You can do this using hook cron or rules also
contrib module available for your requirement  https://www.drupal.org/project/user_expire