Rules erases the last value inserted

Question: i've an import module built with Rules which imports my users. An user can have one or many conventions. I manage these conventions with taxonomy. Conventions are store in my user fields, 'Number of values' under Field settings as 'Unlimited'
My point is, i cannot add many conventions to an user, only the last convention keep in store.
This is how i did:
<code>{ "rules_updatepartenaireslistbatch" : {
    "LABEL" : "UpdatePartenairesListBatch",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "wsclient", "rules_conditional" ],
    "ACTION SET" : [
      { "data_create" : {
          "USING" : {
            "type" : "wsclient_ws_applicam_partenaire_FiltresPartenaire",
            "param_codePartenaire" : [ "" ],
            "param_complet" : 0,
            "param_conventions" : [ "" ],
            "param_raisonSociale" : [ "" ],
            "param_statutCode" : [ "" ],
            "param_typesAttribut" : [ "" ],
            "param_ville" : [ "" ],
            "param_top" : "20"
          },
          "PROVIDE" : { "data_created" : { "data_filtrepartenaire" : "Created data" } }
        }
      },
      { "data_create" : {
          "USING" : {
            "type" : "wsclient_ws_applicam_partenaire_GetListePartenaires",
            "param_numSite" : "1058",
            "param_filtres" : [ "data-filtrepartenaire" ]
          },
          "PROVIDE" : { "data_created" : { "data_getlistpartenaire" : "Created data" } }
        }
      },
      { "wsclient_ws_applicam_partenaire_GetListePartenaires" : {
          "USING" : { "param_parameters" : [ "data-getlistpartenaire" ] },
          "PROVIDE" : { "result" : { "result_list_partenaire" : "GetListePartenairesResponse" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "result-list-partenaire:GetListePartenairesResult" ] },
          "ITEM" : { "partenaire_item" : "Current list item" },
          "DO" : [
            { "data_convert" : {
                "USING" : { "type" : "text", "value" : [ "partenaire-item:id" ] },
                "PROVIDE" : { "conversion_result" : { "string_id" : "Conversion result" } }
              }
            },
            { "entity_query" : {
                "USING" : {
                  "type" : "user",
                  "property" : "name",
                  "value" : "PART_[string-id:value]",
                  "limit" : "1"
                },
                "PROVIDE" : { "entity_fetched" : { "part_fetched" : "Fetched entity" } }
              }
            },
            { "CONDITIONAL" : [
                {
                  "IF" : { "data_is_empty" : { "data" : [ "part-fetched:0" ] } },
                  "DO" : [
                    { "entity_create" : {
                        "USING" : {
                          "type" : "user",
                          "param_name" : "PART_[string-id:value]",
                          "param_mail" : "PART_[string-id:value]@here.invalid"
                        },
                        "PROVIDE" : { "entity_created" : { "entity_part" : "Created entity" } }
                      }
                    },
                    { "entity_save" : { "data" : [ "entity-part" ], "immediate" : 1 } },
                    { "user_add_role" : { "account" : [ "entity-part" ], "roles" : { "value" : { "5" : "5" } } } },
                    { "user_unblock" : { "account" : [ "entity-part" ] } }
                  ]
                },
                { "ELSE" : [
                    { "variable_add" : {
                        "USING" : { "type" : "user", "value" : [ "part-fetched:0" ] },
                        "PROVIDE" : { "variable_added" : { "entity_part" : "Added variable" } }
                      }
                    }
                  ]
                }
              ]
            },
            { "LOOP" : {
                "USING" : { "list" : [ "partenaire-item:conventions" ] },
                "ITEM" : { "convention" : "Current list item" },
                "DO" : [
                  { "entity_query" : {
                      "USING" : {
                        "type" : "taxonomy_term",
                        "property" : "name",
                        "value" : [ "convention:libelle" ],
                        "limit" : "1"
                      },
                      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
                    }
                  },
                  { "CONDITIONAL" : [
                      {
                        "IF" : { "data_is_empty" : { "data" : [ "entity-fetched" ] } },
                        "DO" : [
                          { "entity_create" : {
                              "USING" : {
                                "type" : "taxonomy_term",
                                "param_name" : [ "convention:libelle" ],
                                "param_vocabulary" : "conventions"
                              },
                              "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
                            }
                          },
                          { "entity_save" : { "data" : [ "entity-created" ], "immediate" : 1 } }
                        ]
                      },
                      { "ELSE" : [
                          { "variable_add" : {
                              "USING" : { "type" : "taxonomy_term", "value" : [ "entity-fetched:0" ] },
                              "PROVIDE" : { "variable_added" : { "entity_created" : "Added variable" } }
                            }
                          }
                        ]
                      }
                    ]
                  },
                  { "data_set" : {
                      "data" : [ "entity-part:field-conventions:0" ],
                      "value" : [ "entity-created" ]
                    }
                  },
                  { "entity_save" : { "data" : [ "entity-part" ], "immediate" : 1 } },
                  { "drupal_message" : { "message" : [ "entity-created:name" ] } }
                ]
              }
            },
            { "component_rules_update_partenaire" : { "user" : [ "entity-part" ], "partenaire" : [ "partenaire-item" ] } }
          ]
        }
      }
    ]
  }
}
</code>
The aim is simple.
- I get all users from a webservice
- I do a loop on users
    - I loop on user conventions
        - if convention doesn't exist as taxonomy term, i create it
        - else, I had the taxonomy term in a variable
        - I use a "set_data" to add the convention to the user
Ex: one of my user has "SPORT" and "CINEMA" in conventions. Only "CINEMA" is stored.
Comment: What's a "boucle"? In English that's a _yarn with a looped or curled ply, or fabric woven from this yarn._ Perhaps not what you meant :)
Comment: please apologize, i've fixed :)
Answer: Check if the Taxonomy user field (Convention) allows multiple values.

Go to Admin > Configuration > People > Account Settings > Manage Fields
Edit the Term Reference field (in your case, Convention)
Set 'Number of values' under Field settings as 'Unlimited' or 2 or as desired
Save
Execute the rule and check

Hope this helps.
Regards,
Supriya Rajgopal
Comment: Thank for your reponse but unfortunately, i've already applied this configuration :(
Comment: @billyJoe add this info to your question, or emphase it more if it's already there, please. I couldn't see it, and Supriya's answer is most obvious thing to tell when somebody does not know you already checked it.
Comment: i've added this information to my initial post.
Answer: Resolved !
I had simply to replace the data set by "Add an item to a list". So i had each convention in my loop in the user's convention list.

Rules erases the last value inserted


Transformar um Array Json em outro JSON usando node

Question: Bom dia,
Estou com um problema na montagem de um JSON usando NodeJS.
Tenho um retorno de um SQL gigante que segue basicamente a estrutura abaixo.
[
  {
    "numDoc":"0000001",
    "OutrosCampos":"outrosDados",
    "itens":[
      {
        "itemNum":"000000001",
        "nome":"AAAAAAAAA",
        "agrup":"00003",
        "numDoc":"0000001"
      },
      {
        "itemNum":"000000002",
        "nome":"BBBBBBB",
        "agrup":"00003",
        "numDoc":"0000001"
      },
      {
        "itemNum":"000000003",
        "nome":"CCCCCCCCCC",
        "agrup":"00003",
        "numDoc":"0000001"
      }
    ]
  }
]

e preciso que meu JSON siga a seguinte estrutura de saída:
[
  {
    "numDoc":"0000001",
    "OutrosCampos":"outrosDados",
    "itens":[
      {
        "agrup":"00003",
        "itensAgrup":[
          {
            "itemNum":"000000001",
            "nome":"AAAAAAAAA"
          },
          {
            "itemNum":"000000002",
            "nome":"BBBBBBB"
          }
        ]
      },
      {
        "agrup":"00004",
        "itensAgrup":[
          {
            "itemNum":"000000003",
            "nome":"CCCCCCCCCC"
          }
        ]
      }
    ]
  }
]

Resumindo, preciso que o primeiro array (que tem o numDoc) continue intacto, que o segundo array (o itens) seja separado por um array pelo agrupamento, em que não aparecesse mais o campo repetido numDOC e nem o agrupamento se fosse possível.
Estou usando nodeJS e também diversas "packages" como o underscore mas não estou conseguindo transformar o array neste JSON.
OBS: Preciso ler chave e valor, pois esta estrutura, pode variar os nomes dos campos e a quantidade de itens, por isso não posso tentar colocar em um "array" fixo.
Qualquer dúvida, podem falar.
Grato pela ajuda desde já.
Answer: Utilizando javascript puro, ficou da seguinte forma:

var retorno = [{
  "numDoc": "0000001",
  "OutrosCampos": "outrosDados",
  "itens": [{
    "itemNum": "000000001",
    "nome": "AAAAAAAAA",
    "agrup": "00003",
    "numDoc": "0000001"
  }, {
    "itemNum": "000000002",
    "nome": "BBBBBBB",
    "agrup": "00003",
    "numDoc": "0000001"
  }, {
    "itemNum": "000000003",
    "nome": "CCCCCCCCCC",
    "agrup": "00003",
    "numDoc": "0000001"
  }, {
    "itemNum": "000000004",
    "nome": "CCCCCCCCCC",
    "agrup": "00004",
    "numDoc": "0000001"
  }]
}];

// Variável com o valor final da conversão
var novoRetorno = [];

retorno.map(function(item) {

  // Objeto temporário, será inserido no final
  var tmp = {
    numDoc: item.numDoc,
    OutrosCampos: item.OutrosCampos,
    itens: [],
  };

  // Objeto temporário, será utilizado para armazenar os itens agrupados
  var tmp2 = {};
  item.itens.map(function(item2) {
    // Cria o agrupamento caso não exista, se existir utiliza ele
    tmp2[item2.agrup] = tmp2[item2.agrup] || {};
    // Define o nome do agrup
    tmp2[item2.agrup].agrup = item2.agrup;
    // Resgata os itens já criados ou cria um array vazio
    tmp2[item2.agrup].itensAgrup = tmp2[item2.agrup].itensAgrup || [];
    // Inseri no array de itens o novo item
    tmp2[item2.agrup].itensAgrup.push({
      itemNum: item2.itemNum,
      nome: item2.nome,
    });
  });

  // Loop para remover a key e inserir o objeto puro
  for (var key in tmp2) {
    if (tmp2.hasOwnProperty(key)) {
      tmp.itens.push(tmp2[key]);
    }
  }

  // Insere o objeto final no retorno
  novoRetorno.push(tmp);

});

// Magic!
console.log(novoRetorno);
Answer: Comece criando um mapeamento e depois transforme para o formato desejado.

var objeto = [
  {
    "numDoc":"0000001",
    "OutrosCampos":"outrosDados",
    "itens":[
      {
        "itemNum":"000000001",
        "nome":"AAAAAAAAA",
        "agrup":"00003",
        "numDoc":"0000001"
      },
      {
        "itemNum":"000000002",
        "nome":"BBBBBBB",
        "agrup":"00003",
        "numDoc":"0000001"
      },
      {
        "itemNum":"000000003",
        "nome":"CCCCCCCCCC",
        "agrup":"00004",
        "numDoc":"0000001"
      }
    ]
  }
];

var agrupar = objeto[0].itens.reduce(function(obj, item){
    obj[item.agrup] = obj[item.agrup] || [];
    var valores = { "itemNum": item.itemNum, "nome": item.nome };
    obj[item.agrup].push(valores);
    return obj;
}, {});

var grupos = Object.keys(agrupar).map(function(key){
    return {agrup: key, itensAgrup: agrupar[key]};
});

objeto[0].itens = grupos;
console.log(objeto);

