use cvSet2D in gray scale image in C language?

Question: I want to set pixel value in given bmp image using CvSet2D but I want to access only the first value. Could you explain what the 4 arguments of CvSet2D are for?
For example:
#include <stdio.h>
#include <cv.h>
#include <highgui.h>
#include <math.h>

int main(int argc, char *argv[])
{
    IplImage* img = cvLoadImage("initial.bmp",1);

    int f = 123;
    cvSet2D(img, 1, 2, f); // here is the error
    //cvSet2D(img, 1, 2, cvScalar(f)); // error also this way

    return 0;
}

I get an error that says:
incompatible type for argument 4 of 'cvSet2D'

I just need to set pixel value of a gray scale image, how con I do this?
Answer: You can refer to  this question.

C: void cvSet2D(CvArr* arr, int idx0, int idx1, CvScalar value)

The arguments are:

arr -  Input array (i.e. the image)
idx0 – The first zero-based component of the element index (i.e. row)
idx1 – The second zero-based component of the element index (i.e column)
value – The assigned value

To know what cvScalar is, refer to this and

The cvScalar is simply a convenient container for 1, 2, 3 or 4 floating point values.

You should do something like:
uchar f = 123;
CvScalar scalar = cvGet2D(img, 1, 2);
scalar.val[0] = f;
cvSet2D(img, 1, 2, scalar);

Comment: this cvSet2D(img, 1, 2, cvScalar(f)); doesn't work at all
Comment: @RiwaMl it should work, what's the error? Also post a small sample where you also show how you create the image.
Comment: @RiwaMl updated the snippet about `cvSet2D`. It works as expected. Is it different from what you're doing? Post your code...
Comment: the error is
too few arguments to function 'cvScalar'
Comment: it is C programming not C++
Comment: Yeah, I was using C++ wrapper to C stuff. Check updated snippet
Comment: @RiwaMl from your posted code (which you should add to your question) I think I finally got what you meant. Check if it's ok now. Please note that a clear question with all needed info will get you the correct answer sooner!
Comment: @RiwaMl I added the relevant code to the question, now you can delete your answer. If you find this answer useful, please accept it and/or upvote. Or comment to get additional information. To use C++ functions, you should `#include `


If I set a Gaussian prior in the parameter space, can I use the variance as diagonal of the Hessian?