reduce e map, permitem que você obtenha construções poderosas de alto nível que podem poupar tempo e código comparado à iteração manual.
Comment: opa, usando a sua resposta, se eu quisesse inserir uma outra informação, antes de agrupamento de itens, tipo,
{...
  {agrup : 000003,
   nomeAgrup : ZZZZZZZ,
   itens: [...
adicionar somente essa linha nome agrup, que está, no array original, junto com o código dos itens, como seria ?
Answer: Eu nunca usei underscore, mas de acordo com a documentação funcionaria se você aplicasse assim, considerando resp como o retorno do SQL:
_.groupBy(resp[0].itens, function(item) { return item.agrup; });


React useEffect() localhost API fetching doesn't work

Question: I'm having trouble with my ReactJS application. I'm trying to fetch data from an API that I've written (in GOlang) which is running on localhost:9090.
I'm trying to fetch data like this (setters takes 'TEST' for testing purpose)
function ImamsDetails() {
    const [firstName, setFirstName] = React.useState(null);
    const [lastName, setLastName] = React.useState(null);

    React.useEffect(() => {
        fetch('http://localhost:9090/imams/1')
            .then(results => results.json())
            .then(data => {
                setFirstName('TEST');
                setLastName('TEST');
            });
        }, []);

    return (

            Name: {!firstName || !lastName ? 'Loading...' : `${firstName} ${lastName}`}

    );
}

I've tried to change localhost to 127.0.0.1 or my computer IP address, it doesn't work. It is stuck on "Loading...". Whereas, if I change the URI to a distant fake API like https://jsonplaceholder.typicode.com/todos/1 it works fine.
My API returns something like this :
{"Id":1,"FName":"XXX","LName":"YYY","PersonType":2,"GivenAudios":null}

which is the same format as the link posted below.
Any thought why it doesn't work with localhost?
Comment: Ok, I've added the header ("Access-Control-Allow-Origin") on the response on the API and now it works fine, it was as stupid as that. Thank you for your help. How can I endorse you or something ?
Comment: can you try adding a `catch` and inspecting the error on `fetch`?
Comment: I have this message "Access to fetch at 'http://localhost:9090/imams/1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
Comment: Nah, just Happy to help
Answer: Are you using create-react-app? You should set up proxy in your package.json so you could fetch data from external urls. Here you can read more in React documentation.
Add this to your package.json:
"proxy": "http://localhost:9090"


Optimizing Neural Network speed for larger inputs (Facial Recognition)

Question: I am building a neural network to recognise the difference between male and female. The issue is that I have a database with a collection of 250x250 pixels (Not x 3 since I convert to grey-scale). Meaning the input layer consist of 62500 neurons. I use 1 hidden layer with 5 neurons. There are 5000+ images. This is allot of computations that needs to be done. Simply too much.
So my what I want to know is if there are better/quicker techniques and ways to use when working with such a large input?
Answer: two simple tricks that might be useful:
1. reduce the resolution (for many tasks we can reduce the resolutions considerably without losing too much information, maybe try something like 30*30 as a starting point
2. batch size do not need to be very large (maybe around 20 will do for this task?
If available, using GPU could be a lot faster.
For deeper networks, there're tricks like pooling and stride that can reduce the size of input for subsequent layers.
Please feel free to correct me where I'm wrong. :)


Ordenar um array em JavaScript

Question: Olá. Estou com um problema e não estou conseguindo resolver.
EU tenho um texto dentro de um array com várias letras aleatórias.
Ex:"vwv rhjs vqgvcq pjdvb gjpsmc jsm zhctgvl jwgbbs" e por assim vai, são 600 palavras.
Eu preciso ordenar as palavras em ordem alfabética, porém não na ordem do nosso alfabeto. Mas esse alfaberto personalizado,a ordem das letras é
"k,b,w,r,q,d,n,f,x,j,m,l,v,h,t,c,g,z,p,s.
Já tentei passar tudo para float, e tentar ordenar com o Sort(), mas não deu certo. Alguém poderia me ajudar com isso?
Comment: No caso estão faltando as letras "aeiouy"
Comment: Texto dentro de um array? Ou cada palavra é um elemento da array?
Comment: Então, o texto nem está num array. É apenas um texto.. Eu que coloquei ele em um array...
Comment: Tá faltando letra aí na sua ordem
Comment: Entao... mas esse alfabeto personalizado, são só essas letras... não tem as demais.
Comment: Mas as demais aparecem antes ou depois das que mencionou ?
Answer: Aí você tem que usar uma função comparando os itens de acordo com o valor da posição das letras na string que você ordenou. Usando .indexOf() você acha a posição da primeira letra no índice [0], mas você terá que quebrar o texto da array para usar o .sort():

var string = ["sap vwv rhjs vqgvcq pjdvb pwzs gjpsmc jsm zhctgvl jwgbbs pwz"];
var alfa = "k,b,w,r,q,d,n,f,x,j,m,l,v,h,t,c,g,z,p,s";
string[0] = string[0].split(" ").sort(function(a, b){

   // faz uma comparação de tamanho da palavra para
   // fazer o laço "for" mais abaixo pela palavra que for maior
   var len = a.length > b.length || a.length == b.length ? a.length : b.length;

   // só faz o "return" quando uma letra for diferente da outra
   for(var x=0; x < len; x++){
      if(a[x] != b[x]) return alfa.indexOf(a[x])-alfa.indexOf(b[x]);
   }

}).join(" ");
console.log(string);

O string[0].split(" ") quebra o texto do índice [0] da array pelo espaço em branco.
O alfa.indexOf(a[x])-alfa.indexOf(b[x]) compara a posição das letras de cada palavra pela anterior na string alfa e monta um novo array organizado, e o .join(" ") converte em string separando os itens da array por um espaço, atribuindo um novo valor ao string[0], agora com as palavras na ordem.
Comment: Então, deu certo para a primeira letra... Ele ordenou, mas quando a varias palavras iniciando com a mesma letra, ele nao ordena na ordem correta.
Comment: To quebrando a cabeça aqui o fds de semana interiro, nao consegui. o Mais proximo que conseguir foi transformar tudo para int com o indexof, e depois tentar comparar o com sort() usando uma function => p1-p2. Porém, quando transformo tudo em numero, vira um array assim : [1,12,13,2] e quando peço pro sort comparar dois arrays dessa forma, ele nao consegue... mas se eu juntar o array, [12 2 12 2] ai o sort entendo que é tudo um numero só.
Comment: Veja agora.....
Comment: Show de bola.. Obrigado pela ajuda...
Comment: TRanquilo! Saiba como agradecer [neste link](https://pt.stackoverflow.com/tour) ;)
Answer:
Crie um dicionário das letras na ordem que você quer dentro de um array;
Crie um array com as letras normais do alfabeto;
Separe as palavras da frase que você quer com split por espaço;
Indexe as palavras resultantes utilizando o dicionário criado anteriormente, assim você terá um array com palavras transformadas em números. No seu exemplo você terá o seguinte:
[[12,2,12], [3,13,9,19], [12,4,16,12,15,4], [18,9,5,12,1], [16,9,18,19,10,15], [9,19,10], [17,13,15,14,16,12,11], [9,2,16,1,1,19]]

Faça a equivalencia entre os índices gerados e o alfabeto normal para obter uma lista de palavras equivalentes. No seu exemplo você terá o seguinte:
['mcm', 'dnjt', 'meqmpe', 'sjfmb', 'qjstkp', 'jtk', 'rnpoqml', 'jcqbbt']

Utilize o sort para ordenar as palavras resultantes, obtendo:
['dnjt', 'jcqbbt', 'jtk', 'mcm', 'meqmpe', 'qjstkp', 'rnpoqml', 'sjfmb']

Indexe a equivalencia ordenada e utilize o array dicionário para transformar os índices em palavras novamente, obtendo o seguinte resultado após unir o array resultante em uma nova frase:
rhjs jwgbbs jsm vwv vqgvcq gjpsmc zhctgvl pjdvb

const DICIONARIO = ['k', 'b', 'w', 'r', 'q', 'd', 'n', 'f', 'x', 'j', 'm', 'l', 'v', 'h', 't', 'c', 'g', 'z', 'p', 's'];
const ALFABETO = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm','n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

const indexar = (referencia, palavra) => [...palavra].map((letra) => referencia.indexOf(letra));

const traduzir = (indices) => indices.map((indice) => DICIONARIO[parseInt(indice, 10)]).join('');

const ordenar = (frase) => {
  const indices = frase
    .split(' ')
    .map((palavra) => indexar(DICIONARIO, palavra));

  const equivalentes = indices.map((indice) => indice.map(posicao => ALFABETO[posicao]).join(''));

  equivalentes.sort();

  return equivalentes
    .map((palavra) => indexar(ALFABETO, palavra))
    .map(traduzir)
    .join(' ');
};

console.log(ordenar('vwv rhjs vqgvcq pjdvb gjpsmc jsm zhctgvl jwgbbs'));
Comment: Muito obrigado.
Comment: @RodolfoMori se a resposta te ajudou de um +1 nelas

Ordenar um array em JavaScript


Propriedade height do jQuery e do JavaScript, qual diferença?

Question: Qual a diferença entre $(window).height() do jQuery para o screen.height do JavaScript ?
Usando eles percebo resultados diferentes...
E qual o similar ao screen.height no jQuery ?
Answer: As duas funções tratam de aspectos diferentes:

screen.height = altura baseada na resolução do monitor
$(window).height() = altura da janela do browser

O objeto screen do JavaScript remete a resolução da tela do usuário, de forma que o tamanho da janela do navegador não interfere nos seus valores. Já o objeto $(window) usado pelo jQuery trata justamente da janela do navegador, sendo que $(window).height() é equivalente à função window.innerHeight em JavaScript puro.
O objeto screen não é tratado pelo jQuery. Mas como o @Jader disse na resposta dele, jQuery nada mais é do que JavaScript, ou seja, você pode utilizar screen.height com seu código jQuery sem problemas.
Answer: No jquery o $(window).height() é o tamanho da janela de exibição (viewport), já screen.height é o tamanho total da tela do usuário.
Tenha em mente que jquery é javascript, e você pode usar screen.height nele sem nenhum problema, se o caso for obter o tamanho da tela...


dll replace in a big system

Question: When change the dll, I have to put it in a directory from where the system loads into memory. The problem is that everytime I change it, I have to close the system, replace the dll with a new one and start the system. It takes around 15/20 minutes which isvery long.
Can anyone tell me how to avoid this ?
Answer: When you quickly want to switch DLL versions, place the DLL in the same directory as the executable or provide a path to the directory where you switch your DLLs in Project Settings -> Configuration Properties -> Debugging -> Environment. Then you don't have to mess with you Windows System directory.
However, Microsoft states here:

If a DLL with the same module name is already loaded in memory, the system checks only for redirection and a manifest before resolving to the loaded DLL, no matter which directory it is in. The system does not search for the DLL.

You could try if AlwaysUnloadDLL works for you.
Comment: You mean the DDLs which are already loaded into memory? When they are not loaded already, my answer actually applies. Please see http://msdn.microsoft.com/en-us/library/windows/desktop/ms682586(v=vs.85).aspx and a similar question: http://stackoverflow.com/questions/518228/is-it-possible-to-add-a-directory-to-dll-search-path-from-a-batch-file-or-cmd-sc
If this is not what you are looking for, please explain your problem more clear.
Comment: The Directory in which Visual Studio places the dlls is fixed, I can't change it. The directory from where the system picks up dlls is also fixed and can't be altered. What I need here is some kind of batch program or any utility program, that will kill the processes accessing the dlls, then replace the dlls and then restart the program.
Comment: That Microsoft link is very helpful. I mean the DLLs which are already loaded into memory. I want to replace the DLL files and reload again into memory.

dll replace in a big system


Calculate the determinant of a given matrix

Question: In a classical mechanics exercise i cannot calculate the determinant of the following matrix
$\begin{pmatrix}\left(-\omega ^2-\frac{2k}{m}\right)\: & \:\frac{k}{m}\: & \:0\: & \:0\: \\\frac{k}{m}\: & \:\left(-\omega ^2-\frac{2k}{m}\right)\: & \:\frac{k}{m}\: & \:0\: \\0\: & \:\frac{k}{m}\: & \:\left(-\omega ^2-\frac{2k}{m}\right)\: & \:\frac{k}{m}\: \\0\: & \:0\: & \:\frac{k}{m}\: & \:\left(-\omega ^2-\frac{2k}{m}\right)\end{pmatrix}$
Then it is needed to solve for $\omega$ and i cannot because it gave me $\:\frac{\left(-\omega \:^2-\frac{2k}{m}\right)^2}{\left(\frac{k}{m}\right)^2}-\frac{\left(\frac{k}{m}\right)^2}{\left(-\omega \:\:^2-\frac{2k}{m}\right)^2}=1$
Then i need also to calculate the following system:
$\begin{pmatrix}\left(-\omega ^2-\frac{2k}{m}\right)\: & \:\frac{k}{m}\: & \:0\: & \:0\: \\\frac{k}{m}\: & \:\left(-\omega ^2-\frac{2k}{m}\right)\: & \:\frac{k}{m}\: & \:0\: \\0\: & \:\frac{k}{m}\: & \:\left(-\omega ^2-\frac{2k}{m}\right)\: & \:\frac{k}{m}\: \\0\: & \:0\: & \:\frac{k}{m}\: & \:\left(-\omega ^2-\frac{2k}{m}\right)\end{pmatrix}\cdot \begin{pmatrix}A_1 \\A_2 \\A_3 \\A_4\end{pmatrix}=\begin{pmatrix}0\: \\0\: \\0\: \\0\end{pmatrix}$
Can you help me?
Answer: Rewrite the system as
$$
A =
\frac{k}{m} \overbrace{\pmatrix{
-2&1\\
1&-2&1\\
&1&-2&1\\
&&1&-2&1
}}^{\text{call this matrix } B} - \omega^2 I
$$
It suffices to calculate the characteristic polynomial $p(x) = \det(B - xI)$.  We then have
$$
\det(A) = (k/m)^4p\left(\frac{m\omega^2}{k}\right)
$$
Your system will only have a solution when $p\left(\frac{m\omega^2}{k}\right) = 0$.

You should find
$$
p(x) = x^4 - 8x^3 + 21 x^2 - 20 x + 5 =(x^2 - 5x + 5)(x^2 - 3x + 1)
$$


Nonsensical result that the radius of convergence of the Taylor series of $(c_1z + c_2)^{-1}$ about the origin is infinite

Question: For some reason I seem to get a nonsensical result for the radius of convergence of the following function: Let $c_1, c_2 \in \mathbb{C}\setminus \{0\}$ and $f(z) = \frac{1}{c_1z + c_2}$. Then a quick computation shows that $f^{(n)}(z) = \frac{(-1)^nc_1^n}{(c_1z + c_2)^{n+1}}$ whenever $z\neq \frac{-c_2}{c_1}$. Hence $f(z;0) = \sum_{n=0}^\infty \frac{(-1)^n}{n!}\frac{c_1^n}{c_2^{n+1}}z^n$ is the Taylor expansion of $f$ about the origin.
Now if $\left|z\right| < \left|\frac{c_2}{c_1}\right|$, $f$ is well-defined and the series converges absolutely and uniformly. But, the exact definition of the radius of convergence is
$$\rho \equiv \left(\lim_{n\to\infty}\sup \left(|a_n|\right)^{1/n}\right)^{-1}$$
for the coefficients $a_n$ of a series. In our case $a_n = \frac{(-1)^n}{n!}\frac{c_1^n}{c_2^{n+1}}$, so that
$$\left|a_n\right|^{1/n} = \left|\frac{(-1)^n}{n!}\frac{c_1^n}{c_2^{n+1}}\right|^{1/n}\Longleftrightarrow$$
$$\left|a_n\right|^{1/n} = \left|\frac{1}{n!}\right|^{1/n}\left|\frac{c_1}{c_2}\right|^{1/n}\left|\frac{1}{c_2}\right|^{1/n}$$
Then $\left|a_n\right|^{1/n}\to 0, n\to\infty$, for $\left(\frac{1}{n!}\right)^{1/n}\to 0$. Hence $\rho = \frac{1}{0} = \infty$. But clearly $f$ is not well-defined at $\frac{-c_2}{c_1}$. So what is going on with the radius?
Comment: The $n!$ in your Taylor expansion are wrong.
Comment: More precisely, when you differentiate $f$ you introduce a $n!$ from the successive derivatives so it cancels out leaving the Taylor coefficients as expected
Answer: Your Taylor expansion is incorrect.
$$
\frac{1}{c_1z+c_2} = \frac{1}{c_2} \frac{1}{1 - (- \frac{c_1z}{c_2}) }
$$
This is the sum of a geometric series with initial term $\frac{1}{c_2}$ and ratio $-\frac{c_1z}{c_2}$.
So the Taylor expansion about $z=0$ is $\frac{1}{c_2} \sum_{k=0}^\infty (-\frac{c_1}{c_2})^k z^k$, and the sum converges when $|-\frac{c_1z}{c_2}|< 1 $, i.e. when $|z|< \frac{|c_2|}{|c_1|}$.
This also makes sense since the pole of $f$ is at $z = \frac{-c_2}{c_1}$, so this is the largest possible disk centered at $z=0$ on which $f$ is holomorphic.
I suggest getting really comfortable with geometric series in particular, since the proof of analyticity of holomorphic functions involves using Cauchy's integral formula to represent $f$, expanding the Cauchy kernel $\frac{1}{z - \zeta}$ in a geometric series about the base point $p$, and then integrating term by term.


Java Testng unit test: Spring is not able to create object before BeforeSuite or BeforeTest

Question: I have an unit test is working fine in it's current format. My unit test looks like:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

@Test
@ContextConfiguration(locations = { "classpath:testContext.xml" })
public class DialPadMonitorTest extends AbstractTestNGSpringContextTests
{
    @Autowired
    DialPadMonitor service;

    @BeforeSuite
    public void doBeforeSuite() {
        System.out.println("Initializing suit.........");
    }

    @BeforeTest
    public void doBeforeTest() {
        System.out.println("Initializing tests.........");
    }

    @Test()
    void testIfEasyToDial()
    {
        service.createDialAssociation();

        Assert.assertTrue(service.isNumberEasy(159658521));
        Assert.assertTrue(service.isNumberEasy(555555555));
        Assert.assertFalse(service.isNumberEasy(505555555));
        Assert.assertFalse(service.isNumberEasy(555555505));

        Assert.assertTrue(service.isNumberEasy(2547096));
        Assert.assertTrue(service.isNumberEasy(5547521));
        Assert.assertFalse(service.isNumberEasy(2806547));
        Assert.assertFalse(service.isNumberEasy(3558123));

    }

    @Test()
    void testIfAssociated()
    {
        service.createDialAssociation();

        Assert.assertTrue(service.isNoAssociated(3,3));
        Assert.assertTrue(service.isNoAssociated(3,6));
        Assert.assertFalse(service.isNoAssociated(3,9));

    }
}

Even though I am seeing the comments like

System.out.println("Initializing suit.........");
System.out.println("Initializing test.........");

Problem is that if I move service.createDialAssociation() into any of BeforeSuite or BeforeTest, I am getting null pointer exception.
Any insight on why am I getting the null pointer exception in that case and how to solve?
Answer: If you want to make sure Spring context was loaded fully, add a method anotated with @PostConstruct

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization
Answer: You should use @BeforeMethod instead of @BeforeTest because context is initialized that way. You can see it in a Spring source file.
Answer: Adding
 @BeforeSuite(alwaysRun = true)
 @BeforeClass(alwaysRun = true)
 @Override
 protected void springTestContextPrepareTestInstance() throws Exception {
     super.springTestContextPrepareTestInstance();
 }

solves the issue. Note that this method springTestContextPrepareTestInstance should be executed before all @BeforeSuite methods. This can be achieved by placing it to a separate base class or by adding depenedsOn in others @BeforeSuite annotations.


Database modelagem, quando é possível desnormalizar

Question: Estou modelando um database (MSSQL) e surgiu uma dúvida. Em toda regra de negócio do clientes os dados são visualizados verticalmente ex:

Produto,
Preço Original,
Preço Concorrente01,
Preço Concorrente02,
Preço Concorrente03,
Preço Concorrente04,
Preço Concorrente05
DataLeitura

ou seja definiria logo de cara os 5 concorrentes e na pior das hipóteses teria que adicionar uma nova coluna para um novo concorrente.
Porém meu conhecimento em SQL diz que devo normalizar e colocar os dados horizontalmente, mesmo sabendo que a chances de aumentar um novo concorrente seja ínfima.
ex:

Produto
Preço Original
Preço Concorrente
Id do Concorrente;// 1= concorrente 01, 2=concorrente 02, etc
DataLeitura

Ao fazer da forma tradicional (normalizada), já percebi que terei muito trabalho para gerar os relatórios conforme o cliente deseja, visto que várias linhas na verdade representarão apenas uma única linha para o relatório.
No SQL teria que fazer as consultas com PIVOT
Dúvida:

Qual a forma correta nessa modelagem? Seguindo a regra de negócio do
cliente e ai desnormalizar para facilitar ou sigo as normas rígidas da normalização? Esse é um cenário que pra mim seria uma vantagem desnormalizar.
Comment: Os concorrentes são sempre os mesmos, para todos os produtos?
Comment: não, são 5 concorrentes distintos, sempre cada produto é consutlado em 5 concorrentes.
Comment: @Dorathoto Alguma resposta resolveu o que estava em dúvida? Precisa que algo mais seja melhorado? Acha que é possível aceitá-la agora?
Comment: ainda estou verificando...o que fazer..
Answer: De uma maneira geral o ideal é normalizar. Até que tenha um motivo para não fazer. Eu já respondi sobre isto em termos gerais.
Nunca haverá mais que 5 preços de concorrentes? Acredito que não haverá, né?
Pode arcar com o preço de ter um pequeno espaço ocupado sem uso quando há menos de 5 preços? Acho que não é um problema. Não me parece que essa seja sua preocupação, e nem sempre devemos nos preocupar com isso mesmo. Mesmo que tenha essa preocupação, tem solução, ainda que talvez não simplifique relatórios e outras operações.
Pelos comentários, parece que não só sempre serão 5, mas serão os mesmos. Me parece um caso claro que a normalização só estará sendo feita pra seguir regra. Está desconsiderando o conceito.
Quando vai modelar tem que pensar no conceito em primeiro lugar. Lá na resposta que eu linkei acima fala que há casos que sequer está fazendo desnormalização, o modelo deve ser assim. Não digo que seja este o caso, mas a questão é sempre se perguntar porque está fazendo de uma forma ou outra. Não siga regras, faça o que é certo para aquele caso.
Acha que poderá ter problemas no futuro com uma mudança porque fez do jeito atual? Acho que não. Essa parte do banco de dados é usado por todo o sistema e uma mudança seria um pesadelo? Talvez seja algo muito específico usado em algo pontual.
Nunca pense no melhor modelo para o relatório porque essa é a parte fácil e que não dá problema. Mas nunca desconsidere outros fatores que podem indicar a não necessidade da regra "rígida". Não posso responder com toda certeza porque pode ter um requisito oculto aí, mas parece caso para fazer como quer mesmo.
Answer: Em minha opinião, a modelagem de dados deve ser realizada independente do sgbd. Após terminar a modelagem de dados é que vem a implementação física, quando então pode ser necessário adaptar o modelo de dados às características do sgbd.
(1)
Considerando-se a 3FN, poderíamos ter a seguinte implementação física no sgbd SQL Server:
-- código #1
CREATE TABLE Produto (
  ID_produto int primary key,
  Nome_produto varchar(200) not null,
  Preço money not null
);

CREATE TABLE Concorrente (
  ID_concorrente smallint primary key,
  Nome_concorrente varchar(80) not null
);

e
-- código #2
CREATE TABLE ColetaPreço (
  ID_produto int not null references Produto,
  ID_concorrente smallint not null references Concorrente,
  Data_coleta date not null,
  Preço money not null
);

Pode-se criar uma exibição (view) que retorne os preços de produtos em uma única linha por produto, tornando a visualização independente da implementação física.
Há vantagens e desvantagens nessa implementação.

(2)
Às vezes, por questão de performance, desnormaliza-se alguma entidade para a implementação física. Caso se perceba a necessidade de implementar na 2FN , pode-se então utilizar 5 colunas (uma para cada concorrente). Algo assim:
-- código #3 v2
CREATE TABLE ColetaPreço (
  ID_produto int not null references Produto,
  Data_coleta date not null,
  Preço_concorrente1 money null,
  Preço_concorrente2 money null,
  Preço_concorrente3 money null,
  Preço_concorrente4 money null,
  Preço_concorrente5 money null
);

A desvantagem desta opção é que, se resolverem acrescentar um sexto concorrente na coleta de preços, é necessário alterar a estrutura do banco de dados bem como a programação existente.

(3)
Outra forma mais radical seria armazenar a lista de preços da concorrência em uma única coluna:
-- código #4 v2
CREATE TABLE ColetaPreços (
  ID_produto int not null references Produto,
  Data_coleta date not null,
  Lista_preço varchar(200) not null
);

Cada uma destas opções deve vir com o respectivo conjunto de objetos de manipulação (exibição, função etc), para transformar os dados em algo simples de visualizar.
Comment: então a solução que vou utilizar é essa, horizontal, fiz uma representação simplificada lá em cima, porém nessa visão dificulta os relatórios pro cliente já que é um sistema de BI e tudo neles é vertical. quase pensando em fazer um modo que pra mim é gambiarra pra facilitar o resto.
Comment: vou estudar sobre esses termos 3fn, 2fn, valeu
Comment: sobre o código 3, não vejo o pq de ter Id_Concorrente2, preço2, poderiamos ter uma única coluna PrecoConcorrente2, e assim procurar na tabela concorrentes que é o Id=2.
Comment: No início perguntei se "Os concorrentes são sempre os mesmos, para todos os produtos?", pois estava em dúvida sobre esta parte.  ///  O concorrente 1 do produto 1 (sabão, por exemplo), é o mesmo concorrente 1 do produto 2 (pão de queijo, por exemplo)?  Ao todo, independente de produto, somente são 5 concorrentes?
Comment: sempre são iguais..
Answer: Uma conclusão que cheguei:

Quando desnormalizar ou não uma modelagem?

Por padrão a normalização é sempre um caminho que devemos seguir, nesse meu projeto estava claro que parecia um dos casos raros que a desnormalização até valeria a pena, por algumas regras específicas do cliente.
Então a minha abordagem foi desnormalizar. Porém tinha um parâmetro que não havia comentado na pergunta e que coloco aqui para ajudar quem quiser se aventurar por banco de dados desnormalizado.
Tive bastante problemas ao utilizar EntityFramework, definitivamente ele não é feito para isso!.
Até existe como contornar diversos problemas que estava tendo, porém as soluções eram mais monumentais do que as dificuldades que teria no caso da normalização.
Resumo: Vou normalizar o banco de dados (gerará dificuldades em relatórios e alguns outros pontos) porém EntityFramework + processos assync não estão preparados para bancos de dados fora do padrão. Pode ser que outras linguagens ou até com Ado.net em síncrono, funcione.


invalid parameter in posting offer to facebook api

Question: I have problem with posting offer to page (which I am admin) via facebook api. It'is work, when I post feed to this page, but not for offers. This always return me FacebookSDKException with message : Invalid parameter. I use PHP (Laravel framework), but I think it does not matter on the language I use. I use this code:
<code>try {
        $response = $fb->post('/'  . $page_id . '/offers' , $offerData, (string) $request->access_token
                );
    } catch (\Facebook\Exceptions\FacebookSDKException $e) {
        return response()->json(['error'=>$e->getMessage(),
            ], 200);
    }
</code>
where my "$request->access_token" is page access token. And in my "$offerData" I have this fields:
<code>$offerData =[
        'claim_limit'=>8,
        'expiration_time'=>\Carbon\Carbon::now()->addDays(10)->toDateTimeString(),
        'message'=>"bbb",
        'title'=>"ascvc",
        'coupon_required'=>false,
        'image_url'=>'...',
        'published'=>true,
        'reminder_time'=>\Carbon\Carbon::now()->addDays(5)->toDateTimeString(),
       // 'scheduled_publish_time'=>5
    ];
</code>
I also try do this by curl (not by first code) and by curl it returns similar error message.
<code>"{"error":{"message":"Invalid parameter","type":"OAuthException","code":100,"error_subcode":1528104,"is_transient":false,"error_user_title":"Check Your Admin Permission Level","error_user_msg":"Only some admins of your Page are able to create and edit offers. Talk to the person responsible for your Page about your admin permission level.","fbtrace_id":"..."}}"
</code>
It looks that there is problem with permissions but at login to facebook I set this permissions:
<code>['manage_pages', 'pages_show_list', 'email',
        'user_hometown', 'publish_actions', 'user_photos', 'publish_pages']
</code>
I have no idea where is problem. I must to tell you that feeds on same page works fine, but not offers. Can you help me, please?
Comment: This is not about permissions you ask from the user to grant to your app, but what level of admin permissions the person has assigned in the page settings.
Answer: Take a look at the newer /nativeoffers endpoint; that should be a cleaner path through this one.
https://developers.facebook.com/ads/blog/post/2016/08/30/offer-ads-apis/


Sylvester's sequence - series representation of Vardi's constant

Question: First, a bit of background - Sylvester's sequence is defined recursively as
$$e_{n+1}=\prod_{j=0}^{n-1}e_j=e_n^2-e_n+1, \space\space\space e_0=2$$
and, miraculously, there exists a number $E\approx 1.26$ that satisfies
$$e_n=\lfloor E^{2^{n+1}}+1/2\rfloor$$
Wolfram gives a series representation for the constant $E$ (also called "Vardi's constant"), a proof of which I have been unable to find (or derive):
$$E=\frac{\sqrt 6}{2}\exp\Bigg[\sum_{j=1}^\infty \frac{1}{2^{j+1}}\ln\bigg(1+\frac{1}{(2e_j-1)^2}\bigg)\Bigg]$$
or, reduced to a product,
$$E=\frac{\sqrt 6}{2}\prod_{j=1}^\infty \bigg(1+\frac{1}{(2e_j-1)^2}\bigg)^{2^{-j-1}}$$
Reduced further, this is equal to
$$E=\frac{\sqrt 6}{2}\prod_{j=1}^\infty \bigg(\frac{4e_{j+1}-4}{4e_{j+1}-3}\bigg)^{2^{-j-1}}$$
How might one derive this property? I haven't been able to make much progress with its derivation.
Comment: Did you look at [Aho and Sloane's paper](http://www.fq.math.ca/Scanned/11-4/aho-a.pdf) already?
Comment: http://oeis.org/A076393
Answer:
Caveat: this is a partial answer. I will try to explain the methodology for the construction of the generating function and the definition of the constant (it lacks detail but it should give an overview, if the reader finds errors please be free to fix them or let me know and I will try to fix them). I hope it will help as an idea of how Vardi's constant and its generating function can be developed. So below I will not include the construction of  $E\approx 1.26$ that satisfies $$e_n=\lfloor E^{2^{n+1}}+1/2\rfloor$$ but a similar construction based on another constant that I will call $L$ such that  $L\approx 1.597910225682488561085083110$ that satisfies
$$e_n=\lfloor L^{2^{n}}+1/2\rfloor$$

The difference is that the exponent of my generating function based on the constant $L$ is $2^{n}$ instead of $2^{n+1}$, as in the case of Vardi's $E$.

Basically we observe that the expression below is true:

$$(e_n-1)^2 \lt e_{n+1} \lt e_n^2$$
for Sylvester's sequence:
$2, 3, 7, 43, 1807, 3263443, 10650056950807, 113423713055421844361000443, \dots$
(sequence A000058 in the OEIS).
e.g.
$$(e_0-1)^2 = (2-1)^2=1 \lt e_1=3 \lt e_0^2 = 2^2=4$$
$$(e_1-1)^2 = (3-1)^2=4 \lt e_2=7 \lt e_1^2 = 3^2=9$$
$$(e_2-1)^2 = (7-1)^2=36 \lt e_3=43 \lt e_2^2 = 7^2=49$$
$$\cdots$$

Following the classical Mills demonstration (1947) (please see details of the theorem and proof in the paper) we can conclude that we have a bounded monotone increasing sequence able to generate each $e_n$. The generation of the $L$ constant is as follows:

$$L_0={e_0^{\frac{1}{2^0}}}$$
$$L_1={e_1^{\frac{1}{2^1}}}$$
$$L_2={e_2^{\frac{1}{2^2}}}$$
$$\cdots$$
$$L_5={e_5^{\frac{1}{2^5}}}=1.597910225682488561085083110$$
Where $L$ will be: $$\lim_{n \to \infty} L_n \ .$$ As in the case of the classical results of Mills, we do no know if it is a rational number or whether a closed-form formula could be obtained.
So you will require more precision as $n$ grows higher. With $L_5$ we will be able to calculate accurately $\{e_0,e_1,e_2,e_3,e_4,e_5\}$
The generating function initially would be as follows (it will require a correction I will explain later):
$$e_n = \lfloor L^{2^n} \rfloor$$
e.g. (still without correction):
$$e_5 = \lfloor L^{2^5} \rfloor = 3263443$$
$$e_4 = \lfloor L^{2^4} \rfloor = \color{red}{1806}$$
$$e_3 = \lfloor L^{2^3} \rfloor = \color{red}{42}$$
$$e_2 = \lfloor L^{2^2} \rfloor = \color{red}{6}$$
$$e_1 = \lfloor L^{2^1} \rfloor = \color{red}{2}$$
$$e_0 = \lfloor L^{2^0} \rfloor = \color{red}{1}$$
As you can observe still $e_0 \dots e_4$ are not accurate, but if we add $1/2$ the correction is good enough to make the result of the floor function match the sequence (as you can see the same correction is done in the OP's generating function for Vardi's constant $E$).
$$e_n=\lfloor L^{2^{n}}+1/2\rfloor$$
And now:
$$e_5 = \lfloor L^{2^5} +1/2\rfloor = 3263443$$
$$e_4 = \lfloor L^{2^4} +1/2 \rfloor = 1807$$
$$e_3 = \lfloor L^{2^3} +1/2 \rfloor = 43$$
$$e_2 = \lfloor L^{2^2} +1/2 \rfloor = 7$$
$$e_1 = \lfloor L^{2^11/2} +1/2 \rfloor = 3$$
$$e_0 = \lfloor L^{2^0} +1/2 \rfloor = 2$$
My guess is that the correction is required because, due to the properties of the sequence, we are embedding the sequence into quadratics intervals $(e_n-1)^2 \lt e_{n+1} \lt e_n^2$ instead of intervals of the shape $e_n^2 \lt e_{n+1} \lt (e_n+1)^2$ (which is the same case as Mills' constant but for intervals based on powers of three instead of powers of two. In the case of Mills' constant the correction is not required). I know this point do require a formal explanation but I would dare to say that it is related with the definition of the quadratic intervals.

So we have been able to define the generating function:
$$e_n=\lfloor L^{2^{n}}+1/2\rfloor$$
where
$$L\approx 1.597910225682488561085083110$$

This is basically an overview and lacks a lot of details, but the point is that due to the characteristics of the sequence we can bound it into quadratic intervals. Due to this, there is a monotone increasing sequence that we can embed into a constant, such that a quadratic exponent applied to it (plus the floor function corrected by $+1/2$) is able to recover the embedded sequence. So I think it is safe to say that this has been done by Vardi as well in a similar way. About the calculations of Wolfram, I think they are done by Wolfram's engine backwards, once you have defined properly the generating function and the constant. It can be seen that the precision of $E$ depends on the iteration $e_n$ so as $n$ grows higher we need more precision of $E$ (and same for my example $L$) to recover accurately the element $e_n$ of the sequence.


more than one contact form block?

Question: I have this module enabled
http://drupal.org/project/contact_form_blocks
but I only have one contact form block, which is set to global.  How would I make another contact form block?  Thank you!
Answer: Try Webform, to create many flexible forms. Here is a quote about it (from the module's project page):

... is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.

more than one contact form block?


How to do this query in one query?

Question: eI don't know if what I want to do is possible, but I am curious.
I have a time table that looks like that
timeTable
---------
_id
date

I have another table that stored that with timeinfo that is a ForeignKey to the timeTable
myTable
-------
action
date_id

Now, what I would like to do is updating the date_id with the id of the same date next month.
UPDATE myTable
SET date_id =  (SELECT date + interval '1 month' FROM timeTable INNER JOIN myTabe ON _id = date_id)
;

I know that this query can't work because the query return a date where it does expect an uuid.
My question : Is it possible to retrieve the date_id of the same date the next month with one query without anohter subquery ? That my actual query I don't see how could I do it. Any idea ?
SELECT date + interval '1 month' FROM dimtime INNER JOIN roadmap ON _id = date_id

Comment: I´m afraid you´ll have to use a sub querry to get the id. Why don't you want to use a sub query anyway?
Comment: I don't mind that what I am doing. I just though that because + interval '1 month' is something knew I could trick the query. This question is just out of curiosity.
Comment: Your queries list names of the tables which you did not describe. Please edit your question, I can't really understand what are you trying to do.
Comment: @maksymko : Sorry it was a typo. I just did edit my question.
Answer: Maybe something like this:
Edited
UPDATE myTable t1
SET t1.date_id = (SELECT t2._id FROM timeTable t2 WHERE t2.date = (SELECT t3.date + interval '1 month' FROM timeTable t3 WHERE t3._id  = t1.date_id));

Comment: This works but that not what I was asking. I was asking on hon to do it without a second subquery. Here your solution uses a second subquery
Comment: Ah, sorry, obviously I didnt read your question thoroughly enough. I wouldn't know another way to do it.
Answer: It's a nasty hack, but if your RDBMS supports a deterministic conversion between integer and date datatypes, there is a way to do this without any subqueries at all - but it is almost certain to require changes to existing data.
The solution requires that you use the integer representation of the date as the key in timeTable (rather than arbitrarily assigned values). If you do this, then you can perform date calcuations without the need to look up the date value from timeTable. This removes the need to include timeTable in the query at all (unless you need to validate that the new date exists there). In this scenario, pseudo-SQL for your query would become:
UPDATE myTable
SET date_id =  to_int(to_date(date_id) + interval `1 month`))
;

If the int <-> date conversion is implicit in your RDBMS, it gets even shorter:
UPDATE myTable
SET date_id =  date_id + interval `1 month`
;

However, if you're at the point where you can choose to implement this design, you might be better off discarding the link timeTable and storing a native date type in the target table rather than the integer FK.

How to do this query in one query?


SBS 2011 folder redirection

Question: I would like to disable folder redirection for a user in SBS 2011, but I also want to have desktop and all other folders moved back to client machine.
The problem is when I disable folder redirection and restart the machine I see clear destop on the on the client machine desktop. When I login to server as this user, the desktop is fully loaded on the server as I expect it to load on the client machine.
How to restore folders to client machine?
Comment: Are you using roaming profiles at all?
Comment: @syneticon-dj no we don't
Comment: Should we use roaming profiles together with folder redirection?
Answer: After removing or disabling the Small Business Server Folder Redirection Policy your location redirections should be reverted back to the user's profile directories. The contents should be copied back into the profile directories if the "Move the contents ... to the new location" option was checked upon the original GPO setup. Since it is not moving automatically for some reason, you just can copy (or move) the redirected folder's contents either manually or using a logon script back into the user's local profile.

SBS 2011 folder redirection


Costumizar DB Grid com dados do webservice

Question: Estou criando um sistema simples para testar o funcionamento do Delphi com WebService REST, o primeiro teste é uma busca de dados no banco que neste caso esta funcionando tudo certinho, só que, quando os dados são carregados na DBGrid a visualização fica horrível, gostaria de saber se tem como customizar a visualização destas informações como alterar o nome e o tamanho das colunas.
DBGrid:

Como podem ver, fica muito ruim com esses campos gigantes pra pouca informação e esses títulos da coluna ficam com o nome que chega do WS.
Eu utilizei a ferramenta REST Debugger para fazer essa comunicação do WS com a Grid.
Comment: Em algum evento após os dados serem carregados (talvez no final do evento do botão Pesquisar) faça um *for* das colunas do grid e verifique pelo dataset o tamanho do campo (ex. string(200)), aí calcule o width da coluna, faça por exemplo 200 * 3 e vc terá um tamanho aproximado apropriado ao tamanho do campo.
Comment: Normalmente, quando o `DBGrid` é preenchido em tempo de execução, ele próprio define a propriedade `Width`de cada coluna. Diante isto, alguns ficam com o tamanho muito grande mesmo, em alguns casos é até desnecessário.

Minha sugestão: Já deixe os campos no `DBGrid` configurados para que, ao receber o retorno do REST, apenas preencher e não configurar.
Comment: Bem, se você clicar duas vezes sobre o `Grid` você consegue adicionar os campos que você precisa exibir. Configurar ele é fácil, é só informar o `Title` e o `FieldName` e pronto.
Comment: @LucasdeSouzaCruz meu problema é justamente tentar já deixar configurado, já que eu não consigo adicionar Fields no TFDMemTable para conseguir configurar fields na grid, há não ser que exista outra forma de configura-la, pois eu só conheço utilizando um Query e um DataSource (FireDac).
Comment: @LucasdeSouzaCruz então, o problema é que quando eu clica no FieldName da erro: Cannot open dataset, provavelmente eu tenho que adicionar um novo componente ou configurar alguma coisa no TFDMemTable, mas de qualquer forma eu consegui configurar certinho da forma que queria utilizando a dica do Andrey.
Answer: Em algum evento após os dados serem carregados (talvez no final do evento do botão Pesquisar) faça um for (laço de repetição) das colunas do grid e verifique pelo dataset o tamanho do campo (ex. string(200)), aí calcule o width da coluna, faça por exemplo 200 * 3 e vc terá um tamanho aproximado apropriado ao tamanho do campo.
<code>for i:=0 to dbgrid.columns.count -1 do
begin
  dbgrid.columns[i].width := dbgrid.datasource.dataset.fieldbyname(dbgrid.columns[i].fieldname).size * 3
end;
</code>
Claro que o código acima pode ser melhorado, ele é apenas uma ideia de como fazer. Podes ainda ver o tipo do campo (integer, varchar e etc) e alterar o valor de multiplicação.
Comment: Complemento para a Resposta: Ideal aplicar esta lógica no `onDrawCell` que é um loop automático do Grid.
Comment: @JúniorMoreira Não vejo a necessidade de colocar no `onDrawCell`, porque as colunas não variarão seu tamanho de acordo com o conteúdo do campo, mas sim de acordo com o tamanho no banco, então se executar apenas uma vez logo após a abertura do `dataset` já é o suficiente. Entendo que sua sugestão é válida caso a largura da coluna seja condicional ao conteúdo do campo. Concorda?
Comment: Concordo, a sugestão foi em relação a `Em algum evento após os dados serem carregados`. No `onDrawCell` fica elegante por ser automático e SEMPRE executar no carregamento/recarregamento, não sendo necessário a estrutura extra de repetição `for` (este é meu pensamento lógico para diminuição de código ;D). De qualquer forma o meu +1 já esta dado ;D
Comment: Ah legal, entendi seu objetivo ao colocar no `onDrawCell`, realmente diminui o código, mas ao meu ver consome recursos do sistema sem necessidade pois ele será executado cada vez que o grid for *redesenhado*.. mas ta valendo. Obrigado pelo +1 e pela sugestão. ;)


Erro A coluna 'EXEMPLO' é inválida na lista de seleção porque não está contida em uma função de agregação nem na cláusula GROUP BY

Question: Olá, amigos. Estou tentando realizar uma consulta no SQL SERVER que funcionava perfeitamente no SQLite. Alguém sabe como posso fazer ela funcionar?
Consulta:
SELECT B.CLIENTE, A.CODCLI, SUM(A.VALOR-A.VALORPAGO) AS 'A RECEBER'
FROM ARGCONTASRECEBER A
INNER JOIN ARGCLIENTE B
ON A.CODCLI = B.CODCLI
WHERE A.VALORPAGO < A.VALOR
GROUP BY A.CODCLI

Erro:

Mensagem 8120, Nível 16, Estado 1, Linha 1 A coluna
  'ARGCLIENTE.CLIENTE' é inválida na lista de seleção porque não está
  contida em uma função de agregação nem na cláusula GROUP BY.

Grato desde já!
Answer: Você precisa inserir a coluna cliente no seu GROUP BY, a query atualizada fica da seguinte forma:

SELECT B.CLIENTE, A.CODCLI, SUM(A.VALOR-A.VALORPAGO) AS 'A RECEBER' FROM ARGCONTASRECEBER A INNER JOIN ARGCLIENTE B ON A.CODCLI = B.CODCLI WHERE A.VALORPAGO < A.VALOR GROUP BY B.CLIENTE, A.CODCLI


Computing the Hastings ratio for multinomial distribution as a proposal distribution in Metropolis-Hastings accept-reject step

Question: I have a question concerning calculating the Hastings ratio in a specific case (multinomial proposal distribution).
I consider a discrete vector $M$ with integer values that sum up to some number $N$. In each step of the Metropolis-Hastings algorithm I need to propose a new value for $N$ and a new value of $M$.
Let's denote $q(x \mid y)$ as the proposal distribution, i.e., the conditional probability of proposing a new state $x$ given the previous value was equal to $y$.
We propose a new value $N^*$ according to:
$$
q_1\left(N^*\mid N^{\textrm{prev}} \right) \stackrel{d}{=}  \lfloor T \rfloor, \textrm{ where }
T \sim tNorm(N^{\textrm{prev}}, \sigma).
$$
For proposing a new value of $M$, we introduce:
$$
q_2\left( M^* \mid   N^{*}, M^{\textrm{prev}} \right) \sim Multinomial \left( N^*,\frac{ M^{\textrm{prev}} + s}{ \sum \limits_{i}  M^{\textrm{prev},\;i} + s} \right)
$$
where $s$ is a realisation of a random variable
$$
S \sim N(0, \sigma)
$$
and introduces an additional noise.
To perform a Metropolis-Hastings accept-reject step, we need to calculate the acceptance probability:
$$
r = \min \left(1, \frac{f\left(  x^*  \right) q\left( x^{\textrm{prev}} \mid x^* \right)}{f\left( x^{\textrm{prev}}\right) q\left( x^* \mid x^{\textrm{prev}}\right)} \right)
$$
where $x = [M,N]$.
$$
 \frac{q\left( x^{\textrm{prev}} \mid x^* \right)}{q\left( x^* \mid x^{\textrm{prev}}\right)} =
\frac{q_1( N^{\textrm{prev}}\mid N^{*} ) \;\; q_2\left( M^{\textrm{prev}}\mid  N^{\textrm{prev}}, \frac{ M^{*} + s}{ \sum \limits_{i}  (M^{*,i} + s)} \right)}{ q_1(  N^{*}\mid  N^{\textrm{prev}}  ) \;\; q_2 \left( M^{*}\mid  N^{*}, \frac{ M^{\textrm{prev}} + s}{ \sum \limits_{i}  (M^{\textrm{prev},i} + s)} \right) } =
$$
$$
= \frac{\text{dabsNorm}(N^{\textrm{prev}} \mid N^*, \sigma) }{\text{dabsNorm}(N^* \mid N^{\textrm{prev}}, \sigma)}
\frac{\text{dmultinom} \left( M^{\textrm{prev}}\mid  N^{\textrm{prev}}, \frac{ M^{*} + s}{ \sum \limits_{i}  (M^{*,t} + s)}  \right)}
{\text{dmultinom} \left( M^* \mid  N^*, \frac{ M^{\textrm{prev}} + s}{ \sum \limits_i  (M^{\textrm{prev},i} + s)}\right)},
$$
where $\text{dabsNorm}$ denotes density of absolute value of the floor of a random variable following the normal distribution and $\text{dmultinom}$ density of a random variable following the multinomial distribution.
Is the above calculation correct?~
Edit 1: (based on the first comment) I was missing randomness coming from $S$. Multinomial distribution should be integrated with respect to s, or at least $s^*$ and $s^\textrm{prev}$ should appear:
$$
 \frac{q\left( x^{\textrm{prev}} \mid x^* \right)}{q\left( x^* \mid x^{\textrm{prev}}\right)} =
\frac{q_1( N^{\textrm{prev}}\mid N^{*} ) \;\; q_2\left( M^{\textrm{prev}}\mid  N^{\textrm{prev}}, \frac{ M^{*} + s^*}{ \sum \limits_{i}  (M^{*,i} + s^*)} \right)}{ q_1(  N^{*}\mid  N^{\textrm{prev}}  ) \;\; q_2 \left( M^{*}\mid  N^{*}, \frac{ M^{\textrm{prev}} + s^{\textrm{prev}}}{ \sum \limits_{i}  (M^{\textrm{prev},i} + s^{\textrm{prev}})} \right) } =
$$
$$
= \frac{\text{dabsNorm}(N^{\textrm{prev}} \mid N^*, \sigma) }{\text{dabsNorm}(N^* \mid N^{\textrm{prev}}, \sigma)}
\frac{\text{dmultinom} \left( M^{\textrm{prev}}\mid  N^{\textrm{prev}}, \frac{ M^{*} + s^*}{ \sum \limits_{i}  (M^{*,t} + s^*)}  \right)}
{\text{dmultinom} \left( M^* \mid  N^*, \frac{ M^{\textrm{prev}} + s^{\textrm{prev}}}{ \sum \limits_i  (M^{\textrm{prev},i} + s^{\textrm{prev}})}\right)}.
$$
Comment: You are missing the randomness associated with the generation of $s$: the multinomial density should be integrated wrt $s$, or at the very least, $s^*$ and $s^\text{prev}$  should appear in denominator and numerator.
Comment: Thank you very much!
Answer: The ratio of proposal densities$$\dfrac{\text{dabsNorm}(N^{\textrm{prev}} \mid N^*, \sigma) }{\text{dabsNorm}(N^* \mid N^{\textrm{prev}}, \sigma)}\times
\dfrac{\text{dmultinom} \left( M^{\textrm{prev}}\mid  N^{\textrm{prev}}, \frac{ M^{*} + s^*}{ \sum \limits_{i}  (M^{*,t} + s^*)}  \right)}
{\text{dmultinom} \left( M^* \mid  N^*, \frac{ M^{\textrm{prev}} + s^{\textrm{prev}}}{ \sum \limits_i  (M^{\textrm{prev},i} + s^{\textrm{prev}})}\right)}$$should be
$$\dfrac{\text{dabsNorm}(N^{\textrm{prev}} \mid N^*, \sigma) }{\text{dabsNorm}(N^* \mid N^{\textrm{prev}}, \sigma)}\times
\dfrac{\text{dmultinom} \left( M^{\textrm{prev}}\mid  N^{\textrm{prev}}, \frac{ M^{*} + s^{\textrm{prev}}}{ \sum \limits_{i}  (M^{*,t} + s^{\textrm{prev}})}  \right)}
{\text{dmultinom} \left( M^* \mid  N^*, \frac{ M^{\textrm{prev}} + s^{*}}{ \sum \limits_i  (M^{\textrm{prev},i} +s^{*} )}\right)}$$
and is justified as being a proper Metropolis-Hastings ratio by including the $s$'s within the Markov chain, that is, by setting
$$x=(N,M,s)$$
and by creating a pseudo-target on $s$ that is the
$$S∼N(0,σ)$$
distribution used in the proposal. (Hence its density cancels out in the overall Metropolis-Hastings ratio, being found in both target and proposal.)


Exercise with tensor product base change

Question: I'm refreshing my knowledge of Galois theory and thinking about Galois extensions and splitting fields. Suppose that $k$ is a ground field, $P$ is some polynomial of degree $n$ with a splitting field $K$, and $K_j$ are intermediate fields ($K_1=k$, $K_2=k[x]/P$ and so on).
My hypothesis is that $K\otimes_k K \simeq K \otimes_{K_{n-1}} K$.
I think that it can be deduced straightforward from base change property of tensor product ($A\otimes_C B \simeq (A\otimes_C D)\otimes_D B$), but some problem appears.
$$K\otimes_{K_{n-1}}K_n \simeq (K\otimes_{K_{n-1}} K_{n-2})\otimes_{K_{n-2}}K_n$$
and I have no idea how to proceed to $K\otimes_k K$ from this step.
It will be great if anybody would tell me is it really true and, if it is, help me to finish proof.
Answer: To answer your question years later and get this off the unanswered queue, this will be the case if and only if $k\to K_{n-1}$ is an isomorphism.
Recall that if $L/K$ is a field extension, and $V$ and $W$ are finite-dimensional $L$-vector spaces, then we have
$$
\dim_L(V\otimes_L W) = \dim_L(V)\dim_L(W)
$$
and
$$
\dim_K(V) = [L:K]\dim_L(V).
$$
Let $[K_{n-1}:k] = d$. We have
$$
\deg_k(K\otimes_{K_{n-1}} K) = d\deg_{K_{n-1}}(K\otimes_{K_{n-1}}K) = d[K:K_{n-1}]^2,
$$
while
$$
\deg_k(K\otimes_k K) = [K:k]^2 = ([K:K_{n-1}][K_{n-1}:k])^2 = d^2[K:K_{n-1}]^2.
$$
These two quantities will be equal if and only if $d = d^2,$ which is true if and only if $d = 1.$


Excel: Como fazer um série temporal usando tabela e gráfico dinâmicos com acúmulo de valores na linha?

Question: Gostaria de fazer um gráfico de série temporal em que indicasse os valores acumulados ao longo do tempo. Portanto, não seria uma linha zig-zag, seria uma linha denotando uma evolução, conforme os valores são acumulados.
Para ilustrar, anexo duas imagens. A primeira eu consegui fazer com os recursos tabela dinâmica e gráfico dinâmico. Ele mostra os valores reais e a linha em zig-zag. A segunda (que é a que eu gostaria) fiz "na mão", apenas para ilustrar aqui, não consegui fazer automaticamente. Como seria possível?
Os dados são os que seguem:
Ano     Qtt
1945    1
1961    1
1964    1
1966    2
1970    1
1971    1
1972    1
1973    1
1980    1
1981    3
1982    1
1983    1
1984    2
1986    3
1987    4
1988    1
1989    4
1990    6
1991    11
1992    5
1993    13
1994    6
1995    11
1996    14
1997    23
1998    7
1999    12
2000    12
2001    20
2002    19
2003    58
2004    30
2005    69
2006    223
2007    201
2008    113
2009    71
Ignorado    28
Total Geral 981

Comment: daniel, não consegui inserir os dados através deste site, desculpe, sou muito iniciante por aqui. Coloquei como imagem, espero que possa ter esclarecido melhor. Grato e abraços!
Comment: Eu gostaria de fazer o gráfico da segunda imagem, a partir dos dados abaixo. Note que os valores vão acumulando. Isso que estou chamando de evolução.

Ano Qtt
1945 1
1961 1
1964 1
1966 2
1970 1
1971 1
1972 1
1973 1
1980 1
1981 3
1982 1
1983 1
1984 2
1986 3
1987 4
1988 1
1989 4
1990 6
1991 11
1992 5
1993 13
1994 6
1995 11
1996 14
1997 23
1998 7
1999 12
2000 12
2001 20
2002 19
2003 58
2004 30
2005 69
2006 223
2007 201
2008 113
2009 71
Ignorado 28
Total Geral 981
Comment: Favor editar a pergunta com estas informações e tente colocar o valor na tabela deste site: [https://ozh.github.io/ascii-tables/](https://ozh.github.io/ascii-tables/), para facilitar a sua pergunta a ser respondida.
Comment: Você deseja fazer um gráfico, mas sem utilizar uma coluna extra? Porque se utilizar uma coluna extra é possível adicionando uma fórmula simples em outra coluna, digamos que os valores estão na coluna `B`, então em outra coluna adicione: `=SOMA($B$2:$B2)` e use o auto preenchimento até a última linha. Assim os valores acumulados podem ser vistos.
Comment: Valeu, Daniel, se houver uma solução que não adicione coluna extra, seria melhor, pois são vários gráficos que farei. Mas, de toda a forma, a solução que você apresentou já ajuda! Grato!
Answer: Solução
Você pode utilizar o gráfico do tipo Cascata para visualizar os valores acumulados.
Passo a Passo
1. Selecione os dados:
Selecione os dados a serem vistos no gráfico de acumulados.

2. Inserir gráfico:
Insira o gráfico em Inserir > Gráficos Recomendados > Todos os Gráficos e escolha o Cascata.

Resultado
O gráfico ilustra o valor cumulativo e quanto acumulou em cada ano acima da barra.
Comment: A ideia é exatamente essa e desse jeito fica muito bom. Vou tentar instalar (se é que dá) esse tipo de gráfico no meu excel (2013) já que ele não apresenta essa função. Super valeu!
Comment: Utilizei o Excel 2016 para realizar isto.


Primitive roots and Legendre symbol

Question: One knows that if $a$ is a primitive root modulo $p$, then $(\frac{a}{p})=-1$.
Thus, if $(\frac{a}{p})=1$ we know that $a$ is not a primitive root modulo $p$.
Are there any other properties between Legendre symbol and primitive roots?
Answer: Suppose that $p-1$ is divisible by $3$. If $a$ is a cubic residue of $p$, then $a$ is not a primitive root of $p$. Similarly for other prime divisors $q$ of $p-1$.

Primitive roots and Legendre symbol


Run script while installing war file in Grails

Question: Is it possible to run some sort of script during the installation of a Grails war file?
For example, I would like to copy my app's Config.groovy file to our Tomcat server's conf folder during the installation. This way it can be used as an external config file (instead of having to manually create it and move it there every time). Is something like this possible?
Answer: I think you can use the BootStrap to do that. When your app is initializing, check if you are in the Tomcat (catalina.home prop) and if the file not exists, create.
<code>class BootStrap {
  def init = {
    if(grails.util.Environment.warDeployed) {
       String homeFolder = System.getProperty('catalina.home')
       if(homeFolder) {
         File externalConfigFile = new File("$homeFolder/conf/MyAppConfig.groovy")
         if(!externalConfigFile.exists()) {
           externalConfigFile.createNewFile()
         }
       }
    }
  }
}
</code>
Comment: Worked beautifully. Thank you!


How to find table engine in MySQL Workbench?

Question: I've just installed MySQL Workbench 5.2.39 and I'm currently viewing one of my databases through the 'Schema' panel in a 'SQL Editor' tab. I can see all of my database's tables under 'Tables', but no indication of what engine they use. Where can I find this information?
Answer: There are two ways to see the storage engine of a table
METHOD #1
Step 01) Double Click on which Connection you want to open (Opens SQL Editor)
Step 02) Click on the Database
Step 03) Right Click on the Table (menu pops up)
Step 04) Click on Send to SQL Editor (menu appears sideways)
Step 05) Click Create Statement
You will see the CREATE TABLE SQL command. At the bottom of the Command is the part that says ENGINE=.
METHOD #2
Another way to display the engine of a table is to query the INFORMATION_SCHEMA database
For a table mydb.mytable, run this to see the engine
SELECT engine FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema='mydb' AND table_name='mytable';

Give it a Try !!!
Comment: Both methods work, but it seems like a glaring omission from the GUI to not mention somewhere the engine type! Compared to the previous MySQL Administrator Toolkit.


Do we still need to use tanh and sigmoid activation functions in neural networks, or can we always replace them by ReLU or leaky ReLU?

Question: Although it seems clear that ReLU and/or leaky ReLU have advantages over sigmoid or tanh activation functions in many situations, I find it very difficult to find out whether the latter are really "legacy". Is there a common situation in which using tanh or sigmoid activations is better than both ReLU and leaky ReLU?
To clarify, "better" may mean faster or more stable training, a better model precision, or any other desirable quality (please explain which one it is in your example). With a "common situation" I mean it should be a bit broader than one particular exotic example which breaks down as soon as the hyperparameters are chosen slightly differently.
Answer: A common use case is multi-class classification. Using the sigmoid activation in the final layer produces a quantity in $[0,1]$. When used element-wise, the output is a vector where each element is a probability. This is in contrast to the softmax case, where the entire vector is a probability distribution over the classes. A vector where each element is a probability can be helpful for tasks where the target has multiple, non-exclusive categories.
Softmax activations also play a crucial role in Transformer networks, which are a recent neural network architecture that has strong performance on sequence transduction tasks. See: "Attention Is All You Need" by  Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin. Replacing softmax with ReLU would create some problems, because then the output of the activation would not have a sum-to-1 constraint.
Another use case for tanh and sigmoid activations is in LSTM units, where the activations' constraints form a critical part of the so-called "constant error carousel".
Comment: Indeed, I think there is a use-case for sigmoid in the last layer. But as far as I understand, that is especially for non-mutually exclusive classification. For classification with mutually exclusive classes, softmax is the usual choice.
Comment: @MightyCurious Good point. See my edit.
Answer: I've found that for simple regression problems with neural networks, tanh can be superior to ReLU. An example would be input = x, output = sin(x), over a limited domain such as [-pi,pi]. Any function approximated with ReLU activation functions is going to be piecewise linear. So, it takes a lot of piecewise linear functions to fit to a smooth function like sin. Meanwhile, tanh is very smooth, and it doesn't take as many tanh primitives to build something that closely resembles a sine wave.
Note that for classification problems, especially using multiply convolution layers, ReLU and its minor variants are hard to beat.


Start a java program with an object model as parameter

Question: A server listens on a port, waiting for incoming requests from clients (the client as a matter of fact is an ejb). These requests pass a complete object model as parameter (e.g. a list of Employees, each Employee a list of Tasks etc.).
Now the server has to start another java program in a new JVM instance on the same machine, with this object model as a parameter.
This other java program should be a standalone java program, but I cannot pass the object model as a parameter to the main method (void main(String[] args)).
So what to do? I am looking for a "simple" solution, e.g. preferably without a database or a file for persistancy.
The stand alone program is really cpu intensive and cannot be hosted by an appserver.
Thx.
Answer: Run the application and capture its in/out streams, then stream the serialized object model through it. The new application should deserialize input coming from System.in .
Example of the concept (I just wanted to make sure my example works, sorry for the delay):
package tests;

import java.io.File;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class AppFirst {
    public static void main(String[] args) throws Exception {
        ProcessBuilder pb = new ProcessBuilder("java", "-cp",
            "./bin", "tests.AppSecond");
        pb.directory(new File("."));
        pb.redirectErrorStream(true);
        Process proc = pb.start();

        ObjectOutputStream out = new ObjectOutputStream(
            proc.getOutputStream());
        ObjectInputStream oin = null;

        for (int i = 0; i < 1000; i++) {
            out.writeObject("Hello world " + i);
            out.flush();
            if (oin == null) {
                oin = new ObjectInputStream(proc.getInputStream());
            }
            String s = (String)oin.readObject();
            System.out.println(s);
        }
        out.writeObject("Stop");
        out.flush();

        proc.waitFor();
    }
}

package tests;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class AppSecond {
    public static void main(String[] args) throws Exception {
        ObjectInputStream oin = null;
        ObjectOutputStream out = new ObjectOutputStream(System.out);
        while (true) {
            if (oin == null) {
                oin = new ObjectInputStream(System.in);
            }
            String s = (String)oin.readObject();
            if ("Stop".equals(s)) {
                break;
            }
            out.writeObject("Received: " + s);
            out.flush();
        }
    }
}

Edit: Added a looping version. Note that there needs to be a trick with the OOS, as it instantly starts to read the passed in stream (and blocks your app If you do it at the wrong step - it should be wrapped AFTER the first object is sent out to the child process).
Comment: what does your solution compare to the one 'George IV' suggests?
Will this solution also perform in case of many requests?
Comment: Frankly, I never tried to write more than one object to an OOS. You could wrap the request and response pair in both sample apps into a for loop and execute it 1000 times. I'll check this now and will return.
Comment: @akarnokdthis didn't work for me. Can you help me with this? I'm generating a jasper report from a large amount of data. But it forever waits. Finally, application hangs and have to kill the process finally.
Answer: You could serialize the object and write it to the file system. Then, you can read in that serialized object at runtime.  Alternatively, you could use JMS to transfer that object as a stream of bytes.
More on serialization.
More on JMS. I have always used ActiveMQ, an Apache project for my JMS needs. It is easy to use and highly scalabe. Oh yeah, and it's free.
Comment: - JMS solution: does it require any overhead in the form of software installations?
- serialization: will the original objects really be restored after reading?
any beginner examples?
Comment: see edits. i've never used JMS outside of ActiveMQ, which i recommend.  the serialized objects are read back as though they were never gone. only `transient` variables are lost. but they shouldn't be necessary for use later (that's why they are marked `transient`).
Comment: what do you think of the solution from kd304?
Answer: Have a look at RMI. Your server could start up the new service which in turn publishes and exports itself to a local registry. Then your new service can receive the object model as a parameter to a Remote-extending method. Should be very simple, requires no file access or an additional service, and no more heavyweight than any of the other answers.
Answer: One way would be that the original JVM opens a socket for listening, and the new JVM instance runs a program that connects to that socket and receives the parameters through the socket (Java's default serialization will probably be good enough). That way you only need to pass the socket port number as a parameter to main, and no files/databases are needed. The same method can also be used to communicate other commands between the JVMs.
Comment: - how will the original JVM know that the parameters have been read by the new machine, can it detect that?
- how about many requests per minute: should i pass a unique id as a parameter, next to the port number, so that the correct object model will be passed?
Comment: (1) It might be good for the client to send a message to the original JVM when it has read the data, that it has received it all, because there can be a short delay (some milliseconds) between the original JVM sending data over the socket and the client receiving it. (2) Have a different port for each JVM that you start. That way the port number is unique and you will know which JVM connected to it, because you tell about the port number only to one JVM.
Answer: Either way, you can't pass an object model as it exists in memory.  If you want to pass the object model, you're going to have to find a way to encode and decode that model into something you can pass.
Since the data's already being sent via EJB, object serialization's the obvious choice, although there's nothing wrong with XML, JSON, etc.
You also need to get the object from your server program to the newly-invoked JVM.  If the object model is small enough, you could pass the serialized object to the java program as a command-line argument.  You could also, as George IV has suggested, write it to the file system and then tell your new application where to find the file containing the serialized data.  You could use JMS.  Web services.  Sockets.
But if your server application is already EJB-based, the simplest thing to do is to have your new application invoke on the EJB layer as an EJB client to request the data you're looking for.
Comment: this may be a good solution. 1.) the ejb invokes the remote socket, 2.) the server starts the standalone java program and 3.) the standalone program starts connecting to the ejb to get it's model. Now about the communication: which information do i have to pass in steps 1. and 2. so that step 3. will know what to do and where to do it?
Answer: The serialization approach is good enaugh. What you need in addition is the root object to carry some references to the relevant objects to the call. What I did in the past was to serialize a complete object graph and to let the root object implement some interface like Runnable and then on the receiving node cast this root object to Runnable and execute run() on it.
Comment: what do you mean by 'the relevant objects to the call'?
Comment: Depends on where you functionality is located. If it is within the serialized classes' code then you don't need to take care about that. On the other hand, if certain objects of the graph are relevant as parameters to functions on your server, that is outside of the serialized classes, then you can just use an `Object[]` as root object and pass the contents to a function accepting an `Object[]`.


Redundent Disks with Google Cloud Virtual Machine

Question: I am using Google Compute Engine VM for a web server. Is it possible to setup a RAID type of disk structure with the virtual machine? I basically would like ti have 2 disks on the machine where they are always mirrored and in case one disk fails the other automatically takes over with no data loss or down time.  Thanks for your help.
Comment: Google's virtual storage is [already redundant](https://cloud.google.com/compute/docs/disks). What is the point of this?
Comment: Can you tell me in a regular situation with no persistent disk set up, what happens if the disk crashes?  Does a new disk automatically take over with no data loss?  Or do I personally need to create a new disk?
Comment: You would never notice such an event; it is utterly transparent. It may have happened ten times already for each of your running VMs. Google handles it and you do not need to do anything. There is not even any way to find out if a disk failed; it is entirely automatic.
Comment: Thanks for your response.  When you say it is utterly transparent do you mean with or without using persistent disk?
Comment: What other disk would your VM be using?
Answer: For this scenario, I will recommend other options for having always availability on your web service, as the issue is often the instance itself and not the disk regarding GCE running websites possible issues.
First thing to have in mind is to have a robust system, since a lot of us never take this in mind when using GCP compute engine (specially for web servers) as certain events are unpredictable, and it is best to be prepared for these events (region out of resources, ongoing known issues, VM failure).
I can tell that creating a Managed Instance Group will work for you as it will keep your service up in case of failure, it let you operate apps on multiple identical VMs. You can make your workloads scalable and highly available by taking advantage of automated MIG services, including: autoscaling, autohealing, regional (multiple zone) deployment, and automatic updating.
You can use managed instance group (MIG) for scenarios like these:
-Stateless serving workloads, such as a website frontend.
-Stateless batch, high-performance, or high-throughput compute workloads, such as image processing from a queue.
-Stateful applications, such as databases, legacy applications, and long-running batch computations with checkpointing.
A managed instance group creates each of its managed instances based on the instance template and optional stateful configuration that you specify.
Since you are searching for high availability on your web server, Instance groups keeps VM instances running. If a VM in the group stops, crashes, or is deleted by an action other than an instance group management command (for example, an intentional scale in), the instance group automatically recreates that VM in accordance with the original instance's specification (same VM name, same template) so that the VM can resume its work.
Comment: Can you tell me in a regular situation with no persistent disk set up, what happens if the disk crashes?  Does a new disk automatically take over with no data loss?  Or do I personally need to create a new disk?
Comment: You can use HDD as regional persistent disk. Regional persistent disks have storage qualities that are similar to zonal persistent disks. However, regional persistent disks provide durable storage and replication of data between two zones in the same region.

In the event of a zonal outage, you can usually failover your workload running on regional persistent disks to another zone by using the --force-attach flag. This flag lets you attach the regional persistent disk to a standby VM instance even if the disk can't be detached from the original VM due to its unavailability.


Gatling ElFileBody and parameter + static test

Question: I want to parameterize just the NIN (05129996961) in this example (I have it in session).
<code> "subject": {
            "reference": "urn:uuid:c1015cfa-d6b6-4f06-8150-ced7dbea759c",
            "type": "http://xxx/fhir/StructureDefinition/sfm-Patient",
            "display": "Patient 05129996961"
          },
</code>
Is there a way to say i.e.  "display": "Patient + ${nin}" or something similar in the ElFileBody?
Comment: What's the question? Is there possibility for add Gatling EL inside the json? - Yes it's
Answer: Plain old Gatling EL:
<code> "subject": {
            "reference": "urn:uuid:c1015cfa-d6b6-4f06-8150-ced7dbea759c",
            "type": "http://xxx/fhir/StructureDefinition/sfm-Patient",
            "display": "Patient #{nin}"
          },
</code>
Comment: another challenge is how to put in a value like this:

  .exec(session=>{
      val fullUrl = session("fullUrl").as[Vector[String]]
      println(s"fullUrl: ${fullUrl(0)}")
      session})

into the json request body above. As in using it as a string "s" before.


Do the hands' sizes affect piano learning/performance?

Question: I don't really know anything about pianos, but since I just got a digital one I guess I should give it a go.
The first thing I noticed is that it is difficult for me to press multiple keys that are a bit separated from each other with one hand. Not gonna lie: my hands are kinda small (I think).
I guess that it is still possible to play it well anyway and I just need practice. However, given that my hands are small, will my learning curve be significantly more challenging, or is this kind of problem very common and happens to most people?
They're not miniature though :(
Comment: Are your hands smaller than those of the 7-year-olds who take piano lessons over at Mrs. Metzler's? You're probably fine.
Comment: The piano is absolutely easier to play with large hands (if your fingers aren't too broad) depending on how complex the piece is.  Some pieces may be impossible to play without other tools if your hands are not large enough (notably Rachmaninoff).
Comment: Check out the ones in this video: http://www.youtube.com/watch?v=93JiXloIhn4
Comment: @MatthewRead: What kind of tools?
Comment: @AlexBasson: Ha, I guess you're right XD
Answer: If your hands are really smaller than the "average hand" (whatever that is) there will be a few passages you'll find physically hard or impossible to play. These will be in the minority and probably feature in pieces of a more advanced complexity than you're going to meet when starting out.
Your feeling of "it is difficult for me to press multiple keys that are a bit separated from each other with one hand" is more likely just a lack of hand strength at this stage - whenever I try and teach a non-pianist a little piece I always forget that I only find it easy because my hands are used to making that sort of movement and shape.
When I don't play for a while and attempt something that requires a bit of dexterity, I find it a lot harder because the muscles have got lazy!
So don't worry too much about not being able to span 12 keys; work on finger-strength to compensate.
Answer: For most of the classical repertoire you need to be able to reach an octave comfortably.
Beyond an octave, extra reach helps, but even professionals make use of "cheats" by turning large chords into rolls or grace notes or even (gasp) leaving notes out.
Answer: Of course it would help if I could remember his name, but I recently heard an interview with an internationally acclaimed concert pianist.
He said that because of his small hands, there were some passages where he struggled to reach the notes, so all of his practice went into learning to play the passage, rather than into developing the expression he wanted.
Yet his audience would love it anyway.
There will be many pieces for which your hand size will not be a problem. There will be some pieces that will require you to improve your stretch. There will be some pieces that will be unattainable for you.
After all, I could write a piece right now which no human could play with two hands!
In conclusion, there may be some parts you won't be able to play. But there will be plenty which you can play, so don't let it stop you learning the instrument.


O que significa o erro: realloc(): invalid pointer: 0xb78094d8?

Question: O meu programa,cujo código está mais abaixo, acusou o seguinte erro:
Não entendo pois, tenho memória de sobra no meu PC, e todos os sites compiladores acusam o mesmo problema.

*** Error in `./prog': realloc(): invalid pointer: 0xb78094d8 ***
======= Backtrace: =========
/lib/i386-linux-gnu/i686/cmov/libc.so.6(+0x75e72)[0xb76d2e72]
/lib/i386-linux-gnu/i686/cmov/libc.so.6(realloc+0x275)[0xb76d6ad5]
./prog[0x804866c]
/lib/i386-linux-gnu/i686/cmov/libc.so.6(__libc_start_main+0xf5)[0xb76768f5]
./prog[0x80486ad]
======= Memory map: ========
08048000-08049000 r-xp 00000000 08:03 1295711    /home/MhQXj9/prog
08049000-0804a000 rw-p 00000000 08:03 1295711    /home/MhQXj9/prog
0914d000-0916e000 rw-p 00000000 00:00 0          [heap]
b763b000-b7656000 r-xp 00000000 08:03 1303883    /lib/i386-linux-gnu/libgcc_s.so.1
b7656000-b7657000 rw-p 0001a000 08:03 1303883    /lib/i386-linux-gnu/libgcc_s.so.1
b765b000-b765d000 rw-p 00000000 00:00 0
b765d000-b7806000 r-xp 00000000 08:03 1303839    /lib/i386-linux-gnu/i686/cmov/libc-2.17.so
b7806000-b7807000 ---p 001a9000 08:03 1303839    /lib/i386-linux-gnu/i686/cmov/libc-2.17.so
b7807000-b7809000 r--p 001a9000 08:03 1303839    /lib/i386-linux-gnu/i686/cmov/libc-2.17.so
b7809000-b780a000 rw-p 001ab000 08:03 1303839    /lib/i386-linux-gnu/i686/cmov/libc-2.17.so
b780a000-b780d000 rw-p 00000000 00:00 0
b780d000-b784e000 r-xp 00000000 08:03 1303836    /lib/i386-linux-gnu/i686/cmov/libm-2.17.so
b784e000-b784f000 r--p 00040000 08:03 1303836    /lib/i386-linux-gnu/i686/cmov/libm-2.17.so
b784f000-b7850000 rw-p 00041000 08:03 1303836    /lib/i386-linux-gnu/i686/cmov/libm-2.17.so
b7851000-b7856000 rw-p 00000000 00:00 0
b7856000-b7857000 r-xp 00000000 00:00 0          [vdso]
b7857000-b7876000 r-xp 00000000 08:03 1303796    /lib/i386-linux-gnu/ld-2.17.so
b7876000-b7877000 r--p 0001f000 08:03 1303796    /lib/i386-linux-gnu/ld-2.17.so
b7877000-b7878000 rw-p 00020000 08:03 1303796    /lib/i386-linux-gnu/ld-2.17.so
bf99a000-bf9af000 rw-p 00000000 00:00 0          [stack]

o programa abaixo é uma hash table e faz o seguinte:
tenho um tipo estruturado Tab[int* vetor, int tam_vetor], e constantemente o Tab[n].vetor precisa ser reallocado para crescer de tamanho.
No fim de cada num_de_caso eu libero os *vetores e a estrutura Tab. E depois os crio novamente, até encerrar o ciclo.
#include <stdio.h>
#include <stdlib.h>

typedef struct tab
{
    int* vetor;
    short int tam_vetor;

}Tab;

void inicializa(Tab* tabela, int tam)
{
    int i;

    for(i=0; i < tam; i++)
        tabela[i].tam_vetor = 0;
}

int hash(int num,int tam, int i)//gera um codigo p a chave
{
    num = (num%tam + i);

    return num;
}

void insere(Tab* tabela, int chave, int pos)
{
    tabela[pos].vetor[tabela[pos].tam_vetor] = chave;
    tabela[pos].tam_vetor = tabela[pos].tam_vetor + 1;
}

void liberaTabela(Tab* tabela, int tam_tabela)
{
    int i;

    for(i=0; i<tam_tabela;i++)
        if(tabela[i].vetor != NULL)
            free(tabela[i].vetor);

    free(tabela);

}

void verificaAlocacao(Tab* tabela, int pos)
{
    if(pos < 0)
    {
        if(tabela == NULL)
        {
            printf("\nmemoria insuficiente");
            exit(1);
        }
    }
    else
    {
        if(tabela[pos].vetor == NULL)
        {
            printf("\nmemoria insuficiente");
            exit(1);
        }
    }
}

void printTabela(Tab* tabela, int tam_tabela)
{
    int i,j;

    for(i=0; i< tam_tabela; i++)
    {
        printf("%d ->",i);

        if(tabela[i].vetor != NULL)
        {
            for(j=0; j < tabela[i].tam_vetor; j++)
            {
                printf(" %d ->",tabela[i].vetor[j]);
            }
        }

        printf(" \\\n");
    }
}

int main()
{
    int num_de_casos,
        tam_tabela,
        num_chaves,
        chave,
        pos,
        i,
        j;

    Tab* tabela;

    scanf("%d", &num_de_casos);

    while(num_de_casos != 0)
    {
        scanf("%d",&tam_tabela);
        scanf("%d",&num_chaves);
        tabela = (Tab*) malloc(tam_tabela*sizeof(Tab));
        inicializa(tabela, tam_tabela);
        verificaAlocacao(tabela, -1);

        while(num_chaves != 0)
        {
            scanf("%d",&chave);

            i=0;

            pos = hash(chave,tam_tabela,i);

            while(1)
            {
                if(tabela[pos].vetor == NULL)
                {
                    tabela[pos].vetor = (int*) malloc(sizeof(int));
                    verificaAlocacao(tabela, pos);
                    insere(tabela,chave,pos);
                    break;
                }
                else
                {
                    for(j=0; j < tabela[pos].tam_vetor && chave != tabela[pos].vetor[j]; j++);//acha j<tam_vetor se: chave == algum elemento && acha j == tam_vetor se: chave não coincide com nenhum elemento

                    if(j == tabela[pos].tam_vetor)
                    {
                        tabela[pos].vetor = (int*) realloc(tabela[pos].vetor,(j+2)*sizeof(int));
                        verificaAlocacao(tabela, pos);
                        insere(tabela,chave,pos);
                        break;
                    }
                    else
                    {
                       i++;
                       pos = hash(chave,tam_tabela,i);
                    }
                }
            }

            num_chaves--;
        }

        printTabela(tabela, tam_tabela);
        liberaTabela(tabela, tam_tabela);
        num_de_casos--;
    }

    return 0;
}

Comment: O problema acontece na sua função liberaTabela ela está acessando um vetor que aparentemente não foi preenchido. Observe também a saída da função printTabela(), vc vai perceber que a última impressão sai vazia. Agora já sabemos onde o problema está, tenta resolver e posta aqui até onde vc conseguiu chegar
Comment: Se vc comentar a função liberaTabela() o seu código roda parcialmente, logo as chances do seu problema estar ali é grande. Agora é necessário que vc dê uma olhada com calma nessa função e debugue em busca do erro e poste aqui as dúvidas e avanços.
Comment: Experimenta usar o http://valgrind.org/. Poderá dar-te uma indicação mais precisa do teu problema atual.
Comment: @Zuul como que faz pra utilizar o valgrind. agradeço!
Comment: @RaulSenaFerreira Não entendi o pq de ser a função liberaTabela()... pq ela nunca está vazia. Todos os dados de entrada vão pra ela. A o função printTabela() tem que ter aquele final, pra poder sair dessa forma no print: \
Answer: Bem... o que eu aprendi nesse problema foi: De não esquecer, nunca, de forma alguma, de inicializar um vetor de ponteiros com NULL;
void inicializa(Tab* tabela, int tam)
{
    int i;

    for(i=0; i < tam; i++)
    {
        tabela[i].vetor = NULL;//a falta dessa linha ocasionou o erro de memóriaN

        tabela[i].tam_vetor = 0;
    }
}


Usuários autenticados

Question: como adiciono (usuários autenticados) de volta no NOMES DE GRUPOS OU DE USUÁRIO na aba segurança em uma determinada pasta?
Answer: Encontrei....
Mas vou deixar registrado, caso ajude alguém que tenha a mesma dúvida
Processo.
Windows 7 Professional
1º Botão direito na pasta especificada.
2º Propriedades.
3º Segurança
4º Editar em - Nomes de Grupo ou de usuários.
5º Adicionar
6º Digite o nome Usuários e pesquise.
7º O sistema vai retornar a busca do usuários autenticados
8º Selecione/ aplique e de OK.
9º As novas configurações serão carregadas.

Usuários autenticados


How to iterate over React children and access their ref in a helper function with TypeScript?

Question: I am trying to learn how to perform more complex browser animations and would like to experiment with the FLIP methodology. I found this blog post https://medium.com/ft-product-technology/animating-list-reordering-with-react-hooks-1aa0d78a24dc that achieves an affect very similar what I want but I cannot work out how to translate the calculateBoundingBoxes helper function into TypeScript.
Attempting to access child.ref has the TypeScript error:
Property 'ref' does not exist on type 'string | number | boolean | {} | ReactElement<any, string | JSXElementConstructor<any>> | ReactPortal'.
  Property 'ref' does not exist on type 'string'.

How do I correctly type this function such that it only accepts children that all have refs?
const calculateBoundingBoxes = (children: ReactNode) => {
  const boundingBoxes = {};

  React.Children.forEach(children, (child) => {
    if (child == null) {
      throw new Error()
    }

    const domNode = child.ref.current;
    const nodeBoundingBox = domNode.getBoundingClientRect();

    boundingBoxes[child.key] = nodeBoundingBox;
  });

  return boundingBoxes;
};

Thank you!
Answer: I had the same problem. Here, my solution :
type ElementWithRef = React.ReactElement & { ref?: React.RefObject<HTMLElement> };

const calculateBoundingBoxes = (children: ElementWithRef[]) => {
  const boundingBoxes: { [key: React.Key]: DOMRect | undefined } = {};

  React.Children.forEach(children, (child) => {
    if (!child || !child.key || !child.ref) {
      throw new Error();
    }

    const domNode = child.ref?.current;
    boundingBoxes[child.key] = domNode?.getBoundingClientRect();
  });

  return boundingBoxes;
};

children must be typed with ref.