Question: Say I have a neural network, where I put a Gaussian prior over the parameters $\theta_i \sim N(\mu_i, \sigma_i^2)$ and that I learn both $\mu$ and $\sigma$ via the reparameterization trick $f = \mu + \epsilon \cdot \sigma$
After training, I'll have for each weight its corresponding $\mu, \sigma$
My question is, can I consider $\sigma$ as a "proxy" for the diagonal of the Hessian?
In my mind it works because $\sigma >>0$ means that that parameter is pretty invariant to big changes, thus should have a second derivative pretty large, right?
Comment: @JohnMadden you know what? i like your idea, i'll let you know asap
Comment: seems something related to variational approximation of the posterior, but not sure though
Comment: Sounds like an interesting question; maybe you can try it out and let us know? (get the diagonal of the hessian efficiently in an autodiff framework by taking the derivative of the squared magnitude of the gradient).
Comment: @JohnMadden done, answered (though there is for sure a connection between variance and hessian, related by the Fisher Information, but it doesn't play a role in this case)
Answer: TLDR: no, the $\sigma$ converge to $0$

Well, seems like that an empirical test was more than enough to answer to this question
I trained a linear model on a test dataset with the following objective:
$$
L(\mu, \log\sigma) = N^{-1}\sum_{i=0}^N (\beta x - y ), \\
\beta = \mu + \epsilon \cdot \exp(\log\sigma)\\
\epsilon \sim N(0,1)
$$
And the result is the following:

Clearly, the loss converges, but the $\log\sigma\rightarrow 0$
A colleague of mine correctly pointed out that the "variance" term will just be white noise, so half a time will make the prediction better, and half not.
Indeed, this trick is used to train VAEs, where in addition to it, there is also an anchor to a prior (the loss is $L = L' + D_{KL}(p_\theta(z)) || q(z)$) thus forcing $\sigma$ to be similar to something specific
Comment: +1 awesome work, and those plots beautifully illustrate your point.


Computing $\iint_{\mathbb R^2}\exp\left(u\frac{xy}{\sqrt{x^2+y^2}}+v\frac{x^2-y^2}{2\sqrt{x^2+y^2}}-\frac12(x^2+y^2)\right)dxdy$

Question: I'm trying to work on another solution to this question by computing the moment generating function:
$$M(u,v)=\iint_{\mathbb{R}^2}\frac1{2\pi}\exp\left(u\frac{xy}{\sqrt{x^2+y^2}}+v\frac{x^2-y^2}{2\sqrt{x^2+y^2}}\right)\cdot\exp\left(-\frac{1}{2}(x^2+y^2)\right)dxdy$$ which should integrate to : $$M(u,v)=\exp\left(\frac18(u^2+v^2)\right)$$
Polar coordinates look like they could help but I'm helpless (maybe completing the squares in terms of $r$ ?):
$$M(u,v)=\int_0^{+\infty}\int_{0}^{2\pi}\frac1{2\pi}\exp\left(\frac{r}2(u \sin2\theta + v\cos 2\theta)\right) r\cdot\mathrm{e}^{-\frac{1}{2}r^2}\:\mathrm{d}r\,\mathrm{d}\theta$$
Comment: Letting $c=c(\theta)=u\sin(2\theta)+v\cos(2\theta)$, I got to:
$$M(u,v)=(2\pi)^{-1}\int_{0}^{2\pi}e^{c^2/2}\int_{-c}^{+\infty}(r+c)e^{-r^2/2}\,\mathrm{d}r\,\mathrm{d}\theta$$ but I think this approach is doomed to fail though..
Answer: After changing to polar coordinates, make the change of variables $\theta=\phi/2$, to obtain that $$\begin{align*}M(u,v)&=\int_0^{\infty}\int_{0}^{2\pi}\frac1{2\pi}\exp\left(\frac{r}2(u \sin2\theta + v\cos 2\theta)\right) r\cdot\mathrm{e}^{-\frac{1}{2}r^2}\,dr\,d\theta\\&=\int_0^{\infty}\int_{0}^{4\pi}\frac1{4\pi}\exp\left(\frac{r}2(u \sin\phi + v\cos \phi)\right) r\cdot\mathrm{e}^{-\frac{1}{2}r^2}\,dr\,d\phi\\&=\frac{1}{2\pi}\int_0^{\infty}\int_{0}^{2\pi}\exp\left(\frac{r}2(u \sin\phi + v\cos \phi)\right) r\cdot\mathrm{e}^{-\frac{1}{2}r^2}\,dr\,d\phi\end{align*}.$$ Changing back to cartesian coordinates, we obtain that $$\begin{align*}M(u,v)&=\frac{1}{2\pi}\int_{\mathbb R^2}\exp\left(\frac{xu+yv}{2}\right)\exp\left(-\frac{x^2+y^2}{2}\right)\,dx\,dy\\
&=\frac{1}{2\pi}\int_{\mathbb R}\exp\left(\frac{ux}{2}-\frac{x^2}{2}\right)\,dx\cdot\int_{\mathbb R}\exp\left(\frac{vy}{2}-\frac{y^2}{2}\right)\,dy\\
&=\frac{1}{2\pi}e^{u^2/8}\int_{\mathbb R}\exp\left(-(u/\sqrt{8}-x/\sqrt{2})^2\right)\,dx\cdot e^{v^2/8}\int_{\mathbb R}\exp\left(-(v/\sqrt{8}-y/\sqrt{2})^2\right)\,dy\\&=e^{(u^2+v^2)/8}.\end{align*}$$
Comment: This derivation seems faulty. To replace $\cos/\sin(2\theta)$ by $\cos/\sin\phi$, one needs that $\phi=2\theta$, in which case the integration interval of $\phi$ is $(0,4\pi)$, not $(0,\pi)$.
Comment: You are right, we actually get a closed form. I edited my answer.
Comment: Yes. Nice proof.


Clico no botão e não adiciona a div - C# Asp.Net

Question: Clico no botão e ele não me adiciona a div, mas manda para a base de dados, alguém pode me ajudar?
C#
protected void img_btn_enviar_nome_Click(object sender, EventArgs e)
        {
            UtilizadoresBot msg_nome = new UtilizadoresBot
            {

                Nome = txt_msg_nome.Text,

            };
            db.UtilizadoresBot.InsertOnSubmit(msg_nome);
            db.SubmitChanges();

            div_conversa.Controls.Add(new LiteralControl("
 1 " + msg_nome + "
"));
            div_conversa.Controls.Add(new LiteralControl("

"));

        }

HTML

Answer: O atributo runat="server" só deve ser utilizado para os componentes do ASP.Net, aqueles em que o markup começa com <asp: ou alguma outra tagprefix que você tenha registrado em sua página. Nesse caso o mais adequado seria utilizar um <asp:panel> que seria renderizado como uma
.
E nesse seu cenário não parece ser necessário ter esse componente sendo rederizado no lado do servidor. Outra coisa que não faz sentido é você adicionar controles Literal apenas para incluir um HTML cru na página... Você poderia utilizar uma
 simples e aí sim, dentro dela utilizar um <asp:Literal> para receber o novo conteúdo.
ASPX

    <asp:Literal ID="conversa" runat="server"></asp:Literal>

Code-Behind
protected void img_btn_enviar_nome_Click(object sender, EventArgs e)
{

    UtilizadoresBot msg_nome = new UtilizadoresBot
    {

        Nome = txt_msg_nome.Text,

    };
    db.UtilizadoresBot.InsertOnSubmit(msg_nome);
    db.SubmitChanges();

    conversa.Text += "
 1 " + msg_nome + "
"
                        + "

";
}


Changing the field date type from 'datetime' to 'unix timestamp' without losing data

Question: I am investigating how could I convert the date format in the 4 database tables: field_data_field_article_publication_date from the actual datetime format:
2013-09-10 12:43:03  to its unix timestamp equivalent: 1378816983
with a minimal negative impact on data integrity of the actual articles on a production environment.
UPDATE

My guess scenario would be:

Update the field type in my feature: MYFEATURE.features.field.inc // changed to timestamp [EASY]
Alter the table field structure from 'datetime' to 'timestamp' in a hook_schema_alter [EASY]. This should be performed using db_change_field().

RISKY AS I CAN LOSE DATA WHEN MOVING CONTENT. I MIGHT TRY TO DUPLICATE COLUMN DATE (INTO DATE2) FIRST.

I NEED HELP HERE: Convert all existing dates for articles found in 'field_data_field_article_publication_date' table to the new format unix stamp. [NOT SURE HOW]

Any further help?
I am interested in minimizing querying time by using MYSQL: UNIX_TIMESTAMP(date) somehow.
My approach on No.3
loop over all 4 tables {
<code>   - create a new column date2 of type: int (or datetime?)
   - copy all dates from date to date2 passing them through strtotime()
   - delete column date
   - rename column date2 to column date
</code>
}
That would be a start in MYMODULE.install:
<code>function MYMODULE_schema_alter() {
//...loop over 4 tables
  $schema['TABLENAME1']['fields']['DATE2'] = array(
    'type' => 'int', //or timestamp
    'not null' => TRUE,
    'unsigned' => TRUE,
    'default' => 0,
    'description' => 'Field added by my_module',
  );
//…
}

/**
 * Content types using date fields should be using timestamp instead datetime
 */
function MYMODULE_update_7192() {
//define their names or get them from schema
$tables = array('TABLENAME1', 'TABLENAME2', 'TABLENAME3', 'TABLENAME4');

foreach ($tables as $table) {
       //create a new column date2 of type: int (or datetime?)
       $schema = drupal_get_schema($table);
       db_add_field($table, 'DATE2', $schema['fields']['DATE2']);
       db_update($table)
      ->fields(array(
          'DATE2' => strtotime('DATE'),
         )
         )
       ->execute();
      db_drop_field($table, 'DATE');
}
}
</code>
Comment: You mean to update without changing the datatype?
Comment: @DanielVérité No, I assume I need to perform a hook_schema_alter before, not sure about the priority as I don't want to loose data.
Answer: The strtotime() php function will be helpful for converting date to unix timestamp
Comment: @harshal..I have updated my spec.


C# Keeping DLLs with the associated library

Question: We have a library built on the back of eldos' Secure Black Box.
We use copy local to ensure that the appropriate runtime DLLs are included.
If we now reference our library in another project with a copy local our library is copied into the bin folder of our main project but the Eldos SBB libraries aren't.  We could reference SBB in the main project but there are no direct calls to SBB so any time the code is refactored the references may be removed as unused.
What is the best way of handling this issue?
Simon
Answer: One way to do it would be to put an msbuild script entry into the project properties--> build events --> pre or post build event dialog which would handle copying your Eldos SBB libraries for you.  This way you dont have and explicit reference that might get removed, although someone can remove the script so nothing is 100%.
So your script might look something like this:
<code>copy "{path1}EldosSBB.dll" "{path2}EldosSBB.dll"
</code>
Enjoy!
Comment: Yep - but it isn't really a solution.  We can't be the first people to come up with this issue - surely there is a standard method for doing this?

Simon
Comment: What I have proposed above is, in my opinion, the easiest solution, but certainly you could build something like this into your formal build process if you need to completely remove any dependency from your development environment.


How to substitute 2 columns values in dataframe with their ids from other dataframe?

Question: There is a df_value:
metric_type metric_name   metric_value
visits      total         111
visits      time_related  222
followers   total         333
followers   time_related  444

and another df with ids for the metric_type and metric_name
df_ids

metric_id  metric_name   metric_type
1          total         visits
2          time_related  visits
3          total         followers
4          time_related  followers

I need to change values like this:
metric_id   metric_value
1           111
2           222
3           333
4           444

I have tried to combine metric_name with metric_type in one column in both dfs:
df_value['combined']=df_value.apply(lambda x:'%s_%s' % (x['metric_name'],x['metric_type']),axis=1)
df_ids['combined']=df_ids.apply(lambda x:'%s_%s' % (x['metric_name'],x['metric_type']),axis=1)

and tried to change values like this
df_value.rename(
                columns=dict(zip(df_ids['combined'], df_ids['metric_id'])))

But it doesn't work, I have no idea how to proceed. Appreciate any help
Comment: put it already I need to change values like this:
Comment: `df_value.merge(df_ids, on=['metric_name', 'metric_type'])`?
Comment: are these actual values, where 1 -> 111 2 ->222 ... 9 -> 999
Comment: it could be any values, 1-> 15653 and so on
Comment: Could you manually write your desired output?
Comment: @ Code Different, haaa, so simple and I forgot totally, appreciate thanks, it worked
Answer: I think this is what you want:
# Dataframes:
data1 = [
    ['visits', 'total', 111],
    ['visits', 'time_related', 222],
    ['followers', 'total', 333],
    ['followers', 'time_related', 444]
]
cols_1 = ['metric_type', 'metric_name', 'metric_value']

df1 = pd.DataFrame(data1, columns=cols_1)

data2 = [
    [1, 'total', 'visits'],
    [2, 'time_related', 'visits'],
    [3, 'total', 'followers'],
    [4, 'time_related', 'followers']
]
cols_2 = ['metric_id', 'metric_name', 'metric_type']

df2 = pd.DataFrame(data2, columns=cols_2)

# Solution:
pd.merge(
    df1, df2, on=['metric_type', 'metric_name']
)[['metric_id', 'metric_value']]

Output:
  metric_id   metric_value
0   1         111
1   2         222
2   3         333
3   4         444

Answer: This should worked:
df = pd.DataFrame(data = [df_ids['metric_id'], df_value['metric_value']]).transpose()

Output:
   metric_id  metric_value
0          1           111
1          2           222
2          3           333
3          4           444


$\sum c_k^2<\infty$ then $A=\{\sum_{k=1}^{\infty} a_ke_k :|a_k|\leq c_k \}$ is compact

Question:
Let $\{e_k\}_{k=1}^\infty$ be an orthonormal set in a Hilbert space $H$. If $\{c_k\}_{k=1}^\infty$ is a sequence of positive real numbers such that $\sum c_k^2<\infty$, then the set:
  $$A=\left\{\sum_{k=1}^{\infty} a_ke_k :|a_k|\leq c_k\right\}$$
  is compact in $H$.

My effort: We need to prove that every sequence $\{f_n\}$ has a subsequence $\{{f_n}_k\}$ so that $\{{f_n}_k\}$ converges to a limit in $A$.I'm trying to build such a sequence:
First, for each $n$ look at $|\langle f_n,e_1\rangle|=|a_{n1}|\leq c_1$ then the sequence $\{a_{n1}\}$ is bounded thus there must be a subsequence that converges and  we define the limit as $l_1$. So we continue for all the vectors in the given set and define the limit of these subsets as $f=\sum_{k=1}^{\infty} l_ke_k \in H$.
But something must be wrong with the proof since I havent used $\sum c_k^2<\infty$.
Thanks.
Answer: What you did is more incomplete than wrong.
Firstly, we need to justify the sentence "we continue for all the vectors in the given set", writing explicitely the diagonal extraction.
Then we need to prove the limit element we get is indeed in $H$ (otherwise, we would have proved when $c_k=1$ that a set containing the unit ball is compact). That's where the conditions is used.
Also, there are criteria of compactness you can use here.
Comment: @Roy Since $\lvert (f_n)_k\rvert \leqslant c_k$ for all $n$, the same estimate holds for the pointwise limit, hence $\lvert (f_n - l)_k\rvert \leqslant 2c_k$. Now, given $\varepsilon > 0$, by the summability condition, there exists a $k_0$ such that $\sum_{k \geqslant k_0} {c_k}^2 < \frac{\varepsilon^2}{8}$. Split the sum in $\lVert f_n - l\rVert_2^2$ at a convenient place.
Comment: Did you mean that we need to prove that the limit element is in $A$? If so, isn't it obious since each $|l_k|$ is smaller than $c_k$?
Comment: @Roy No, the point is that you must prove $\lVert f_n - l\rVert_2 \to 0$. That is where you need the summability of ${c_k}^2$.
Comment: @DanielFischer: I've been trying to prove that but with no success. Can you give me a hint please?
Comment: @DanielFischer: I think I understand now, thanks!


Há alguma maneira de executar um programa java (.jar) a partir de um programa C ou C++?

Question: Eu quero saber se há uma maneira de eu escrever um programa .jar, e escrever um programa C/C++ que chamasse o JVM para executar o arquivo .jar. É possível? Se sim, podem me dar um exemplo de código ou uma instrução de como fazer isso?
Answer: Pode usar a linha de comando (system()):
 java -jar "arquivo.jar"

Dependendo do que quer fazer pode usar JNI. É bem complicado.
Comment: Dependendo do caso tem a [JNA](https://github.com/java-native-access/jna) também.
Comment: Obrigado. Já encontrei a resposta em uma pergunta similar.
Answer: A solução mais padrão seria utilizando a função system() da biblioteca padrão stdlib.h.
PORÉM, do ponto de vista de sistemas *nix, o uso de system() deve ser evitado:

1 - A chamada da função system() executa o interpretador de comandos
  (shell), o que o torna muito mais lento que a chamada de um fork()
  seguido de um exec();
2 - É um potencial risco de segurança se você passar como parametro
  uma string de fonte não confiável;
3 - Não pode ser usado de maneira assíncrona, ou seja, o sistema fica
  bloqueado aguardando o retorno do processo filho;
4 - A dupla fork() e exec() nos dá um controle muito maior antes e entre as suas
  chamadas.

O programa a seguir exemplifica execução de um .jar utilizando as chamadas de fork(), exec() e waitpid() em um sistema Linux.
Repare que o processo filho, antes de fazer a chamada de exec(), prepara o ambiente redirecionando os fluxos de saída (STDERR e STDOUT) para dois arquivos de saida: stderr.txt e stdout.txt.
O fluxo do processo pai é bloqueado de propósito com a chamada de waitpid(), mas poderia estar "trabalhando" em outra tarefa:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

#define MAX_CMD_TAM  (1024)

int main( int argc, char * argv[] )
{
    char cmd[ MAX_CMD_TAM + 1 ] = {0};

    /* Verifica se o nome de arquivo .jar foi passado como parametro na linha de comando */
    if( argc != 2 )
    {
        printf("Erro de sintaxe: %s [ARQUIVO_JAR]\n", argv[0] );
        return 1;
    }

    /* Processo pai cria uma copia de si mesmo (cria um processo filho) */
    pid_t child = fork();

    /* Monta a linha de comando que sera executada */
    snprintf( cmd, MAX_CMD_TAM, "java -jar %s", argv[1] );

    if( child == 0 ) /* Fluxo do processo filho */
    {
        /* Abre/Cria arquivos para substituirem as saidss padroes: STDOUT e STDERR */
        int fdout = open( "stdout.txt", O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR );
        int fderr = open( "stderr.txt", O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR );

        /* Redireciona o STDOUT e STDERR para os arquivos correspondentes */
        dup2( fdout, STDOUT_FILENO );
        dup2( fderr, STDERR_FILENO );

        /* Depois de duplicados, os descritores dos arquivos nao sao mais necessarios */
        close(fdout);
        close(fderr);

        /* Executa comando */
        execlp( cmd, NULL );
    }
    else if( child > 0 ) /* Fluxo do processo pai */
    {
        /* Processo pai aguarda a execucao do processo filho */
        printf( "Executando Comando: \"%s\"\n", cmd );

        printf( "Aguardando a execucao do processo filho...\n");
        waitpid(child);

        printf("Sucesso!\n");
    }
    else
    {
        printf("fork() falhou!\n");
        return 1;
    }

    return 0;
}

/* fim-de-arquivo */

Espero ter ajudado!


Comparar dois arrays de objeto?

Question: Preciso fazer a comparação de 2 arrays em Javascript, um que retorna de uma consulta do MongoDB e o outro vem do provedor de emails.
Os dois critérios de comparação são a ID do email e a caixa à qual ele pertence, e o email será descartado se OS DOIS critérios coincidirem, senão o email será gravado no banco.
Até aí tudo ok, o problema é que eu não sei a lógica nem os métodos para fazer isso de forma correta, já tentei usando 2 for e nenhum deu certo.
Servidor:
let dados = [];
    for (let l = 0; l < array.length; l++) { //array é o vetor com os emails que vem do provedor
        dados.push({
            idEmail: array[l].id,
            remetente: array[l].remetente,
            destinatario: array[l].destinatario,
            assunto: array[l].assunto,
            texto: array[l].texto,
            box: flag
        });
    }
    let pesquisa = {'idEmail': {$ne: dados.idEmail}, 'box': {$ne: dados.box}};
    db.open(function (err, mongoclient) {
        mongoclient.collection('emails', function (err, collection) {
            collection.find(pesquisa).toArray(function (err, results) {
                if (err){
                    console.log(err);
                    mongoclient.close()
                } else {
                let comp = [];
                for (let a = 0; a < results.length; a++) {
                    comp.push({
                        id: results[a].idEmail,
                        caixa: results[a].box
                    });
                }
                for (let l = 0; l < comp.length; l++) {
                    if (comp[l].idEmail === dados[l].idEmail && comp[l].caixa === dados.box) {
                        console.log('Repetido')
                    } else if (comp[l].idEmail !== dados[l].idEmail && comp[l].caixa !== dados.box) {
                        mongoclient.collection('emails', function (err, collection) {
                            collection.insert(dados, function (err, records) {
                                if (err) {
                                    console.log(err)
                                } else {
                                    console.log(records)
                                }
                                mongoclient.close()
                            })
                        })
                    }
                }
            }
        })
   })

Answer: Em
comp.push({
   id: results[a].idEmail,
   caixa: results[a].box
});

Sua key é referenciada como id e na condição é tratada como valor
o certo seria
    if (comp[l].id === dados[l].idEmail && comp[l].caixa === dados.box) {
                            console.log('Repetido')
                        } else {
                        mongoclient.collection('emails', function (err, collection) {
                        collection.insert(dados, function (err, records) {
                            if (err) {
                                console.log(err)
                            } else {
                                console.log(records)
                            }
                            mongoclient.close()
                        })
                    })
    }

repare também que seu else if contrária seu if tornando-o simplesmente falso, basta substituí-lo por else.
Comment: É o que eu vou fazer, muito obrigado pela ajuda @Felipe Duarte
Comment: Ok, vou testar aqui e já retorno com o resultado.

E só uma dúvida, é só retirar o `if` que funciona??
Comment: retire o else if e deixe só else e substitua seu if pelo if acima, editei para ficar mais fácil
Comment: Implementei esse código que vc editou, porém não está gravando no banco de dados...
Comment: E agora descobri que o código nem está sendo executado, ele para antes de chegar nessas funções...
Comment: sempre bom ficar de olho no console, e ir debugando os valores com 'console.log' , caso os arrays que queira comparar sejam associativos o código acima já basta se quer comparar cada valor com um array inteiro, 2 loopings são necessários ou outra função exemplo array_map que faz isso mt bem

Comparar dois arrays de objeto?


${(49^{7})}^0=1$ however ${(49)}^{(7^0)}=49$ why don't they equal?

Question: 49 to power of 7 to the power of 0
Now ${(49^{7})}^0=1$ since $x^0 =1$
However ${(49)}^{(7^0)}=(49)^1=49$.
Hence  ${(49^{7})}^0 \neq {(49)}^{7^0}$
Why don't these agree?
When I see ${49^{7}}^{0}$ in questions / texts which meaning should I take?
I am aware of power towers but have not studied them before. I have a Maths Degree (UK).
Comment: Because exponentiation is not associative.
Comment: Why shouldn't they be different? (Also ask for your money back!)
Comment: Why _should_ they agree? Nothing you learned in that Math Degree says they should agree...
Comment: $(a^b)^c$ simplifies to $a^{bc}.$  When you see $a^{b^c}$ you should assume $a^{(b^c)}$ and not  $(a^b)^c.$  And if you mean $(a^b)^c$ you should either include the parenthesis or simplify it.
Comment: When you say, as you wrote:  "49 to power of 7 to the power of 0", it is meaningless, because it is ambiguous:  You list the two possible interpretations; both are legitimate, given the ambiguous statement.  As you note, the interpretations result in two different answers, but we can't say which is wrong or right unless we use parentheses $(a^b)^c$ or else, $a^{(b^c)}$.  From the phrase you start with, neither of this is the right *one*, but each is equally relevant. And so a^b^c is meaningless without parentheses.
Answer: One rule for exponentiation is ${(a^b)}^c=a^{bc},$ so you have ${(49^7)}^0=49^{7*0}=49^0=1.$
When we have $a^{b^c}$, in this case, we have $49^{7^0}= 49$.  These are not equal.
So the phrase "49 to power of 7 to the power of 0" is ambiguous.
As mentioned in the comments, exponentiation is not associative. The two expressions that you have have different meanings.
${(49^7)}^0$ means that you taking the product of zero $49^7$'s  (that is, $\underbrace{49^7*49^7*\dotsi*49^7}_{\text{0 times}}$), so the result is the empty product, 1.
Meanwhile, $49^{(7^0)}$ means that you are taking the product of $7^0$ $49$'s. So, you have $\underbrace{49*49*\dotsi*49}_{7^0=1\text{ times}}=49.$
Comment: That doesn't explain *why to assume* from the written statement that we mean $(a^b)^c$, instead of $a^{b^c}$?   "49 to power of 7 to the power of 0" may mean $(49^7)^0$, or it may mean $49^{7^0}$.  The sentence therefore is ambiguous.  And you simply assumed one particular interpretation.  The point is,  What is your answer?  You give one rule for as to how to interpret $(a^b)^c$, but fail to address what $a^{b^c}$ is nor my you chose your way over its alternative?  Other than that, the answer seems to be nothing more than a (poor) summary of the comments.
Comment: @amWhy Thank you for pointing that out. I was trying to add some information that I didn't explicitly see in previous replies that may help with OP's first question. I will delete or edit later.
Comment: No problem; I also see the asker has edited the question from the original.
Answer: The power operation is not associative.
Note that $3^{(3^3)}=3^{27},$ whereas $(3^3)^3=3^9,$ so the phenomenon is not restricted to a case where one of the exponents is zero.
Answer: There's simply no reason that $(a^b)^c$ should be the same as $a^{(b^c)}$. If you do see the notation $a^{b^c}$ you should probably assume it means $a^{(b^c)}$, because if the author meant $(a^b)^c$ he would have written $a^{bc}$ instead.


Tying accidental natural with same note that has # from key signature

Question: If I have F#  in key signature and I put natural sign in front of this note and I am tying it across the bar line with same F natural do I have to put natural sign on note across the bar too?
Comment: Incidentally, this is the subject of some [unexpected behaviour](https://youtu.be/msJ6-wawFnc) in Finale notation software.
Answer: No, you don't need to set the accidental again in the next bar ( if you mean this);
the accidental in front of a tied note is  affecting the tied note in the next bar too, as e.g. 2 half notes tied across the bar line have the same meaning like one whole note. and the 3 most usual accidentals (there are still double sharp and double flat) are all treated the same. You also don't have to put (repeat) the accidental in the next bar in front of the 2nd tied note, but it is always possible to set it again in brackets (#).
I think this question is asked and answered here.
What conventions are used with accidentals and tied notes?
the problem is a little bit different but is included if you read this information:
https://datadragon.com/education/reading/symbols.shtml
in the explanation and examples of Wikipedia
"the sharp (♯), flat (♭), and natural (♮) symbols, among others, mark such notes—and those symbols are also called accidentals",  they didn't show especially the case of the natural one. but they are handled the same way, you may now combine it with the double sharp (x) and double flat (♭♭) too.


Componente DBTreeGrid para o DelphiXE

Question: Estou precisando de um componente DBTreeGrid para o DelphiXE3? Já procurei no Google mas não encontrei nada :(
Alguém conhece algum?
Answer: A suite DevExpress tem o dxDBTreeList.
Um exemplo pode ser visto neste link https://www.devexpress.com/Products/VCL/ExQuantumTreeList/

Componente DBTreeGrid para o DelphiXE


Monotone convergence of a bounded set.

Question: I'm given $\{b_n\}$ is a bounded set of non-negative numbers and $r$ such that $0 \leq r < 1$.
I need to show the sequence $\{s_n\} = b_1r +b_2r^2 + ... +b_nr^n $ converges. Ideally with the monotone convergence theorem.
So starting out I know $\{b_n\}$ is a bounded set. So $|s_n| \leq Mr + Mr^2 + ... + Mr^n$ and $Mr + Mr^2 + ... + Mr^n = M(r+r^2 + ... + r^n) = M(\frac{1}{1-r})$ so $|s_n| \leq M\frac{1}{1-r}$ giving me that $s_n$ is bounded. I also know that $r,r^2,r^3,...,r^n$ is decreasing monotonically since $0 \leq r < 1$
But at this point I get stuck. I don't know anything about $\{b_n\}$ except that it is bounded and non-negative. Can anybody give me a hint as to where I should be going from here? I know I need to show that somehow $\{s_n\}$ is monotone increasing since we keep adding to it in smaller and smaller amounts. But I don't know how I can show this with the information I have.
Any hints / pointers would be much appreciated.
Also I would ask that people refrain from posting a full proof. I'm trying to learn this material.
Answer: You showed that the partial sums are bounded. By your hypotheses, they are increasing. This means they converge (do you know the theorem that a bounded monotonic sequence converges?).
You asked about showing that $s_n$ is increasing. Each term of the sequence is nonnegative (why?) so this should be clear. What don't you understand?
Comment: Yes, it appears that doing proofs at midnight has its drawbacks. I see my error. I wasn't thinking of the sequence s_n as a sum but focusing on the individual terms. I figured out the rest of my proof now.

Monotone convergence of a bounded set.


Simplify to terms of generalized power mean

Question: I have the following expression${}^1$ I'd like to simplify
$$r \equiv \left[ \frac1{x\sqrt{x}} \left( 1 - \frac{k}{x} \right) - \frac1{y\sqrt{y}} \left( 1 - \frac{k}{y} \right) \right]\left[ \frac1{\sqrt{x}} \left( 1 - \frac{k}{x} \right) - \frac1{\sqrt{y}} \left( 1 - \frac{k}{y} \right)\right]^{-1}$$
where $x > y > k\geq 1$.
Some attempts led me to think that $r$ can be expressed nicely in terms of generalized means of $x,y$ like the harmonic ($p=-1$), geometric ($p \to 0$), and other powers:${}^2$
$$\begin{align}
H &\equiv \left( \frac1x + \frac1y\right)^{-1} & G &\equiv \sqrt{xy} & M \equiv \left( x^p + y^p \right)^{1/p} \quad \text{with perhaps} \quad p=\frac{-1}2
\end{align}$$
To be specific, my question is this:

Is there a way to write it in this form $$r \overset{?}{=} \frac1x + \frac1y + \frac1{\sqrt{xy}} + {}\color{red}{??} =\frac1H + \frac1G + {}\color{red}{??} $$   such that the $\color{red}{??}$ part is "nice" in terms of $k$ and maybe $H,G$ or $M$ defined above?

I also wonder if there's some standard techniques like examining the asymptotic form to guess the coefficients of the proposed terms. I tried a bit but didn't get very far.
Directly pulling out $\frac1H$ and $\frac1G$ just change $r$ into something equally inviting but not more compact.
Any suggestions will be appreciated. Honestly, one main reason for me to think that "oh there must be some nice and more compact forms" is the glaring symmetry. I will be okay if there turn out to be none. Thanks.

Footnote 1:
$\quad$For the record, $r$ is part of the expression of the ratio between $\frac{\partial^2 f(u)}{ \partial u^2}$ and $\frac{\partial f(u) }{ \partial u}$, evaluated at $u=0$, where $$f(u) = \left( \frac1{\sqrt{u+y}} - \frac1{\sqrt{u+x}} \right)\sqrt{u+k}$$
Footnote 2:
$\quad$This is a slight abuse of notations, as the generalized means should carry the averaging factors $\frac12$ or $\frac1{\sqrt{2}}$. My shorthands can also match the p-norms, which has the benefit of the norms ordered in powers have correspondingly decreasing magnitudes. However, p-norms doesn't cover $\sqrt{x y}$ like generalized mean.

Update (Nov.28th, 2017)
With all the inverses lying around, it turns out that the best way is to express $r$ in terms of the ... you guessed it ... inverses: $v \equiv 1/x$ and $w \equiv 1/y$. I'll spare the readers of the actual algebra. Suffice to say that this is also the natural course to take to adopt the notions of p-norms; one just have to give up on unifying $1 / \sqrt{xy} = 1/G = \sqrt{vw}$ formally.
Answer: We can write
$$r=\frac 1H+\frac 1G+\color{red}{\frac{1}{M-G+\frac{GM}{k}}}$$
where
$$M=(x^{-1/2}+y^{-1/2})^{-2}$$

If we write
$$r=\frac{\frac{1}{x\sqrt x}-\frac{1}{y\sqrt y}-k\left(\frac{1}{x^2\sqrt x}-\frac{1}{y^2\sqrt y}\right)}{\frac{1}{\sqrt x}-\frac{1}{\sqrt y}-k\left(\frac{1}{x\sqrt x}-\frac{1}{y\sqrt y}\right)}=\frac 1x+\frac 1y+\frac{1}{\sqrt{xy}}+A$$ then we have
$$A=\frac{k\left(\frac 1x-\frac 1y\right)\left(\frac{1}{x\sqrt y}+\frac{1}{y\sqrt x}\right)}{\frac{1}{\sqrt x}-\frac{1}{\sqrt y}-k\left(\frac{1}{x\sqrt x}-\frac{1}{y\sqrt y}\right)}$$
Using
$$x+y=\frac{G^2}{H},\quad xy=G^2,\quad \frac{1}{M}=\frac 1H+\frac 2G$$
we have
$$\left(\frac 1x-\frac 1y\right)^2=\left(\frac 1H+\frac 2G\right)\left(\frac 1H-\frac 2G\right)\implies \frac 1x-\frac 1y=-\sqrt{\frac 1M\left(\frac 1H-\frac 2G\right)}$$
$$\left(\frac{1}{x\sqrt y}+\frac{1}{y\sqrt x}\right)^2=\frac{1}{G^2}\left(\frac 1H+\frac 2G\right)\implies \frac{1}{x\sqrt y}+\frac{1}{y\sqrt x}=\frac 1G\sqrt{\frac 1M}$$
$$\left(\frac{1}{\sqrt x}-\frac{1}{\sqrt y}\right)^2=\frac 1H-\frac{2}{G}\implies \frac{1}{\sqrt x}-\frac{1}{\sqrt y}=-\sqrt{\frac 1H-\frac{2}{G}}$$
$$\small\left(\frac{1}{x\sqrt x}-\frac{1}{y\sqrt y}\right)^2=\left(\frac 1H+\frac 1G\right)^2\left(\frac 1H-\frac 2G\right)\implies \frac{1}{x\sqrt x}-\frac{1}{y\sqrt y}=-\left(\frac 1M-\frac 1G\right)\sqrt{\frac 1H-\frac 2G}$$
So, we get
$$A=\frac{k\left(-\sqrt{\frac 1M\left(\frac 1H-\frac 2G\right)}\right)\frac 1G\sqrt{\frac 1M}}{-\sqrt{\frac 1H-\frac{2}{G}}-k\left(-\left(\frac 1M-\frac 1G\right)\sqrt{\frac 1H-\frac 2G}\right)}=\frac{1}{M-G+\frac{GM}{k}}$$
Answer: The solution by @mathlove is clear and readily generalized to more complicated tasks, which is one of the major things that what I wanted for this.
For the sake of completeness, let me share my original approach that I was dissatisfied with (which prompted the post).
Each step of manipulation is motivated to gain just a near-sighted progress. This route " feels natural" but contains redundancy.
First observe that $r$ takes the form of a "mixture" that is not entirely $\frac1x$ nor entirely $\frac1y$.
$$ r = \frac{ \frac1x \alpha - \frac1y \beta}{ \alpha - \beta } \quad \text{with} \quad \alpha\equiv \frac1{\sqrt{x}}\left( 1 - \frac{k}{x} \right),~\beta\equiv \frac1{\sqrt{y}}\left( 1 - \frac{k}{y} \right)$$
Here we break the mixture by pulling out a mixture.
$$ \begin{align}
r &= \frac1{\alpha - \beta}\left\{ \left[ \frac12 \left( \frac1x + \frac1y \right) + \frac12 \left( \frac1x - \frac1y \right) \right] \alpha - \left[  \frac12 \left( \frac1x + \frac1y \right) - \frac12 \left( \frac1x - \frac1y \right) \right]  \beta \right\} \\
&= \frac12 \left( \frac1x + \frac1y \right) + \frac{\alpha + \beta}{\alpha - \beta}\frac12 \left( \frac1x - \frac1y \right) \tag{Eq.1}
\end{align}$$
The definitions of $\alpha+\beta$ and $\alpha-\beta$ move the product forward naturally.
$$\begin{align}
\alpha+\beta &= \frac1{\sqrt{x}} + \frac1{\sqrt{y}} - k \left( \frac1{x^{3/2}} + \frac1{x^{3/2}} \right) = \left( \frac1{\sqrt{x}} + \frac1{\sqrt{y}} \right) \left[ 1 - k \left( \frac1x - \frac1{\sqrt{xy}} + \frac1y \right) \right ] \\
\alpha - \beta &= \frac1{\sqrt{x}} - \frac1{\sqrt{y}} - k \left( \frac1{x^{3/2}} - \frac1{x^{3/2}} \right) = \left( \frac1{\sqrt{x}} - \frac1{\sqrt{y}} \right) \left[ 1 - k \left( \frac1x + \frac1{\sqrt{xy}} + \frac1y \right) \right].
\end{align}$$
$$\begin{align}
\text{so that} \quad &\phantom{{}={}}\frac{\alpha + \beta}{\alpha - \beta}\frac12 \left( \frac1x - \frac1y \right) \\
&= \frac{\alpha + \beta}{\alpha - \beta} \frac12 \left( \frac1{\sqrt{x}} + \frac1{\sqrt{y}} \right) \left( \frac1{\sqrt{x}} - \frac1{\sqrt{y}} \right) \\
&= \frac12 \left( \frac1{\sqrt{x}} + \frac1{\sqrt{y}} \right)^2 \left\{ 1 + \frac{2k}{\sqrt{xy}} \left[ 1 - k \left( \frac1x + \frac1{\sqrt{xy}} + \frac1y \right) \right]^{-1} \right\} \\
&= \left[ \frac12 \left( \frac1x + \frac1y \right) + \frac1{\sqrt{xy}} \right] \left\{ 1 + \frac{2k}{\sqrt{xy}} \left[ 1 - k \left( \frac1x + \frac1{\sqrt{xy}} + \frac1y \right) \right]^{-1} \right\}
\end{align}$$
Substitute this back to Eq.1 (here the redundancy shows) you get
$$ \begin{gather}
r = \frac1x + \frac1y + \frac1{\sqrt{xy}} + A \qquad \text{same as @mathlove opening line} \\
\text{where} \qquad A = \left[ \frac1x + \frac1y + \frac2{\sqrt{xy}} \right] \frac{k}{\sqrt{xy}} \left[ 1 - k \left( \frac1x + \frac1{\sqrt{xy}} + \frac1y \right) \right]^{-1}
\end{gather}$$
So this is going through a lot of trouble just to pull the inverses out sequentially. The only difference is that the remaining term $A$ written in this form is readily recognized as
$$A = \frac1M \frac{k}G \left[ 1 - k\left( \frac1H + \frac1G \right) \right]^{-1} \quad \text{or} \quad \frac1M \frac{k}G \left[ 1 - k\left( \frac1M - \frac1G \right) \right]^{-1}$$
depending on your taste.


How to create multiple log files in log4j2 using property file?

Question: I am using .property file to create log file in specific path but i am creating single file using that. Following is my code of property file:
    status = error
dest = err
name = PropertiesConfig

property.filepath= /ap
property.filename =${filepath}/ai.log
property.filename1 =${filepath}/file1.log
property.filename2 =${filepath}/file2.log

filter.threshold.type = ThresholdFilter
filter.threshold.level = debug

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

appender.file.type = RollingFile
appender.file.name = RootFile1
appender.file.fileName = ${filename}
appender.file.filePattern = ${filepath}/%d{yyyyMMdd}/cpl.mw.%d{yyyyMMdd}.%i.log.gz
appender.file.layout.type = PatternLayout
#appender.file.layout.pattern = %d %p %C{1.} [%t] %m%n
appender.file.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.file.policies.type = Policies
appender.file.policies.time.type = TimeBasedTriggeringPolicy
appender.file.policies.time.interval = 1
appender.file.policies.time.modulate = true
appender.file.policies.size.type = SizeBasedTriggeringPolicy
appender.file.policies.size.size=50MB
appender.file.strategy.type = DefaultRolloverStrategy
appender.file.strategy.max = 20

appender.rolling1.type = RollingFile
appender.rolling1.name = RollingFile1
appender.rolling1.fileName = ${filename1}
appender.rolling1.filePattern = ${filepath}/%d{yyyyMMdd}/cpl.mw.%d{yyyyMMdd}.%i.log.gz
appender.rolling1.layout.type = PatternLayout
#appender.rolling1.layout.pattern = %d %p %C{1.} [%t] %m%n
appender.rolling1.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.rolling1.policies.type = Policies
appender.rolling1.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling1.policies.time.interval = 1
appender.rolling1.policies.time.modulate = true
appender.rolling1.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling1.policies.size.size=50MB
appender.rolling1.strategy.type = DefaultRolloverStrategy
appender.rolling1.strategy.max = 20

appender.rolling2.type = RollingFile
appender.rolling2.name = RollingFile2
appender.rolling2.fileName = ${filename2}
appender.rolling2.filePattern = ${filepath}/%d{yyyyMMdd}/cpl.mw.%d{yyyyMMdd}.%i.log.gz
appender.rolling2.layout.type = PatternLayout
appender.rolling2.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.rolling2.policies.type = Policies
appender.rolling2.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling2.policies.time.interval = 1
appender.rolling2.policies.time.modulate = true
appender.rolling2.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling2.policies.size.size=50MB
appender.rolling2.strategy.type = DefaultRolloverStrategy
appender.rolling2.strategy.max = 20

loggers
logger.name=file1
logger.level = debug
logger.additivity = true
logger.appenderRefs = rolling1,stdout
logger.appenderRefs.level = debug
logger.appenderRef.rolling1.ref = RollingFile1
logger.appenderRef.stdout.ref = STDOUT

logger.name=file2
logger.level = debug
logger.additivity = true
logger.appenderRefs = rolling2
logger.appenderRefs.level = debug
logger.appenderRef.rolling2.ref = RollingFile2

above code is of my xyz.properties file i want to create multiple logs using this configuration file.My property configuration file create multiple file but not put different different logs in log files.I call this from JAVA using below code:
private static final Logger logCommon = LogManager.getLogger("file1");
private static final Logger logAnalytics = LogManager.getLogger("file2");

public static void main(String[] args) throws Exception {

    logCommon.info ("file1 Need it save into commons.log file");
    logAnalytics.info ("file2 Only save into analytics.log file");

}

2018-01-22 12:52:23 INFO  file2:301 - file2 Only save into analytics.log file log put in both log files.
I refer below links:
Log4j2: Dynamic creation of log files for multiple logs
Wildcard pattern for RoutingAppender of Log4j2
How to write different logs in different files with log4j2 (MDC in xml)?
http://logging.apache.org/log4j/2.x/manual/extending.html
i refer below links but not get any solution:
How to implement multi file appender in log4j2
How to avoid multiple log files in slf4j logging?
log4j2 - generate application specific log files in weblogic
How to create multiple log files of different content with log4j
enter link description here
log4j2 KeyValuePair for .properties file
How to Create a Custom Appender in log4j2?
Configuring async loggers in log4j2.properties
How to create custom RewritePolicy in log4j2?
How to set the log level on a class in log4j2 properties
Increasing file indexing on OnStartupTriggeringPolicy in log4j2
how to configure log file path to current working target directory in log4j2 xml format
How to configure RestTemplate debug logging in log4j2 xml
Creating multiple log files in iPhone app
Log4j2 using multiple appender and logger
How to create multiple log file programatically in log4j2?
How to create multiple log file programatically in log4j2?
How to specify log file in log4j2
Log separate log levels to separate files in log4j2 properties file
Unable to create multiple log files based on the ThreadContext map values using routing appender in log4j2
How to create Custom Rolling File appender in log4j2 - customized file name
Different log files for multiple threads using log4j2
Log4j2 YAML generate multiple log files issue
How to create multiple log files using log4j
Log4j2 - Overriding log file programmatically
How to create a rolling file appender plugin in log4j2
Comment: @CowboyFarnz  i want property file of log4j2 not log4j
Comment: Hey, try this link [Logger link](https://stackoverflow.com/questions/9652032/how-can-i-create-2-separate-log-files-with-one-log4j-config-file)
Comment: I am new in log4j2 configuration
Answer: Please set additivity=false for both named loggers.
Also, add a root logger configuration to tell Log4j2 where to send the logging calls other than the "file1" and "file2" loggers:
rootLogger.level = info
rootLogger.appenderRef.stdout.ref = STDOUT

Also, give your named loggers a unique prefix:
logger.aaa.name = file1
logger.aaa.additivity = false
logger.aaa.level = debug
logger.aaa.appenderRef.rrr.ref = RollingFile1

logger.bbb.name = file2
logger.bbb.additivity = false
logger.bbb.level = debug
logger.bbb.appenderRef.sss.ref = RollingFile2

Comment: both file store same log:
Comment: What do you see?
Comment: 2018-01-29 15:40:42 INFO  Logbook:190 - file2 Only save into analytics.log file
Comment: Updated my answer
Comment: Glad to hear that
Answer: Use below configuration and call addLogger() whenever you want to use with fully qualified path
public static void addLogger(String parentPath) throws SecurityException, IOException {
        try {
            InputStream in = ConfiguratorHelper.class.getResourceAsStream("/resources/mylogging.properties");
            LogManager.getLogManager().readConfiguration(in);
        } catch (SecurityException | IOException e1) {
            e1.printStackTrace();
        }
        logger.setLevel(Level.FINE);
        logger.addHandler(new ConsoleHandler());
        logger.addHandler(new MyHandler());
        try {
            //FileHandler file name with max size and number of log files limit
            Handler fileHandler = new FileHandler(path, 1000000, 10);
            fileHandler.setFormatter(new MyFormatter());
            fileHandler.setFilter(new MyFilter());
            logger.addHandler(fileHandler);
            logger.log(Level.CONFIG, "Config data");
        } catch (SecurityException | IOException e) {
            e.printStackTrace();
        }
    }

public class MyFilter implements Filter {

    @Override
    public boolean isLoggable(LogRecord log) {
        //don't log CONFIG logs in file
        if(log.getLevel() == Level.CONFIG) return false;
        return true;
    }

}

public class MyFormatter extends Formatter {

    @Override
    public String format(LogRecord record) {
        return record.getThreadID()+"::"+record.getSourceClassName()+"::"
                +record.getSourceMethodName()+"::"
                +new Date(record.getMillis())+"::"
                +record.getMessage()+"\n";
    }

}

public class MyHandler extends StreamHandler {

    @Override
    public void publish(LogRecord record) {
        //add own logic to publish
        super.publish(record);
    }

    @Override
    public void flush() {
        super.flush();
    }

    @Override
    public void close() throws SecurityException {
        super.close();
    }

}


Add a file field to a block

Question: I have a problem concerning the blocks in drupal.
I need to create a block that has additional fields, image and files, I am currently using the add block feature in Home » Administration » Structure and I just need to add two fields there so I can upload pdf's and images.
I was thinking that there must be a way to add those fields from the admin panel, without programming it by hand or installing modules? Is it possible ?
Answer: No.
Blocks aren't entities in Drupal 7, so there's no real way to add fields to them.
If you want fields on blocks, then take a look at the awesome Bean module.

Beans were driven by the API first. This means that you can create
  block types (bean types) all in a plugin class turning off the UI. The
  entire configuration in code. No worry about feature reverts.
Comment: Well that answers my question, thanks:) i am installing the module now.

Add a file field to a block


Maximum of a set of values from given mean and median

Question: The arithmetic mean and median of $5$ distinct natural numbers are both $7$,what may be the maximum of the $5$ numbers?
Here we see that the median is the $3rd$ value.Also the sum of the numbers is $35$.
Can we get any idea about the maximum value from this?
Comment: You write "we see that the median lies between 3rd and 4th value."  Are you sure?  Also, you state that the numbers must live in $\{1, 2, \ldots\}$ (or maybe you define the natural numbers as including zero -- up to you).  Do you see how that helps?
Comment: The maximum isn't unbounded either (it's finite a natural number exactly as suggested by the question; in fact it's obvious it must be less than 35).
Comment: Please read the [help/on-topic] in relation to homework (though the comments apply to more than just homework) and also the `self-study` [guidelines](http://stats.stackexchange.com/tags/self-study/info). You need to show some effort yourself and explain what you've tried, or to ask a very specific question that would arise from a proper attempt (not just "how do I do this exercise")
Comment: @Adrian, I apologize,I was wrong to state the median between  3rd and 4th value.It will be the 3rd value.I have edited my question.I have recently read article about that zero can not be included in a set of natural numbers.If zero is included then it is easy to find the maximum.
Comment: @Glen_b , All that I understood from the problem is that the median can not be stated specifically.Probably, It is unbounded.But I was not sure as I was not able to prove it in any way.I apologize, from the next time I will definitely try to put some more efforts before asking a question.
Comment: The median is stated to be 7. I don't understand any difficulty there. What do you mean by it being "unbounded"? It's $\mathbf{7}$
Comment: @Glen_b , Thanks for the answer.Yes, It will be 7.
Answer: This is quite straightforward.
Start with any five different natural numbers* with the required properties (median and mean both 7) and then see how you can change them without changing the mean or the median.
* As Adrian notes and as discussed at the link above, whether the natural numbers includes 0 depends on who you're talking to; you will need to check which definition you're expected to use (or to do it for both cases -- once you've done it for one definition, the other is simple)
Manipulating the set of numbers while keeping the mean and median unchanged is easiest if you have the five starting numbers in sorted order.
It's trivial to keep both mean and the median the same as you change some of the numbers; in each case any change you make must leave something unchanged (you note a connection between the mean and the sum - keep that connection mind to figure out what has to stay unchanged as you change numbers).
Once you see what that thing is in each case (one for the median and for the mean), it's a simple matter to change everything else as far as it is possible to do which will increase the largest number, and finally to confirm that no further changes can be made without breaking at least one of the conditions.
You may like to get things rolling by thinking about how small the smallest number can be (why as small as can be? ... think about that, too)

Since it's been up more than a day I can perhaps add a little more information. If the OP posts some additional thoughts I may go further.
Clearly the two invariants to play with are that $\sum_i x_i = 35$ (which makes the mean correct) and that $x_{(3)}=7$ (the median is then correct). So whatever you do must satisfy those points.
Imagine we start with the numbers $(4,5,7,9,10)$ for $(x_{(1)}, ...,x_{(5)})$.
This satisfies both conditions.
Now we would like to make $x_{(5)}$ larger but must keep the sum at $35$. Which other numbers can be moved? Which direction should they go? How far can they go?
Comment: If we start with the numbers $(4,5,7,9,10)$ ,to make the $5th$ value as large as possible we can write $(1,2,7,8,17)$ , here the median and mean are both 7 and I think 17 is the maximum value of the set that we can get.


Assign Roles to Directory Pages in Membership and Roles

Question: I am creating a web application and i am using membership and roles. In my application i have 4 Roles.

Admin
Receptionist
Scheduler
Accountant

i have one page of registerpatient.aspx common in both receptionist and Scheduler. Means both can create a patient. then in which folder i should put this page so that both can access. i dont want any other user to access this page. I am using Roles management by membership and roles. so we can assign roles to Directory so how to assign to particular pages ?
Answer: You can do this by adding location configuration. Location is a web.config section that apply for only one directory or file and contains its own system.web section. See a post about that here:
http://weblogs.asp.net/gurusarkar/archive/2008/09/29/setting-authorization-rules-for-a-particular-page-or-folder-in-web-config.aspx


Cyclical vibration frequency on some of the strings?

Question: I have a yamaha 311h, I was playing around in Amplitube ultra tuner and noticed something weird with the tuning of the 4th, 2nd and 1st strings.
All of these strings are cycling in vibration compared to all the rest of the strings which have a very constant, flat response.
6th string, low E https://postimg.cc/NyF057P4
5th string https://postimg.cc/185FrFjg
4th string https://postimg.cc/dD6rknWM
3rd string https://postimg.cc/xXv08pRM
2nd string https://postimg.cc/sQqX7QZh
It's also pretty strange that at the 12th fret the tuning is very stable for the 4th string:
4th string, 12th fret https://postimg.cc/LY8m8rm5
Plus, 6th and 5th string are at +10 when fretted on 12th string compared to open string tuning.
What could be causing this and how to fix it please?
Answer: It appears to be a typical intonation set up problem, where the saddles on the bridge are not adjusted proerly.
When a 12th fret harmonic is at the same pitch as the fretted string (again 12th), all is good. Simple adjustment with an Allen key on that guitar, I think.
Comment: MIght be worth a few sentences about the physics - wrong string length can lead to competing induced resonances among strings, which leads to that sort of pitch oscillation.
Comment: @CarlWitthoft - you're talking a foreign language - I only do simple! Sounds like it could be your few sentences?


Node.js e PHP no mesmo servidor

Question: Tenho um servidor dedicado CentOS 6.5 com o Painel Plesk 12 instalado, com vários sites em php. Gostaria de desenvolver um chat com node.js e integra-lo com alguns sites feitos em php. Só que esse chat precisa recuperar algumas informações do usuário que está logado Ex.: O usuário só pode acessar o chat se estiver logado. Qual seria a melhor maneira de integrar as duas coisas PHP + Node.js?
Solução:
Segui a sugestão do Lauro Moraes nessa pergunta: Integrar aplicação nodejs a site php em servidores distintos?, e fiz o que o Guilherme me sugeriu. O cliente se loga no site PHP, os dados da sessão são salvos no banco de dados no caso eu usei o Redis. Na parte do php eu solicito ao Node.js por meio do socket.io enviando o cookie com o id da sessão. No Node.js eu pego esse id da sessão, consulto no banco de dados do Redis e libero o acesso.
Answer: Aparentemente você está querendo construir uma arquitetura com SSO (Single sign-on). O SSO é definido como um único ponto de entrada, ou seja, você necessita se autenticar uma única vez. Isso permite acesso automático a diversos módulos de um sistema, sem a necessidade de digitar seu login e senha em cada módulo.
Para implementar o SSO, é preciso construir uma arquitetura para realizar essa comunicação entre sistemas diferentes. No seu caso, há uma abordagem relativamente simples para sua pergunta: guardar as informações no estado de sessão com o PHP em um banco de dados, e ler, com o Node.js, o cookie de sessão e verificá-lo no banco de dados para se certificar que o usuário está logado.
Existem outras soluções parecidas como o uso de memcache no Node.js, mas todas possuem uma implementação relativamente grande, que não seria recomendado colocar aqui (ocuparia muito espaço da tela).
Referências
O que é o Single Sign-On
Sharing data between php and node.js via cookie securely
Comment: Guilherme dá para colocar exemplos de código para resolver o problema?
Comment: É que a solução não é lá muito pequena. Existem alguns artigos sobre [como guardar as sessões no banco de dados em PHP](http://www.devshed.com/c/a/PHP/Storing-PHP-Sessions-in-a-Database/), por exemplo, que são um pouco extensos.

Node.js e PHP no mesmo servidor


Drupal custom page template based on the title of the page

Question: I have the following page:
About us

Whose path is:
site.com/node/6

Theme suggestions for the template files are:
page--node--6.tpl.php
page--node.tpl.php

You should already know that it is too weird to create custom template files based on the node's id, thus I like to have my custom page template based on the page's title (of course, converted to machine name, for instance "About us" to be "about-s"). What should I do?
Comment: Correct @Mostafa, there's no default theme hook suggestions for the page template based on a node alias - just for the internal path (eg node/1). Given that the node id is far less ephemeral than the title, using that method would usually be preferred. Your "you should already know that it's too weird...based on the node id" suggestion is incorrect in my opinion
Comment: Have you tried Context or Panels modules. you can set displays of different pages based on different criteria.
Comment: I have them installed. You mean it is not possible by default in Drupal?
Comment: Maybe somebody else can answer that. I don't bother going the template route with those modules around. I mainly use Panels.
Comment: With title I mean a GUID in String than in vague Integer.
Comment: That's a terrible idea @Mostafa - an alias/title is **not** a GUID. It can be changed, so by definition that doesn't make sense. Not to mention that node titles are not unique. URL slugs are for humans, not computers, so when you're talking to a computer (ie naming a template file), you should use a proper and reliable identifier. Which in this case is the node id.
Comment: well, with GUID, you are right. In many frameworks we use a master template, and then for a certain page, like "about us", you would make another template called something like "about-us.tpl". Now, in Drupal, due to automatic scanning for templates, it should have permitted unique-names, machine-names generated/suggested by Drupal itself. For a front-end developer, it is too vague to search around for about-us page and discern it by seeing page--node--6.tpl.php file. Why do you defend it? There should be, must be, better to be, is necessary to have human-readable names for the template files.
Comment: Yes it's possible (see the answer); but it's definitely not necessary, hence its absence from core. You have a non-standard requirement to address template files by their URL alias or node title (I'm not 100% sure which you're after), so you'll need to code that yourself. The very fact that node titles are not unique should be enough to explain why it's not possible to do this, unless you also do something _else_ to mandate that node titles can't be duplicated. Drupal doesn't have the same constraint out of the box, so the feature you're looking for can't exist without extra work
Comment: As an aside, I'm defending it because given the nature of content in Drupal core, it would be illogical for these template suggestions to already exist. Just to be clear, I'm not suggesting for a moment that your requirement isn't a valid one (me thinking it's not the best idea is irrelevant), I'm just trying to explain why you won't find what you're looking for without jumping through some hoops
Comment: I do not necessarily stick to node's title, an extra field for unique_name or machine_name should suffice. You see famous modules such as Context already follow named GUID, than numeric ones.
Answer: I don't think this is an optimal solution at all, because node titles can easily be changed (and duplicated), but here you go:
function MY_THEME_preprocess_node(&$vars) {
  // This assumes that you are using Pathauto for generating clean URLs.
  // Get the "clean" title.
  $title = pathauto_cleanstring($vars['node']->title);
  // Replace all dashes with underscores. This is necessary for recognizing the
  // template filenames.
  $title = str_replace('-', '_', $title);
  // Add new template variation.
  $vars['theme_hook_suggestions'][] = 'node__' . $title;
}

Note: to make this bulletproof for different languages, alphabets and special characters, make sure you have the Transliteration module installed and set to transliterate strings prior to creating URL aliases. This way if a node title has non-standard character (e.g. Č) it will be transliterated to Latin alphabet (in this case C).
Comment: @Alexar that's not necessarily  correct - if you were creating a CSS class, then sure, but in this case you need the URL alias. Since path auto produces that alias, you should use its functions to reproduce the clean string (I'm assuming path auto installed, I've yet to come across a site where it isn't)
Comment: After testing this, I don't think `drupal_clean_css_identifier` is a viable solution anymore because it does not make the string lowercase, and there could be other edge cases (two spaces are converted to `--` for example) where this will provide quirky results. Hope this makes sense.
Comment: @Topsitemakers I agree that transliteration is totally helpful. Also I can see that `drupal_clean_css_identifier()` is not doing `strtolower` and I figured `drupal_html_class()` is the right one. But I would argue the assumption of having pathauto installed. Given all these, I would do something like this `$title = module_exists('pathauto') ? pathauto_cleanstring($title) : drupal_html_class($title);`
Comment: Instead of using pathauto function, I'd suggest to use Drupal's core function: `drupal_clean_css_identifier()` https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_clean_css_identifier/7 You could consider updating your answer as well.
Comment: Thanks for the comment. The only downside to using Pathauto's function is that you need to have Pathauto installed, which most of the sites already do. `drupal_clean_css_identifier()` also does not transliterate the characters, so you would need another function call to clean the output. I can update it for future reference, but I believe the Pathauto approach makes more sense, because that's the module that will generate your URLs anyway, and it's shorter.
Comment: @Alexar You shouldn't use a function designed for preparing html classes or identifiers to prepare a filename. `drupal_html_class()` and `drupal_clean_css_identifier()` are not appropriate for this
Comment: @Clive I would suggest you first read w3 standards for naming conventions for CSS class names (http://www.w3.org/TR/CSS21/syndata.html#characters), checkout ISO 10646 (http://www.columbia.edu/~fdc/utf8-t1.html), understand what actually file name is (http://en.wikipedia.org/wiki/Filename) and what are invalid characters in different operating systems (https://support.filetransporter.com/article/AA-00410). It is totally safe to use `drupal_clean_css_identifier()` to sanitize file names or you need to support your claim by providing references.
Comment: @Alexar no need to try to be condescending, please keep it civil. I just disagree with you; you can hammer in a nail with a screwdriver, doesn't mean you should.
Comment: @Clive no worries mate. I was challenging you to convince me "why not?" when you say "you shouldn't". This way we learn, we fix ourselves if we are wrong and will leave other readers with valuable arguments and countable decisions. easy.
Comment: @Topsitemakers thanks for your comment it worked with me :)


Failed validation redirects to normal path

Question: I'm using the sub-pathauto module.
I can edit node 1 of type list from the path list/1/edit. However, when validation fails I'm redirected back to node/1/edit (the normal path).
Is this a known limitation of the module? Something I have to accept?
Answer: In your custom module add below code,It check If url not in alias path, redirect it to aliased path.
<code>function mymodule_init() {
    if(module_exists('subpathauto'){
  $alias = subpathauto_lookup_subpath('alias', current_path(), current_path());
  if (!empty($alias) && $alias != request_path()) {
    drupal_goto($alias, array(), 301);
  }
 }
}
</code>


FeedsHTTPFetcher: how to parse object to get source url?

Question: I've got several content-types based on imported RSS feeds (Feeds import, Simple Pie library).
In a Views pre render, I try to display an information stored in $row->node_feeds_item__feeds_source_config that looks like this:
a:1:{s:16:"FeedsHTTPFetcher";a:1:{s:6:"source";s:38:"http://www.as-e.be/agendas_rss/rss.xml";}}

How can I just get the http://www.as-e.be/agendas_rss/rss.xml part of that object? I have no idea how to parse that.
Answer: Ok, I found out a dirty solution to extract an URL from a random string text!
preg_match('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $row->node_feeds_item__feeds_source_config, $match);


RTNETLINK answers: Cannot assign requested address

Question: 161: ovs_bond0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1
    link/ether 00:11:32:xx:xx:xx brd ff:ff:ff:ff:ff:ff
    inet 192.168.0.20/24 brd 192.168.0.255 scope global ovs_bond0
       valid_lft forever preferred_lft forever
162: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN group default qlen 500
    link/none
    inet 10.8.0.1 peer 10.8.0.2/32 scope global tun0
       valid_lft forever preferred_lft forever
164: vdsm@ovs_bond0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1
    link/ether 56:25:46:xx:xx:xx brd ff:ff:ff:ff:ff:ff
    inet 192.168.0.206/32 scope global vdsm
       valid_lft forever preferred_lft forever
    inet 192.168.0.209/32 scope global vdsm
       valid_lft forever preferred_lft forever
    inet6 fe80::xxxx:xxxx:xxxx:xxxx/64 scope link
       valid_lft forever preferred_lft forever
ash-4.4# ip addr del 192.168.0.206/32 dev ovs_bond0
RTNETLINK answers: Cannot assign requested address

can't delete 192.168.0.206 from ovs_bond0
Answer: I solved this by running these commands:
ip addr del 192.168.0.206/32 dev vdsm
ip addr del 192.168.0.209/32 dev vdsm


How to transform the size of the image dynamically?

Question: I want to crop the selected portion of the image that user has selected. I would like to implement like in the following image

By moving the button/image(green bordered box) , the user can select the portion he wants. Can any one please tell me how to do this or please provide me the sample code if you have any.
Any help will be appreciated.
Answer: Check out BJImageCropper. This also have an example.
Comment: Thanks, Nice project, Can you tell me any project that has an option to crop the selected area.


Congruency Modulo - How to Derive

Question: I'm wondering how to derive $41 \equiv 6 \pmod 7$ or $2 \equiv 2 \pmod 7$. Is there a formula for that?
Comment: You just do integer division $41 : 7$ with remainder, so $41=7\cdot 5+6$, so the remainder is $6$.
Answer: According to definition, $a\equiv b \pmod c$ iff $a$ and $b$ have the same remainder when divided by $c$.
$41$ has a remainder of $6$ when divided by $7$.
$2$ has a remainder of $2$ when divided by $7$.

Congruency Modulo - How to Derive


The same open sets

Question: How to prove that the two distances $d(x,y)=|x-y|$ and $d'(x,y)=
|\exp(x)-\exp(y)|$ induced the same topology on R ?
I know that for $a\in R, r>0$
$B_d(a,r)=]a-r, a+r[$,
$B_{d'}(a,r)=]\ln(\exp(a)-r), \ln(\exp(a)+r)[$
How to do ?
Answer: I think that you can use this fact:
If $X$ is a first countable space then a function $f: X\to Y$ is continuos if and only if for each convergent sequence $\{x_n\}_n$ convergent to a point $x$ then $\{f(x_n)\}_n$ is convergent to $f(x)$
Now you can observe that if $X$ has two Topology $\tau_1$ and $\tau_2$ such that $(X,\tau_1)$ is first countable and for  each $\tau_1-$convergent sequence $\{x_n\}_n$ to a point $x$ is $\tau_2-$ convergent sequence to the point $x$ then $\tau_2\subseteq \tau_1$ infact by first lemma you have that the identity map
$Id: (X,\tau_1)\to (X,\tau_2)$
is a countinuos function so for each open set $A\in \tau_2$ then $Id^{-1}(A)=A$ is open in $\tau_1$. So $\tau_2\subseteq \tau_1$.
In your case $\mathbb{R}$ is a first countable set with respect both Topology because they are induced by a distance. You have also that the function $exp$ is a countinuos function from $\mathbb{R}$ to $\mathbb{R}$ so if $\{x_n\}_n$ is convergent to $x$ with respect $d_1$ then
$\lim_{n\to \infty}|exp(x_n)-exp(x)|=|exp(x)-exp(x)|=0$
so $\{x_n\}$ it is convergent to $x$ with respect to $d_2$ so you have that
$\tau_2\subseteq \tau_1$
Now you can hypothesize that a sequence  $\{x_n\}_n$ is convergent with respect $d_2$ to a point $x$ then
$\{x_n\}_n$ is convergent with respect $d_1$ to a point $x$ because $log$ is a countinuos function and so
$\lim_{n\to \infty}|x_n-x|=\lim_{n\to\infty}| log(e^{x_n})-log(e^x)|=0$
So you have that $\tau_1\subseteq \tau_2$
It is obvious that you can generalize your statement:
If $f:\mathbb{R}\to \mathbb{R}$ is an injective function then it is possible define a distance $d_2$ on $\mathbb{R}$ in the following way:
$d_2(x,y):=|f(x)-f(y)|$
If $f:(\mathbb{R},\tau_{eu})\to (\mathbb{R},\tau_{eu})$ is a continuos function then $\tau_2\subseteq \tau_{eu}$.
If $f$ in bijective and your inverse it is continuos then
$\tau_{eu}\subseteq \tau_2$
Comment: It is really difficult, i don't advise you to try that way
Comment: we can't prove with balls?
Comment: ok, if you know please help me just to know
Comment: please do you know how to prove that there is no $a,b>0, \forall x,y\in \mathbb{R}, a d(x,y)\leq d'(x,y)\leq  b d(x,y)$??
Comment: Does not exist that b because exp is not a Lipshitz function
Comment: and for a how to obtain it ?
Answer: Suppose that $(a, b)$ is an open ball in the ordinary topology. (That is, it is the ball
$$
B_d\left(\frac{a+b}2, \frac{b-a}2\right),
$$
but that doesn't matter for our argument.) Then take
$$
x = \log\left(\frac{\exp(a)+\exp(b)}2\right), r = \frac{\exp(b) - \exp(a)}{2}.
$$
We have that
$$
B_{d'}(x, r) = \left(\log(\exp(x) - r), \log(\exp(x) + r)\right) = (a, b),
$$
where I've used your expression for $B_{d'}(x, r)$ in your question. Conversely, consider $B_{d'}(x, r)$ for arbitrary $x, r > 0$. We consider two cases. If $\exp(x) - r$ is positive, then we have your expression again, namely
$$
B_{d'}(x, r) = \left(\log(\exp(x) - r), \log(\exp(x) + r)\right),
$$
and then we already have an open interval in the normal sense. On the other hand, if $\exp(x) - r \leq 0$, then we have that
$$
B_{d'}(x, r) = (-\infty, \log(\exp(x) + r)).
$$
Can you prove that this set is open in the ordinary topology (induced by $d$)?

The same open sets


Statistical models and methods to evaluate and forecast "fine price" increases

Question: I want to evaluate the implications of increasing fine prices. I will have a few different scenarios ranging from business as usual, minor increase, proportional increase, categorical increase, to extreme-increases. Each scenario will have different levels of monetary increase depending on the fine details and subprograms. Also, I'd like to do comparative analysis of implementing a strike base system (x times you get a fine, you're out) versus a cooperative non-extreme user lead system.
Are there any models that predict such increases, especially considering that there is a likelihood of people to eitehr decrease their or increase there frequency of fines after a new system is in place.
Answer: Yes, Gary Becker discusses this at length famously in "Crime and Punishment: An Economic Approach".  You can find it at
http://www.nber.org/chapters/c3625.pdf

and in his Nobel lecture section on crime at
http://faculty.smu.edu/millimet/classes/eco4361/readings/quantity%20section/becker.pdf

Typically, any model of the level of a fine will be intrinsically married to the probability of detection, as in:
http://18.104.22.168/faculty/shavell/pdf/81_Amer_Econ_Rev_618.pdf

More recently, Harold Winter wrote a book in 2008 titled The economics of crime: an introduction to rational crime analysis. There is a chapter on setting fines and one can straightforwardly form econometric models from the framework provided
An example of a rather elementary game theoretic approach is here:
http://bal.buu.ac.th/bal2010/sites/default/files/Research%20report%202008.07.pdf


Reliably convert a string to a double independent of regional settings in classic ASP?

Question: I'm working on a legacy classic ASP interface between our client application and the server. This is not a website, just an intermediate layer in ASP (I know this is not the preferred way of doing things, told you it's legacy and it can - unfortunately - not be changed at this point).
So I'm sending a double value as a parameter on the query string like this:
http:\\localhost\virtdir\myobject.asp?f=function&1=5.25

Now in ASP, I take that value and pass it on to a method on a COM component (myobject is an instance of that COM component) using CDbl to cast the string value to a double:
myobject.DoMethod(CDbl(Request.QueryString("1")))

(Actually, I don't think I have to use CDbl here, as this will be casted implicitly because the COM method takes a double as parameter?)
My problem now is that this doesn't work if in the regional settings of the server a ',' is used as decimal separator. In that case I have to pass "5,25" on the query string to make it work.
As the client doesn't know about the regional settings of the server, is there any reliable way to make sure that a cast to CDbl will always work with the same decimal separator, regardless of the regional settings? Or is there another function like CDbl which does this? Thanks!
Answer: you could force the "current culture" using this before calling cdbl
SetLocale(1033)
Session.LCID = 1033

Comment: by the way you can set 1033 to something else jsut look on google for a full chart ( really easy to get)
Comment: Nice! This is what I needed. Only `SetLocale(1033)` was enough though. No need to set `Session.LCID` as well, or would this be needed in some other obscure scenario of which I am not aware?


Converting arrays of strings from matlab to java

Question: I have a java GUI which I have written, it has some underlying back end to it that is currently in MATLAB.
I am trying to call all the back end functions from the Java portion for ease of use, and I have successfully been able to run the MATLAB functions from java using the MATLAB controller (https://code.google.com/p/matlabcontrol/), however the implementation seems to be limited to numeric data, whereas the data I am dealing with is an array of Strings (Call it a 90 x 8 array of strings just to be safe).
I was able to successfully see an array of numbers in Java using the MatlabController library.
I have also tried using the MATLAB Compiler SDK, however there were multiple internally generated errors when I tried running the code.
I am out of ideas of how I might accomplish the conversion.  Would JSON be an unreasonable option to pursue?
Answer: I think you're doing it the wrong way. Don't send a matlab array to java. Instead construct the java array in matlab, and send that to java. Like how it is done here http://de.mathworks.com/help/matlab/ref/javaarray.html.


Solve too many redirect in android webview

Question: I  created an android WebView and open my website who server with https and authentication redirection anyway this work successfully in all of modern browsers like opera, chrome, Firefox , edge and eth but in android WebView i got 'too many redirect' error
By the way when I set WebView cache mode to none, this error had gone, but i need the cache mode,
Any body can help me?
Comment: can you please add code with url which you are trying to load in webview.
Answer: Use this code to initialize webview and set url, it is work fine with me with all Android versions
@SuppressLint("SetJavaScriptEnabled")
private fun initWebView() {
    webView.settings.javaScriptEnabled = true
    webView.settings.loadsImagesAutomatically = true
    webView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
    webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
}

private fun webViewListener() {
    webView.webViewClient = object : WebViewClient() {
        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
             Log.d(TAG, url)
        }
        override fun onReceivedError(view: WebView, request: WebResourceRequest,
                                     error: WebResourceError) {
            super.onReceivedError(view, request, error)
           //Error load url
        }
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            //Loading url
            view?.loadUrl(url)
            return true
        }
    }
}

Add this line in Manifest File
   <application
    ...
    android:usesCleartextTraffic="true">

You can read more about usesCleartextTraffic


If $2^{2x}+2^{2-x}=15$ then $2^x+2^{-x}=?$

Question: If $2^{2x}+2^{2-x}=15$ then $2^x+2^{-x}=?$
I thought of taking square of $2^x+2^{-x}$ which is $2^{2x}+2^{-2x}+2$, but I couldn't go further than that. Help would be much appreciated.
Comment: Try to solve by assuming $y=2^x$.
Comment: You took the square of the target quantity. In this case, it's better to manipulate the source quantity first, like Soham Saha suggested. By the way, I have solved it without brute-force calculations and it's pretty cool that you don't need to find $x$. Please try it again.
Comment: Maybe introduce variable named for the new quantities, then it will become clearer.
Comment: Thank you all for the suggestions :)
Answer: Let $2^x=y$
First Solution:
$$2^{2x}+2^{2-x}=y^2 + \frac{4}{y}=15$$
$$y^2 + 1 =16 - \frac{4}{y}$$
$$y + \frac{1}{y} =\frac{16}{y} - \frac{4}{y^2}=4\times (15 - y^2) - \frac{4}{y^2}=60 - 4(y^2+\frac{1}{y^2})=60-4[(y+\frac{1}{y})^2-2]=68-4(y+\frac{1}{y})^2$$
$$4(y+\frac{1}{y})^2 + (y + \frac{1}{y}) -68=[4(y + \frac{1}{y})+17]\times [(y + \frac{1}{y})_-4]=0 $$
$y + \frac{1}{y}=2^x+2^{-x}=\frac{-17}{4}$ NA
$y + \frac{1}{y}=2^x+2^{-x}=4$
Second Solution:
$$y^2 + \frac{4}{y}=15, y\neq 0$$
$$y^3-15y+4=(y+4)(y^2-4y+1)=0$$
$$y=-4, y=2\mp\sqrt3$$
$2^x=-4$ NA
$2^x=2 \mp\sqrt3$
$2^x +2^{-x} = 2\mp\sqrt3 + \frac{1}{2\mp\sqrt3} = 4 $
Comment: Yo do not need find the roots. Note that, $$\small {y^2-4y+1=0\implies y+\frac 1y=4}$$
Answer: $2^x = a$
$a^2 + \frac{4}{a} = 15$
$a^3 - 15a = -4$
$a(a^2 - 15) = -4$
$a = -4$
$2^x + 2 ^{-x} = -4 + -\frac{1}{4} = -\frac{17}{4}$

$a^3-15a+4=(a+4)(a^2-4a+1)=0$
$a^2 -4a + 1 = 0 \implies a + \frac{1}{a} = 4 = 2^x + 2^{-x}$
Comment: Note that $2^x > 0$ for every real number $x$.
Comment: Thanks @N.F.Taussig


How to explain negative residual covariance in cross-lagged SEM?

Question: Question in short:
If I see a positive (significant) residual covariance between two endogenous variables in a cross-lagged SEM for the first lag and a negative (significant) residual covariance for the second lag, how can I explain that descriptively to the audience? I am particularly interested in describing why we see such positive and negative residual covariances from the data itself. Could you please suggest?
Details of my scenario:
I have two categorical (binary) endogenous variables emp and SA at three time points, 1, 2, and 5. I have run the following cross-lagged SEM with fixed effects age and sex:
<code>full_clpm1 <- '

# synchronous covariances

SA1 ~~ emp1

SA2 ~~ emp2

SA5 ~~ emp5

# autoregressive + cross-lagged paths

emp1 ~ AGE + sex

SA1 ~ AGE + sex

emp2 ~ AGE + sex + emp1 + SA1

SA2 ~ AGE + sex + emp1 + SA1

emp5 ~ AGE + sex + emp1 + SA1 + emp2 + SA2

SA5 ~ AGE + sex + emp1 + SA1 + emp2 + SA2

'

# fit the model

fit1 <- sem(full_clpm1, data=dp)
summary(fit1)
</code>
I got the following results for the residual covariances and wondering why the first covariance is positive and the second one is negative (both statistically significant):

I want to know what this means and how I can show descriptively why the second time point had negative residual covariance between emp2 and SA2. I already tried separate probit regressions on emp2 and SA2 and found the correlations of the residuals from these two non-simultaneous regression models. But that correlation appears to be positive (and very small). So, could you suggest me a way to show the reason of this negative residual covariance descriptively for the sake of discussion? I am wondering there must be some way of explaining this negative residual covariance descriptively.
Disclaimer: Cross-posted from https://groups.google.com/forum/#!topic/lavaan/4H38vTlUcL4 as suggested there.
Answer: This is not surprising. These covariances are different things. The first covariance is controlling for age and sex, the second is controlling for the t1 measures of the same variables.
It's so uninteresting that I wouldn't even bother to mention it. It might have happened to me. It might not. I'm not sure I would have noticed.
Comment: I'm surprised why such a small partial correlation turns out to be statistically significant. I guess calling this "residual covariance" as "partial correlation" is correct?
Comment: It's a partial covariance (I think), not correlation, so you can't say anything about the size. You can call it a residual covariance or partial covariance.


Induced metric on $S^2$ from pullback of metric on $\mathbb{R}^3$

Question: I'm going over some GR from more of a differential geometry perspective and had a quick question about a simple calculation - my differential geometry background isn't too strong so I apologise if any of the terminology is incorrect, but I'd be grateful for any clarification.
I'm following an example in Appendix A of Sean Carroll's Introduction to GR, where there is a map $\phi:M \to N$, given by
$$ \phi(\theta,\phi) = (\sin\theta \cos \phi , \sin \theta \sin \phi, \cos \phi) ,
$$
and $M=S^2$ is a submanifold of $N =\mathbb{R}^3$ (i.e. the two-sphere embedded in $\mathbb{R}^3$). The coordinates on the manifolds are $x^{\mu} = (\theta,\phi)$ on $M$, and $y^{\alpha} = (x,y,z)$ on $N$. The induced metric on $M$ is just the pullback of the flat-space metric $\phi^*g$, which is given by the formula
$$
(\phi^*g)_{\mu \nu} = \frac{\partial y^{\alpha} }{\partial x^{\mu}} \frac{\partial y^{\beta} }{\partial x^{\nu}} g_{\alpha \beta}.
$$
I understand how to calculate the individual Jacobian matrices of partial derivatives $\frac{\partial y^{\alpha} }{\partial x^{\mu}}$ (e.g. just using $y^1 = \sin\theta \cos \phi $, $y^2 = \sin \theta \sin \phi$ and $y^3 = \cos \phi$ as defined by $\phi$), however I was confused as to how to treat the full expression above.
The Jacobian matrices are $2 \times 3$ matrices, so the second has to be transposed to be a $3 \times 2$ matrix in order to give the required $2 \times 2$ metric $g_{\mu \nu}$. My question is, in the pullback equation above, how does the metric $g_{\alpha \beta}$ act on the Jacobian $\frac{\partial y^{\beta} }{\partial x^{\mu}}$, and how should I be writing this down? I can see that $y^{\beta}$ should be replaced with $y^{\alpha}$, but should any indices be lowered, and how should I interpret the metric tensor transposing the Jacobian matrix?

Edit - Ted Shriffin's comments are correct, the last component of the map should be $\cos \theta$ not $\cos \phi$, and all my matrices should be transposed.
Comment: Be careful. You have a typo in your definition of the mapping — and please don't use $\phi$ for both the mapping and one of the coordinates :) Actually, the mapping should be written as a *vector* (not a row), and the Jacobian will be $3\times 2$.
Comment: The last coordinate needs to be $\cos\theta$. The mapping goes from $\Bbb R^2$ to $\Bbb R^3$, so the derivative matrix is $3\times 2$. This is enough sloppiness for me. I would find another text.
Comment: I agree having $\phi$ as the map and in the coords is a bit confusing but I was copying exactly from the Carroll textbook incase readers were familiar with it. Could you point out the typo?
Comment: As for the Jacobian $\frac{\partial y^{\alpha} }{\partial x^{\mu}}$, it is written explicitly (in the textbook) as a $2 \times 3$ matrix, so maybe I am confused as to what you mean?
Comment: @Eletie Hi, I am studying your question now. Cam you please tell me what is $\frac{\partial y^{\beta} }{\partial x^{\mu}}$ explicitly? Moreover I want to know what is $y^{\beta}$ and $x^{\mu}$ in this case?
Answer: Seeing as I'm getting new comments on this old question I thought I'd post the answer myself. Thanks to Ted Shifrin's help in the comments and also pointing out the typo in the mapping: the map $\Phi:M \to N$ should of course be
$$ \Phi(\stackrel{x^{\mu} \ \rm{coords}}{\theta \, , \, \phi})^T = (\stackrel{y^\alpha \ \rm{coords}}{\sin\theta \cos \phi , \sin \theta \sin \phi, \cos \theta})^T \ ,
$$
where the transpose makes clear these are vectors not rows. I've also made clear the $x^{\mu}$ and $y^{\alpha}$ coordinates on $S^2$ and $\mathbb{R}^3$ respectively.
My mistake came from being unfamiliar with using matrix notation with tensors (it's been a while since I've done linear algebra). The final matrix of course must've been $2 \times 2$ because the indices $\alpha \beta$ were summed over whilst $\mu = \{0,1\}$. Similarly, all the expressions I had should have been transposed, but in the textbook they weren't written this way, probably to save space. e.g. the Jacobian was written as a $2 \times 3$ matrix but should have been $3 \times 2$,
$$
\frac{\partial y^\alpha}{\partial x^{\mu}} =
\begin{pmatrix}
\frac{\partial y^1}{\partial x^1} & \frac{\partial y^1}{\partial x^2}  \\
\frac{\partial y^2}{\partial x^1} & \frac{\partial y^2}{\partial x^2}   \\
\frac{\partial y^3}{\partial x^1} & \frac{\partial y^3}{\partial x^2}
\end{pmatrix}
=
\begin{pmatrix}
\cos \theta \cos \phi & -\sin \theta \sin \phi \\
\cos \theta \sin \phi & \sin \theta \cos \phi  \\
-\sin \theta & 0
\end{pmatrix} \ .
$$
Then the induced metric can be written as
$$ \begin{align}
(\Phi^* g)_{\mu \nu} &= \frac{\partial y^{\alpha}}{\partial x^{\mu}}  \frac{\partial y^{\beta}}{\partial x^{\nu}} g_{\alpha \beta} \\
&= \frac{\partial y^{\alpha}}{\partial x^{\mu}}  \frac{\partial y^{\beta}}{\partial x^{\nu}}
\delta_{\alpha \beta} \ ,
\end{align}
$$
with the Kronecker delta from the flat Euclidean metric on $\mathbb{R}^3$. Here we don't just use matrix multiplication as I originally thought (this wouldn't make sense anyway). We can find the components of the induced metric by summing over the repeated index,
$$
(\Phi^* g)_{\mu \nu} = \sum_{\alpha = 1}^3 \frac{\partial y^{\alpha}}{\partial x^{\mu}}  \frac{\partial y^{\alpha}}{\partial x^{\nu}} .
$$
E.g. the $\mu \nu = 0 0$ component is just $$
(\cos \theta \cos \phi)^2 + (\cos \theta \sin \phi)^2 + (- \sin \theta)^2 = 1 \ ,
$$
and repeat for the others.
One then thankfully finds the induced metric to be
$$
g_{\mu \nu}(x) = \begin{pmatrix}
1 & 0 \\
0 & \sin^2 \theta \\
\end{pmatrix} \ .
$$
Comment: This is very helpful.


How to implement PCA?

Question: Forgive me if this a too much of a beginner question but I am  PCA algorithm on a dataset with having a hard time understanding the implemenation of PCA on a dataset with 18 features. These are the questions I have regarding this:

PCA normally reduce the dimensionality from n to k. In my case, the number of features i.e. n = 18. How can I determine to what level I reduce my dimensions i.e. k value ?
I used the below code to do PCA (got this from one of the tutorials)
from sklearn.decomposition import PCA
pca = PCA(n_components=3)
print norm_features.shape
pca.fit(norm_features)
print pca.components_

It returns a total of three vectors. Should I consider that as my reduced dimension ?

Every example that I see on the internet uses their own dataset and one example is completely different from another and I am unable to generalize on this concept. Any pointers to some resources ?
Answer: PCA itself is not a procedure for choosing the number of principal components. It is a procedure for calculating the values of the principal components. Choosing how many of these principal components to keep is up to you. Your example code produces 3 of them because you asked for n_components=3 in the call to PCA.
There are a variety of philosophies on how to choose the number of principal components to keep. This topic should be covered in any introductory text that also discusses PCA, such as:
Hastie, T., Tibshirani, R., & Friedman, J. H. (2009). The elements of statistical learning: Data mining, inference, and prediction (2nd ed.). New York, NY: Springer. Retrieved from http://www-stat.stanford.edu/~tibs/ElemStatLearn
See also: Choosing number of principal components to retain
Comment: Ok I understand that part and also the fact the output is a vector that minimizes the projection error on to that vector. How do I go on using this vector in building my model ?
Comment: @karun_r You don't get just one vector; each component is a vector. As for what to do with the extracted components: I don't know; why did you do PCA in the first place?
Comment: Yes I got a total of three vectors since I gave provided n_components = 3 when I initialized the pca variable. I am using PCA to reduce the dimensions of my feature data as there are a total of 18 features. As per Andrew Ng's course and other online resources, I was under the assumption that I should be performing PCA after mean normalization to get my data in order before building a model. Is it not a correct approach ? I am actually using this in my attempt at my first Kaggle problem (King County Housing)
Comment: @karun_r It's not incorrect to use PCA, but it's not mandatory either. There are lots of different ways in which PCA is incorporated into larger analyses, and I couldn't tell you whether PCA makes sense for your situation or how you should use it without knowing a lot more about the problem, the analytic strategy you're trying to pursue, what you hope to accomplish with PCA in particular, etc. You may have been lead to believe that data analysis is a lot simpler and more mechanical than it really is.
Comment: Thanks for the explanation. Actually I have just started learning about data analysis and I think this kaggle dataset was the first dataset on which I got my hands dirty. I hope I will learn as I move forward using the resources online. Thanks again for providing another viewpoint.
Comment: Do you recommend any books for proper learning of statistical analysis ?
Answer: Setting the n_components value to a fixed number might not be the best way to reduce the dimensionality of your data if you don't already have a good guess what this number should be. If you set n_components to a value between 0.0 and 1.0 (See documentation) it will choose the number of principle components that represents 'n_components' of the variance in your data. For example, setting 0.8 would choose enough components to represent 80% of the data and the remaining 20% would get dropped, hopefully mostly the noise. You can all look at the explained_variance_ attribute to see how much of the total variance is represented by each component.

How to implement PCA?