Proving $\frac{1}{e}\cosh(2x)=\sum_{n=0,1,2,...}^\infty\frac{1}{(2n)!}H_{2n}(x)$, where $H_{2n}(x)$ is the even order Hermite polynomial

Question:
How can we prove the following relation $$\frac{1}{e}\cosh(2x)=\sum_{n=0, 1, 2, ...}^\infty\frac{1}{(2n)!}H_{2n}(x)$$ where the $H_{2n}(x)$ is the even order Hermite polynomial?

I didn't get any clue by doing $$\frac{1}{e}\left(\frac{e^{2x}+e^{-2x}}{2}\right)=\sum_{n=0, 1, 2, ...}^\infty\frac{1}{(2n)!}H_{2n}(x)$$Thanks beforehand.
Comment: This is an interesting identity. Where did you find it?
Comment: @K.defaoite My teacher told me to prove the relation, can you help me with this?
Comment: I will give it some thought. If I find a solution I will not post it in its entirety, but I will give you some hints to lead you to the solution on your own.
Comment: @K.defaoite Thank you so much.
Comment: that is a direct consequence of [the generating function](https://en.wikipedia.org/wiki/Hermite_polynomials#Generating_function) for H. polynomials
Comment: @G Cab Good observation, but I think it flows more easily from the approach mentioned in my answer.
Comment: @CuriousMind Have you made any progress?
Comment: @K.defaoite Yes I have solved it but in some other way, you can see my way in my answer, I have answered my own question as I got the solution, but thanks for helping me, I will do that by your method now. I didn't know that $\cosh(2x)$ and $\sinh(2x)$ satisfy the ODE $y''(x)=4 y(x)$. Your method seems interesting.
Answer: Here's a hint: $\cosh(2x)$ and $\sinh(2x)$ satisfy the ODE $y''(x)=4 y(x)$. Use the recurrence relation $H_{m}'(x)=2mH_{m-1}(x)$ and differentiate the series. If the series satisfies the same ODE, it is a linear multiple of $\sinh(2x)$ or $\cosh(2x)$. It is easy to show that it is indeed proportional to $\cosh(2x)$ using a simple parity argument. Then, all that is left is to show this proportionality constant is $1/e$. If you're still struggling after this hint, I'll add more. But give it a try first.
Answer: Answering my own question.

We can proceed by putting $t=1$ in the known equation $$e^{2tx-t^2}=\sum_{n=1}^\infty\frac{H_n(x).t^n}{n!}$$ we get $$e^{2x-1}=\sum_{n=1}^\infty\frac{H_n(x)}{n!}$$ and $$e^{2x-1}+e^{-2x-1}=\sum_{n=1}^\infty\frac{H_n(x)}{n!}+\sum_{n=1}^\infty\frac{H_n(x)}{n!}(-1)^n$$ $$=2\sum_{n=1}^\infty\frac{H_{2n}(x)}{(2n)!}$$as odd terms will be cancelled, $$\implies \frac{1}{2}\left(\frac{e^{2x}+e^{-2x}}{e}\right)=\sum_{n=1}^\infty\frac{H_{2n}(x)}{(2n)!}$$ So ultimately we can get, $$\frac{1}{e}\cosh(2x)\:=\sum_{n=0, 1, 2, ...}^\infty\frac{1}{(2n)!}H_{2n}(x)$$So we can prove it in this way also.
Comment: I considered the generating function approach but had a feeling it was going to get messy. Adding the $e^{-2x-1}$ is a clever trick I had completely missed. Nice solution.
Comment: Thanks, and I will try it using generating function
Comment: @K.defaoite Can you help me in this question? https://math.stackexchange.com/q/3873810/777834


PiTFT "Click" event X.org buildroot

Question: I have been busy with the PiTFT and added the following wiki on github: https://github.com/Junky2008/Buildroot_PiTFT.
I still have a problem though. As in the wiki, the screen, touch and X.org server work. I have calibrated the touchscreen and i can move the mousepointer in X. What doesn't work is a "click" I can only move the mouse but not click any items.
Is there a driver I should install to make it work?
Answer: OK, I fixed it! apparently I was using an old version of the STMPE kernel module, I will set everything in my wiki!
https://github.com/Junky2008/Buildroot_PiTFT
I will mark this answer as "the answer" when I updated my wiki

PiTFT "Click" event X.org buildroot


Print Manager.msc missing in Windows 2003 Server R2

Question: There is an msc that I'd really like to use: printmanager.msc. Specifically I want to be able to force certain OUs to use specific printers without having to push the entire directory.
Now I've inherited a Win2k3 domain with a pdc and two secondaries, all patched and current. Unfortunately the printmanager and some other tools weren't installed originally, and I cannot for the life of me figure out how to install them now (If you tell me to do this I am going to mock you without mercy). Can't find a download link for a version that will work, and I can't figure out how to get the older version from the install disks to work either.
Does anyone have any suggestions? I'm beginning to think I'm going to have to wipe one of the secondaries, and do a clean install.
Edit: Since this has turned into a popular question, I'll add the answer: I had to upgrade everything to RC2 in order to install the msc. It was a problem due to my original disks being well below the patched level of my system, so I ended up making an upgraded install disk, and working from there.
Answer: On a Windows 2003 R2 system, you can install Print Management from the Windows Components section in Add/Remove Programs.
If the system is not R2, you'll have to install the R2 components first (from the second CD-ROM).
Comment: Tried it, doesn't work. I don't need the regular "print" stuff, I need the schmancy msc that allows you to integrate your print services better with the AD.
Comment: This is *quite* strange, that console should be installed when you add that component.
Comment: As for using the 2nd CD, that's the root of the problem. At this point in patching, it won't let me pull anything off the 2nd CD.
Comment: Yea, I haven't been able to find a damn thing about it online. I can see the fricking file on the 2nd disk... I've added and removed print services, I've added and removed the print server role...
Comment: Was the AD schema extended for R2? Are your domain controllers R2?
Comment: @massimo: No, I'm not 100% certain...They were *supposed* to be, but I've dug and I can't find any evidence that they were actually updated. That'd pretty much explain everything wouldn't it?
Comment: If you have the second CD-ROM, you can safely update any Windows 2003 SP2 server you have; just run the R2 installer. You can also update the AD schema using the ADPREP tool in that same CD-ROM. The upgrade is totally safe, R2 introduced new features to Windows Server 2003 but you have to manually install and use them, nothing is enabled automatically after you upgrade a server and/or the AD schema to R2.
Comment: @massimo: Alas, my servers are SP2, and my CDs are SP1. Try to run anything, and it tells me the patches are out of whack. I'll have to see if I can make or steal some RC2 SP2 disks.
Answer: Perhaps this is what you're looking for?  (pmcmgmt.exe)
http://www.microsoft.com/downloads/details.aspx?familyid=9BFB44F5-232A-4FB5-BC14-45BFD81B7AC1&displaylang=en
Comment: Nope. 3 out of 4 of those throw the "Microsoft installer detects the wrong version of Windows" error, and the 4th (idmu.exe) one is some Unix integration I have no use for.

A better version of the tools is here: http://www.microsoft.com/downloads/details.aspx?familyid=86B71A4F-4122-44AF-BE79-3F101E533D95&displaylang=en That one still does nothing for me.
Comment: Is this server 2003 R2 x64?

http://www.microsoft.com/downloads/details.aspx?familyid=8F7DF3A5-E738-44B4-91EB-4907511F87C6&displaylang=en
Comment: Are you *SURE* the system is R2?
Answer: I think that was part of the Admin Tools Pack SP1 or R2 (it's been years, so forgive me if I'm wrong) (scroll to bottom of that linked page for the downloads).
Answer: Copy the folder and its contents "PMCSnap" to:
C:\WINDOWS\PMCSnap
Register these dlls:
findnetprinters.dll
pmcsnap.dll
ppcsnap.dll
puiobj.dll
Edit the "PATH" to include the folder "C:\WINDOWS\PMCSnap"
All Done!
Now you can use printmanagement from Administrative Tools or from run command.
P.S. I upload the folder PMCSnap to rapidshare
https://rapidshare.com/files/126883871/PMCSnap.rar


Erro ao salvar imagem JPEG no banco como string (base64)

Question: Estou desenvolvendo uma aplicativo que tem um formulário onde o usuário pode anexar uma foto junto ao form. Porem estou com dificuldade em implementar isto. No meu APK eu ja capturo a imagem, converto em base 64 e envio via Rest para meu serviço.
public void tirarFoto(View view){
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    startActivityForResult(intent, 0);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if(data != null){
        Bundle bundle = data.getExtras();
        if(bundle != null){
            Bitmap img = (Bitmap) bundle.get("data");
            Toast toast = Toast.makeText(getApplicationContext(), "Foto anexada", Toast.LENGTH_LONG);
            toast.show();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            img.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            foto = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);

        }
    }
}
public void registerForms() {

    final String address = frua.getText().toString().trim();
    final String district = fbairro.getText().toString().trim();
    final String city = fcidade.getText().toString().trim();
    final String email = femail.getText().toString().trim();
    final String complement = fcompl.getText().toString().trim();
    final String state = festado.getText().toString().trim();
    final String note = fobs.getText().toString().trim();
    final String countries = fpais.getText().toString().trim();
    progressDialog = ProgressDialog.show(DenunciaActivity.this, "Aguarde um momento", "Enviando...", true, false);

    StringRequest stringRequest = new StringRequest( Request.Method.POST, REGISTER_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            if (response.contains("Erro")) {
                progressDialog.dismiss();
                Toast.makeText( DenunciaActivity.this, "Erro ao enviar", Toast.LENGTH_LONG ).show();

            } else {
                progressDialog.dismiss();
                Intent intent = new Intent(DenunciaActivity.this, MainActivity.class);
                Toast.makeText( DenunciaActivity.this, "Enviado com sucesso!", Toast.LENGTH_LONG ).show();
                startActivity(intent);
            }

        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressDialog.dismiss();
                    Toast.makeText( DenunciaActivity.this, error.toString(), Toast.LENGTH_LONG ).show();
                    Log.i( TAG, "Lat: " + error );
                }
            } ) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> map = new HashMap<String, String>();
            map.put( KEY_USERNAME, name );
            map.put( KEY_DATE, dataFormatada );
            map.put( KEY_STATE, state );
            map.put( KEY_CITY, city );
            map.put( KEY_DISTRICT, district );
            map.put( KEY_ADDRESS, address );
            map.put( KEY_EMAIL, email );
            map.put( KEY_COMPLEMENT, complement );
            map.put( KEY_COUNTRIE, countries );
            map.put( KEY_LAT, String.valueOf( latitude ) );
            map.put( KEY_LONG, String.valueOf( longitude ) );
            map.put( KEY_NOTE, note );
            map.put( KEY_STATUS, "ATIVO" );
            map.put( KEY_IMAGE, foto );
            Log.i( TAG, "Lat: " + longitude +" "+latitude);
            return map;
        }

    };

    RequestQueue requestQueue = Volley.newRequestQueue( this );
    requestQueue.add( stringRequest );
}

No meu serviço esta assim:
public class Services extends Controller {
public static void denuncia(@Valid String nome, String data, String rua, String bairro, String complemento, String cidade, String estado, String pais, String observacao, String email, String latitude, String longitude, Status status, String foto) {
    if (validation.hasErrors()) {
        String mensagem = "Erro ao cadastrar";
        JsonObject j = new JsonObject();
        j.addProperty("Erro", 404);
        j.addProperty("msg", mensagem);
        renderJSON(j);
    } else {
        String msgsucess = "Cadastrado com sucesso!";
        Denuncia denuncia = new Denuncia();
        denuncia.nome = nome;
        denuncia.data = data;
        denuncia.rua = rua;
        denuncia.bairro = bairro;
        denuncia.complemento = complemento;
        denuncia.cidade = cidade;
        denuncia.estado = estado;
        denuncia.pais = pais;
        denuncia.observacao = observacao;
        denuncia.email = email;
        denuncia.latitude = latitude;
        denuncia.longitude = longitude;
        denuncia.status = status;
        denuncia.foto = foto;
        denuncia.save();
        JsonObject j = new JsonObject();
        j.addProperty("Success", 200);
        j.addProperty("msg", msgsucess);
        renderJSON(j);
    }
}

E o meu Model esta:
@Entity
public class Denuncia extends Model{

@Required
public String nome;
@Required
public String rua;
@Required
public String bairro;
@Required
public String complemento;
@Required
public String data;
@Required
public String cidade;
@Required
public String estado;
@Required
public String pais;
@Required
public String observacao;
@Required
@Email
public String email;
public String foto;
public String latitude;
public String longitude;

@Enumerated(EnumType.STRING)
public Status status;
@Enumerated(EnumType.STRING)
public Status statusMsg;
public Denuncia() {
    status = Status.ATIVO;
    statusMsg = Status.NAO_LIDA;
}

O erro que estou passando é referente ao tamanho da string que estou recebendo no meu banco, é maior do que o suportado, conforme a saida:
Caused by: org.h2.jdbc.JdbcSQLException: Value too long for column "FOTO VARCHAR(255)": "STRINGDECODE('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB... (62229)"; SQL statement:
insert into Denuncia (id, bairro, cidade, complemento, data, email, estado, foto, latitude, longitude, nome, observacao, pais, rua, status, statusMsg) values (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [22001-193]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.table.Column.validateConvertUpdateSequence(Column.java:335)
at org.h2.table.Table.validateConvertUpdateSequence(Table.java:784)
at org.h2.command.dml.Insert.insertRows(Insert.java:151)
at org.h2.command.dml.Insert.update(Insert.java:114)
at org.h2.command.CommandContainer.update(CommandContainer.java:98)
at org.h2.command.Command.executeUpdate(Command.java:258)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:160)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:146)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:186)
... 30 more

Alguem me ajudar a achar uma saída para o problema?
Answer: Você definiu a coluna de imagens como VARCHAR(255).
Em geral o tipo varchar armazena de um a dois bytes por caractere (supondo UTF-8).
Isso significa que qualquer imagem que você tentar guardar com mais de 123 bytes vai dar esse erro. Sim, eu disse bytes.
Salvei a sua foto de avatar aqui na minha máquina pra ver o tamanho. Ela ocupa 8192 bytes em disco.
Utilize um tamanho de coluna maior. E se for salvar arquivos, facilite sua vida - tente um formato binário (blob ou algo do tipo).
Comment: Como poderia fazer isso usando esse blob? pq essa tabela terá varias imagens, mas como nunca fiz isso (upload de imagem para banco) nao sei como implementar e qual a melhor maneira
Comment: @CarlosDiego sinto muito, eu sou um zero à esquerda em Java :( não conheço a API.
Comment: A melhor maneira é salvar as imagens no disco e gravar o caminho no banco de dados. Salvar arquivos enormes no banco de dados não é recomendado.
Comment: @ValdeirPsr discordo com todas as minhas forças. Os tipos binários foram criados para isso. Se você não armazenar os arquivos na base, você correrá o sério risco de ter inconsistências com o tempo. E seus backups da base não incluirão os arquivos, logo qualquer restauração em outra máquina será inválida sem um outro backup mais complexo e externo ao banco.
Comment: @Renan apesar dos tipos binários serem criados para isso, o uso de memória será bem maior. Visto que o projeto dele deverá utilizar bastante buscas no DB, eu particularmente (não sou DBA), optaria por outra forma. Claro que ele pode utilizar o banco de dados como uma forma mais segura e confiável (é inegável esse pró do banco de dados), mas ele terá que optar por utilizar um cache para evitar o consumo desenfreado de RAM e provavelmente será no disco rígido. E não pode esquecer: *"Com grandes banco de dados, vem grandes responsabilidades."*
Comment: Deixo aqui alguns links do porquê considero uma solução melhor (principalmente se tiver trabalhando sozinho e não tiver um grande conhecimento em DBA). 1. https://habiletechnologies.com/blog/better-saving-files-database-file-system/; 2. https://dev.mysql.com/doc/refman/5.5/en/optimize-blob.html; 3. https://docs.microsoft.com/en-us/sql/relational-databases/blob/filestream-sql-server e 4. https://softwareengineering.stackexchange.com/a/150787


Make jenkins spawn agents on gke in different node pools

Question: I have a jenkins and most jobs do some ansible work and need 300mb of ram tops with 50m cpu, but I'v got few massive integration testing jobs that take 14000m cpu(14vcpus) or more, i know there is there a way to have 2 node pools (one with small instances 4gb, and one with the massive 30vcpu machines), and if I had 2 microserwices I could make them use NodeSelector, but jenkins is one microserwice, can I make it somehow spawn different job agents in different node pools?
Answer: You should be able to spawn Jenkins agents using another node pool, as NodeSelector is one of the parameter that could be defined.
Based on kubernetes-plugin GitHub Repo, NodeSelector can be defined as anything you want to match the second node pool.
Example could be found on sample file of the repo:
podTemplate(yaml: '''
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: jnlp
    image: jenkins/jnlp-agent:latest-windows
  nodeSelector:
    beta.kubernetes.io/os: windows
'''
) {
    node(POD_LABEL) {
        bat 'dir'
        powershell 'Get-ChildItem Env: | Sort Name'
    }
}


prove $(A \times B)^c = (A^c\times U)\cup(U\times B^c)$

Question: got stuck proving that $(A \times B)^c = (A^c\times U)\cup(U\times B^c)$.
would appreciate your help, this is what I got so far:
Comment: Please do not post large numbers of similar questions - you have asked seven questions that really do not differ by much. Instead, please see if the asnwers to one or two questions allow you to solve the other questions on your own.
Answer: Let $(x,y)$ be an element of the left-hand side. Then $(x,y)\not\in A\times B$, and therefore $x\not \in A$, or $y\not\in B$  (or both).
Suppose $x\not\in A$. Then $x\in A^c$. It follows that $(x,y)\in A^c\times U$, and therefore $(x,y)$ is an element of the right-hand side.
A similar argument works if $y\not\in B$.
We leave it to you to show that every element of the right-hand side is an element of the left-hand side.
Comment: Nicolas can I tell that if $(a,b)\in(A^c \times B^c)$ then it's also in $(A^c \times B^c) \cup (U \times U)$ ?
Comment: Certainly, that is true. By the way, the convention here is that $U$ is some sort of "universal" set that contains the elements of $A$, of $B$, and possibly a lot more.
Comment: is it legal that I decided that if $(a,b)\in(A \times B)^c$ then $a\not\in A \land b\not\in B$. or I have to take also the possibilities when one of the doesn't happen
Comment: Not quite. If you look at my answer, you can see thar one conclude that $a\not\in A$ **or** $b\not\in B$.  In general one cannot conclude **and**.
Comment: what do you mean by 'one cannot conclude and'?
Comment: @Ami $(a,b)\in(A\times B)^c\iff (a\not\in A\ \lor\ b\not\in B)$.
Comment: @Ami: I mean that sometimes we have $(a,b)\not\in A\times B$, and $a\in A$ but $b\not\in B$. Or the other way.
Answer: Ok, so this is what I got. would appreciate your attention if I made any mistakes.. thanks again.
Answer: $\begin{align}(A\times B)^c & = ((A\times \mathscr U)\cap (\mathscr U\times B))^c
\\ & = (A\times \mathscr U)^c\cup (\mathscr U\times B)^c
\\ & = (A^c\times \mathscr U)\cup (\mathscr U\times B^c)
\end{align}$
The first step, $(A\times B)= (A\times \mathscr U)\cap (\mathscr U\times B)$ is equivalent to $$\forall x\,\forall y\;\Big(\big(x\in A\,\wedge\, y\in B\big) \,\leftrightarrow\,\big( x\in A\cap \mathscr U\,\wedge\, y\in \mathscr U\cap B\big)\Big)$$
Which is fairly incontrovertable.
The second step is just deMorgan's Law for Set Complements
The last step hinges on $(A\times \mathscr U)^c = (A^c\times \mathscr U)$, and the symmetric claim.
This is equivalent to the claim that:  $\forall x\,\forall y\;\Big((x,y)\notin A\times \mathscr U \leftrightarrow (x,y)\in A^c\times \mathscr U\Big)$
Clearly this is the case, because is distills down to $\forall x\;(x\notin A \leftrightarrow x\in A^c)$ which is true by definition of set complement.


Minimizing an objective function with input variables from a correlated error term

Question: I've been reading into how to minimize objective functions and I am curious about the following,
I have a model $y=X \beta +\epsilon$ where $E[\epsilon|X]=0$ and $Var[\epsilon|X]=\Sigma$ where $\Sigma$ is not diagonal and is a covariance matrix. $\beta$ can be estimated by least squares to get,
$$\hat{\beta}=(X^T \Sigma^{-1}X)^{-1}X^T\Sigma^{-1}y$$.
So this comes from the minimization of $(y-X\beta)^T \Sigma^{-1}(y-X\beta)$. Now if I assume that $\epsilon \sim AR(2)$ then $Var[\epsilon|X]=\Sigma=Cov(AR(2))$ making it a covariance matrix with respect to AR(2). So my question is, is there any way to decompose $\Sigma$ in the objective function such that it can be written in the form of the AR(2) coefficients and its variance so that the objective function can be minimized with respect to variance, and AR(2) coefficients if $y, \beta$, and $X$ are known.
Thank you
Comment: Are you only interested in a "decomposition" of $\Sigma$, if so, what exactly do you mean by "decomposition"? Or do you want to understand the complete procedure of this optimization problem? Or do you just want to know an implementation you can use?
Comment: Hi Frank,
I actually understand most of the procedures of this optimization, however, I am curious in knowing if anything can be done with $\Sigma$, either rewritten in a different way say through QR decomposition or if it is legitimate to rewrite it as $\sigma^2_w* \Sigma$ since originally $\Sigma$ is calculated using the auto-covariance function which relies on $\sigma^2_w, \phi_1, \phi_2$ where $\sigma^2_w$ is just the variance of white noise, and $\phi_1, \phi_2$ are the coefficients values of the AR(2) model.
Answer: You can do linear regression for $y = X\beta + \epsilon$ using a covariance matrix for $\epsilon$ that belongs to an AR(2) model, or to any ARMA(p, q) model for that matter.
You can e.g. use the gls() function from the nlme R-package. It provides for various types of correlations, among them ARMA correlation (look for corARMA here). There, you provide the coefficients of the ARMA model which are then used by gls() to create the appropriate covariance matrix and execute the optimization.
Comment: THanks, Frank, I'll have to check the ```gls()``` out as I haven't had to use it yet.


Como contar as pessoas por idade

Question: Eu tenho
class Person(TimeStampedModel, Address):
    name = models.CharField(_('nome'), max_length=100)
    birthday = models.DateField(_('data de nascimento'))

e a função
import datetime
from datetime import date

'''
http://keyes.ie/calculate-age-with-python/
'''

def age(when, on=None):
    if on is None:
        on = datetime.date.today()
    was_earlier = (on.month, on.day) < (when.month, when.day)
    return on.year - when.year - (was_earlier)

age(date(2000, 1, 1))

Como contar as pessoas por faixa de idade?
age quant
20-25   89
25-30   100
30-35   90
35-40   102

Eu sei que tenho que usar annottate e count, mas nao sei por onde começar.
Answer: Utilizando annotante eu não consegui extrair o ano e o mês utilizando F('birthday') para realizar o cálculo.
Se eu quisesse pegar a faixa seria algo mais ou menos assim:
model
class Person(TimeStampedModel, Address):
    name = models.CharField(_('nome'), max_length=100)
    birthday = models.DateField(_('data de nascimento'))

    def idade(self):
        hoje = date.today()
        return hoje.year - self.birthday.year - ((hoje.month, hoje.day) < (self.birthday.month, self.birthday.day))

view
faixa = {'vinte_vintecinco': 0, 'vintecinco_trinta': 0, ...}
pessoa = Person.objects.filter(birthday__isnull=False)
for p in pessoas:
    if 20 >= p.idade <= 25:
        faixa['vinte_vintecinco'] += 1
    # ...

Como contar as pessoas por idade


Entropy of random variables taking real numbers

Question: I need to calculate the entropy of 100 instances of 5 sensor signals in python. The sensor values take real numbers. After doing some literature search, I suppose I need to compute joint differential entropy. For this, I should estimate a multivariate probability density function defining my sensor values. Since I do not have a sound knowledge on information theory, I cannot validate my thoughts. Please guide me how to achieve this.
P.S. I am looking for theoretical suggestions and not related to coding.
Comment: multivariate joint PDF on 100 data points will by garbage
Comment: @Aksakal lol. Any suggestions on how to tackle this problem? any alternatives?
Answer: This is how it's been with a lot of data and sensors. "Entropy Based Anomaly Detection Applied to Space Shuttle Main Engines." A. Agogino and K. Tumer. In Proceedings of the IEEE Aerospace Conference, Big Sky, MO, March 2006.
See Eq.2:
$$H(S)=\sum_{i=1}^n \frac {n_i} n\log_2\frac{n_i} n$$
They bin the data, and don't need to estimate the multivariate probability. In their case with 147 sesnors and megabytes of data it would be a garbage joint density, as it would be in your with 5 sensors but only 100 observations.
You could say that they're using some form of a empirical distribution function. You could try Kernel density as others do, but with 100 observations it'll still be garbage :)
Comment: The paper certainly put me on the right track. I should be looking for entropy estimators like nearest neighbor based, etc. I need a clarification on this paper though. If I have understood it well, the entropy is min when all the sensor values fall under similar bins(high or low valued). This might not be always true. For me one sensor should be high and the other low in a 'normal' or 'predictable' scenario. Is this assumption valid? or have I misunderstood it?
Comment: I'm not sure I understood your question. Take a look at [my answer](https://stats.stackexchange.com/a/194615/36041) to an earlier question: there's more uncertainty in a uniform *distribution* than in a bell shaped one. Pay attention to signs in Shannon's definition and Agogino's.
Comment: I have understood the concept of entropy. I am confused with the binning method in the paper. The author's interpretation of low entropy indeed suggests that most of the values at one timestamp are at similar levels of discreteness(i.e. not uniformly distributed). Doesn't it also imply that the signals are all high or all low to obtain low entropy? Isn't it a hard constraint on the sensor values?
Comment: The bin sizes are equal, which is important. So, the uniform distribution will produce the highest Shannon entropy (most uncertainty), but they dropped the negative sign from usual equation. is this the confusion?


Vue CLI - compile CSS files individually from directory of .scss files

Question: I am using Vue CLI which abstracts away much of the Webpack configuration for running and building the application. This comes with some benefits, but I am at a loss as to how to create specific rules for a directory of .scss files.
I would like these files to not be extracted into a single .css file on build, but to be individually compiled into a themes directory (./dist/themes).
I have tried to create a rule in vue.config.js to recognise the directory but it does not work:
module.exports = {
  runtimeCompiler: true,
  configureWebpack: config => {
    config.module.rules.push(
      {
        test: /\.md$/,
        use: 'raw-loader'
      },
      {
        test: /\.ya?ml$/,
        type: 'json', // Required by Webpack v4
        use: 'yaml-loader'
      }
    )
  },
  module: {
    rules: [
      {
        test: /\.scss$/i,
        loader: 'css-loader',
        options: {
          import: (url, media, resourcePath) => {

            // Find .scss files in src/assets/themes
            if (url.includes('./src/assets/themes')) {

            }

          },
        },
      },
    ],
  },
}

Thanks
Answer: I think your format in vue.config.js is incorrect. This is how you pass scss options to the loader:
    css: {
        loaderOptions: {
            scss: {
                   // options
            }
        }
    }

I'm not sure how you configure the output to be how you want it but this should help you. To see what vue.config.js is translated to in terms of webpack you can run vue inspect
Comment: Thanks, I think I'll reformulate the question because I don't know how to do this with a standard Webpack configuration.


Solve vectorial equations

Question: I'm trying to figure out a passage for reducing a vectorial equations ! for doing this somebody told me to use a program of symbolic calculation (matlab,maple, mathematical .. or python as well .. ) I never using symbolic calculation .. but i'm confiding in your knowledge for figure out how to solve my problem !
here the equation :
$$ \mathbf{v}_l + \mathbf{A} \times \mathbf{v}_l = \mathbf{B} $$
where
$$ \mathbf{A} = \frac{D}{D_0}\mathbf{s'}, $$
$$ \mathbf{B} = \frac{\rho_s k}{D_0}(\mathbf{V_s+v_s}) -\frac{D_t}{D_0}\mathbf{v_n}+\frac{D}{D_0}\mathbf{s'}\times \mathbf{v_n}+\frac{\chi}{D_0}\mathbf{s'} $$
where $\chi $ is a generic constant.
The solution of the first equations is:
$$\mathbf{v}_l = \frac{1}{(1+A^2)}[\mathbf{B}-\mathbf{A}\times\mathbf{B} + (\mathbf{A} \cdot \mathbf{B}   ) \mathbf{A} ] $$
how this solution comes from ??? I found it in the paper paper (eq 14)
I'm wait for your precious Help !! thanks in advance
I add the pdf on the web
Comment: paper is behind a paywall. (or at least it is to me) so would it be possible to get a bit more information?
Answer: Hint:
I suppose that your vectors are in $3$D space. In tis case , if $\mathbf A=(A_x,A_y,A_z)^T$, we can represent the cross product as a matrix operation as:
$$
\mathbf A \times \mathbf v_l=\mathbf A_{[\times]}\mathbf v_l=\begin{pmatrix}
0&-A_z&A_y\\
A_z&0&-A_x\\
-A_y&A_x&0
\end{pmatrix} \mathbf v_l
$$
So your equation becomes:
$$
\left(\mathbf I+ \mathbf A_{[\times]}\right)\mathbf v_l=\mathbf B
$$
and the solution is:
$$
\mathbf v_l=\left(\mathbf I+ \mathbf A_{[\times]}\right)^{-1} \mathbf B
$$
If you calculate  the inverse matrix
$$
\left(\mathbf I+ \mathbf A_{[\times]}\right)^{-1}=
\begin{pmatrix}
1&-A_z&A_y\\
A_z&1&-A_x\\
-A_y&A_x&1
\end{pmatrix}^{-1}
$$
I think that you can find the result.

Using WolframAlpha I found:
$$
\begin{pmatrix}
1&-A_z&A_y\\
A_z&1&-A_x\\
-A_y&A_x&1
\end{pmatrix}^{-1}=
\frac{1}{A_x^2+A_y^2+A_z^2+1}
\begin{pmatrix}
1+A_x^2&A_xA_y+A_z&A_xA_z-A_y\\
A_xA_y-A_z&1+A_y^2&A_x+A_yA_z\\
A_y+A_xA_z&A_yA_z-A_x&1+A_z^2\\
\end{pmatrix}=
$$
$$=\frac{1}{1+A^2}\left[
\begin{pmatrix}
1&0&0\\
0&1&0\\
0&0&1\\
\end{pmatrix}+
\begin{pmatrix}
0&A_z&-A_y\\
-A_z&0&A_x\\
A_y&-A_x&0\\
\end{pmatrix}+
\begin{pmatrix}
A_x^2&A_xA_y&A_xA_z\\
A_xA_y&A_y^2&A_yA_z\\
A_xA_z&A_yA_z&A_z^2\\
\end{pmatrix}
\right]
$$
And multiplying by $\mathbf B=(B_x,B_y,B_z)^T$ you can find the result in a form that is the same as in OP. The only difference is the factor $\frac{1}{1+A^2}$. Maybe a sign typo  in the question or in the solution?
Comment: sorry In which way ?? i calculate it but i didn't got the solutions
Comment: I added to my answer. Maybe that there is a sign typo in OP?
Comment: your right !!! it's exact $$\frac{1}{(1+A^2)} $$ could you explain me how i have to multiply for B ?
Comment: I don't understand where the $$\mathbf{B}-\mathbf{A}\times \mathbf{B} $$ come from ...
Comment: could somebody help me with the last passage ? I don't have wolframe or maple here in my laptop ... could you help me in this way ?
Comment: is this correct ?$$\mathbf{v}_l=
\frac{1}{1+A^2}\left[
\underbrace{\begin{pmatrix}
1&0&0\\
0&1&0\\
0&0&1\\
\end{pmatrix} \begin{pmatrix} B_x\\B_y\\B_z\\ \end{pmatrix}  %\mathbf{B}
}_{\normalsize \mathbf{B}}
+
\underbrace{\begin{pmatrix}
0&A_z&-A_y\\
-A_z&0&A_x\\
A_y&-A_x&0\\
\end{pmatrix} \begin{pmatrix} B_x\\B_y\\B_z\\ \end{pmatrix} %\mathbf{B}
}_{- \mathbf{A}\times \mathbf{B}}
+
\underbrace{\begin{pmatrix}
A_x^2&A_xA_y&A_xA_z\\
A_xA_y&A_y^2&A_yA_z\\
A_xA_z&A_yA_z&A_z^2\\
\end{pmatrix} \begin{pmatrix} B_x\\B_y\\B_z\\ \end{pmatrix}}_{\mathbf{(A \cdot B)A}}
\right]$$
Comment: Yes, it is corrrect !
Answer: I'll try this two different ways.

First, let's continue the solution by Emilio Novati.
There is some matrix multiplication involved here, so let's do it
step by step.
First we multiply by $\mathbf B$ on the right in order to get the
desired vector $\mathbf v_l$:
$$\mathbf v_l=\frac 1{1+A^2}\left[ \begin{pmatrix}1&0&0\\0&1&0\\0&0&1\end{pmatrix}+ \begin{pmatrix}0&A_z&-A_y\\-A_z&0&A_x\\A_y&-A_x&0\end{pmatrix}+ \begin{pmatrix}A_x^2&A_xA_y&A_xA_z\\A_xA_y&A_y^2&A_yA_z\\A_xA_z&A_yA_z&A_z^2\end{pmatrix}\right]\mathbf B.$$
Matrix multiplication distributes over matrix addition, so we have
$$\mathbf v_l =
\frac 1{1+A^2}\left[
\begin{pmatrix}1&0&0\\0&1&0\\0&0&1\end{pmatrix}\mathbf B + \begin{pmatrix}0&A_z&-A_y\\-A_z&0&A_x\\A_y&-A_x&0\end{pmatrix} \mathbf B +
\begin{pmatrix}A_x^2&A_xA_y&A_xA_z\\A_xA_y&A_y^2&A_yA_z\\A_xA_z&A_yA_z&A_z^2\end{pmatrix}\mathbf B
\right].$$
Now let's take the three terms inside the brackets one at a time,
denoting the three components of $\mathbf B$ like this:
$$ \mathbf B = \begin{pmatrix}B_x\\B_y\\B_z\end{pmatrix}.$$
So now we have some matrix multiplications. Matrix multiplication
is defined on Wolfram MathWorld among many other places;
Purplemath has a nice animation of the process.
In the particular formula above, every matrix multiplication is
a $3\times3$ matrix by a $3\times1$ matrix, and the rule is
$$
\begin{pmatrix}m_{11}&m_{12}&m_{13}\\m_{21}&m_{22}&m_{23}\\m_{31}&m_{32}&m_{33}\end{pmatrix}
\begin{pmatrix}v_1\\v_2\\v_3\end{pmatrix} =
\begin{pmatrix}m_{11}v_1+m_{12}v_2+m_{13}v_3\\
m_{21}v_1+m_{22}v_2+m_{23}v_3\\
m_{31}v_1+m_{32}v_2+m_{33}v_3\end{pmatrix}
$$
First we have multiplication by an identity matrix:
$$\begin{pmatrix}1&0&0\\0&1&0\\0&0&1\end{pmatrix}
\begin{pmatrix}B_x\\B_y\\B_z\end{pmatrix}
= \begin{pmatrix}B_x\\B_y\\B_z\end{pmatrix} = \mathbf B.$$
For the next term, let's write
$$\begin{pmatrix}0&A_z&-A_y\\-A_z&0&A_x\\A_y&-A_x&0\end{pmatrix}
= -\begin{pmatrix}0&-A_z&A_y\\A_z&0&-A_x\\-A_y&A_x&0\end{pmatrix}.$$
So now we just have to confirm that
$$\begin{pmatrix}0&-A_z&A_y\\A_z&0&-A_x\\-A_y&A_x&0\end{pmatrix}
\begin{pmatrix}B_x\\B_y\\B_z\end{pmatrix}
= \begin{pmatrix}A_yB_z-A_zB_y\\A_zB_x-A_xB_z\\A_xB_y-A_yB_x\end{pmatrix}
= \mathbf A \times \mathbf B,$$
confirming that multiplication by the matrix $\mathbf A_{[\times]}$
does indeed perform a cross product as stated by Emilio Novarti.
Finally we look at the third term:
\begin{align}
\begin{pmatrix}A_x^2&A_xA_y&A_xA_z\\A_xA_y&A_y^2&A_yA_z\\A_xA_z&A_yA_z&A_z^2\end{pmatrix} \begin{pmatrix}B_x\\B_y\\B_z\end{pmatrix} &=
\begin{pmatrix}A_x^2B_x+A_xA_yB_y+A_xA_zB_z\\A_xA_yB_x+A_y^2B_y+A_yA_zB_z\\A_xA_zB_x+A_yA_zB_y+A_z^2B_z\end{pmatrix} \\
&= (A_xB_x+A_yB_y+A_zB_z) \begin{pmatrix}A_x\\A_y\\A_z\end{pmatrix} \\
&= (\mathbf A \cdot \mathbf B) \mathbf A.
\end{align}

For the second way,
we take the formula
$$\frac1{1+A^2}[\mathbf B - \mathbf A\times\mathbf B  + (\mathbf A \cdot \mathbf B) \mathbf A],$$
which is proposed as the value of $\mathbf{v}_l,$
and try plugging it into the formula
$$ \mathbf{v}_l + \mathbf{A} \times \mathbf{v}_l$$
to see if we actually come up with the result $\mathbf{B}$ as desired.
First let's work on the term $\mathbf A\times\mathbf v_l.$
Using various rules of vector arithmetic, we have
\begin{align}
\mathbf A\times\mathbf v_l &=
\mathbf A\times\left[\frac1{1+A^2}[\mathbf B - \mathbf A\times\mathbf B + (\mathbf A \cdot \mathbf B) \mathbf A]\right] \\
 &= \frac1{1+A^2}[\mathbf A\times\mathbf B - \mathbf A\times(\mathbf A\times\mathbf B) + \mathbf A\times(\mathbf A \cdot \mathbf B) \mathbf A] \\
 &= \frac1{1+A^2}[\mathbf A\times\mathbf B - \mathbf A\times(\mathbf A\times\mathbf B)],
\end{align}
because
$$
\mathbf A\times(\mathbf A \cdot \mathbf B) \times\mathbf A
= (\mathbf A \cdot \mathbf B) [\mathbf A\times\mathbf A] = \mathbf 0.
$$
Therefore the proposed substitution for $\mathbf v_l$ says that
\begin{align}
\mathbf v_l + \mathbf A \times \mathbf v_l
&= \frac1{1+A^2}[\mathbf B - \mathbf A\times\mathbf B  + (\mathbf A \cdot \mathbf B) \mathbf A]
+ \frac1{1+A^2}[\mathbf A\times\mathbf B - \mathbf A\times(\mathbf A\times\mathbf B)] \\
&= \frac1{1+A^2}[\mathbf B + (\mathbf A \cdot \mathbf B) \mathbf A
     - \mathbf A\times(\mathbf A\times\mathbf B)].
\end{align}
Next, let's see how the vectors $(\mathbf A \cdot \mathbf B) \mathbf A$ and $\mathbf A\times(\mathbf A\times\mathbf B)$ relate to the plane containing $\mathbf A$ and $\mathbf B.$
Defining $A = \|\mathbf A\|$ and $B = \|\mathbf B\|,$
if $\theta$ is the angle between $\mathbf A$ and $\mathbf B$
then $\mathbf A\times\mathbf B$ is a vector of length
$AB\sin\theta$ perpendicular to the plane
containing $\mathbf A$ and $\mathbf B.$
But $\mathbf A\times(\mathbf A\times\mathbf B)$ is perpendicular to
$\mathbf A\times\mathbf B,$ so it's in the plane
containing $\mathbf A$ and $\mathbf B,$
and it's also perpendicular to $\mathbf A.$
By a couple of applications of the right-hand rule for the cross product,
we find that $\mathbf A\times(\mathbf A\times\mathbf B)$ is on the side of
$\mathbf A$ opposite from $\mathbf B,$
so $-\mathbf A\times(\mathbf A\times\mathbf B)$ is on the same side
as $\mathbf B$ and makes an angle $\frac\pi2 - \theta$ with $\mathbf B.$
Moreover, its length is
$$A(AB\sin\theta)\sin\frac\pi2
= A^2B\sin\theta$$
Meanwhile, $\mathbf A \cdot \mathbf B = AB\cos\theta,$ so
$(\mathbf A \cdot \mathbf B) \mathbf A$ is a vector
of length $A^2B\cos\theta$ parallel to $\mathbf A.$
So now we have two perpendicular vectors, one of length
$A^2B\cos\theta$ parallel to $\mathbf A$ and the other of length
$A^2B\sin\theta$ perpendicular to $\mathbf A.$
The vector sum of these vectors is a vector of length
$A^2B$ at an angle $\theta$ from $\mathbf A$;
in fact it is exactly in the same direction as $\mathbf B,$
and it is the vector $A^2 \mathbf B.$ That is,
$$ (\mathbf A \cdot \mathbf B) \mathbf A
     - \mathbf A\times(\mathbf A\times\mathbf B) = A^2 \mathbf B.$$
So now we have
$$ \mathbf{v}_l + \mathbf{A} \times \mathbf{v}_l
= \frac1{1+A^2}[\mathbf B + A^2 \mathbf B] = \mathbf B,
$$
showing that
$$\mathbf{v}_l = \frac1{1+A^2}[\mathbf B - \mathbf A\times\mathbf B  + (\mathbf A \cdot \mathbf B) \mathbf A]$$
is indeed a solution of that equation.

Solve vectorial equations


how can a .tiff file be input to Matlab vision.VideoFileReader?

Question: I have a .tiff video file and want to input it into my Matlab script.
But vision.VideoFileReader supports only .mpeg .mp2 .mpg .m4v but NOT .tiff.
Does Matlab have a function that converts .tiff to a format readable by vision.VideoFileReader?
Comment: TIFF is a still image format. Do you have a multi-layered TIFF or a folder full of separate frames?
Comment: Yes what? Multi-Tiff of separate frames? Plus what OS are you working with? Supported file types seem to [differ](http://www.mathworks.com/help/vision/ref/vision.videofilereader-class.html?refresh=true) depending on the platform
Comment: Yes.  It is the output from a FLIR camera.
Comment: Sorry -- multi-page .tiff file, where each page is a single frame.  Windows-7 Pro 64-bit.
Answer: You can just use imread.
img = imread('image.tif', i);

will read the i-th image from a multi-image TIFF file.


Apply Modules to Previous Posts

Question: I've recently imported my articles from another database (custom format) and I'd like to apply modules (like Colorbox and other such output-related modules) to those previous posts. Is the standard behaviour to allow this sort of thing, or am I supposed to manually adjust all previous posts?
I've only ever worked with WordPress before, and their plugins work on all articles (past and new).
Answer: For colorbox to work on your new posts, you need to edit the content type(s) of your new posts
<code>Home » Administration » Structure » Content types » YourContentType
</code>
Click on "Manage Display". Here, you can choose the format "Colorbox" for the image field (and click that modal to customize, etc). It will be applied to all nodes of that content type.
Of course, you'll first have to install the colorbox module and library.
The same principle applies to other modules.
About posts/nodes and content types:
Typically, there are only very few content types configured in Drupal - by default there are "article" and "basic page", but you can create more as you need them.
You would import your old post into drupal using one or very few different content types.
The changes need to be done for the content type, meaning they'll get applied to all nodes (posts) in that content type.
You need to look which content type to imported your nodes (posts) into. When you go to http://www.example.com/admin/content, you see a list of your nodes, and in the "Type" column the content type.
Then you go to http://example.com/admin/structure/types/manage/yourcontenttype/display and manage the display as outlined in my answer.
For the article content type, this would be:
http://example.com/admin/structure/types/manage/article/display
Of course, you need to change example.com to your url.
Comment: So I would have to do this for each and every old post too then? If so, this is how Drupal's modules work? I have to manually add them to all posts made before the module's installation? Seems odd, especially in terms of managing a large site...
Comment: I amended my reply to may it more clear. No, you don't need to do this for every post, just for the content type of the posts.
Comment: ok so...the "image" field is not really a thing, since the images are placed right in the text...
Comment: That makes things difficult. Drupal needs to know about these images in a structured way. Maybe you could test a re import of the nodes which enters the images into a field.

Apply Modules to Previous Posts


Equicontinuous and uniformly equicontinuous

Question: Let $f:X\rightarrow Y$ be a continuous function between two metric space then the collection
$\mathfrak{A}=\{f \}$ is equicontinuous if and only if...
I found the question in a book named Topology of Metric spaces.
Question asked for finding iff condition for the given family to be equicontinuous.
My answer: $\mathfrak{A}$ is equicontinuous if and only if $f$ is continuous.
Actually I am confused about the question. In the question it is given that $f$ is continuous.
Please someone help me clarifying my doubts.
Answer: I assume they are just asking you to give the definition of equicontinuity. A collection $\mathcal{U}$ is equicontinuous if and only if for all $\epsilon>0$, there exists a $\delta>0$ so that whenever $d_X(t,s) < \delta$, $\sup_{f\in \mathcal{U}}d_Y(f(t),f(s)) < \epsilon$. In other words whenever $d_X(t,s) < \delta$, $d_Y(f(t),f(s)) < \epsilon$ for all $f\in \mathcal{U}$. Notice this is stronger than continuity. Can you see why?


need guidance on node.js multilingual presentation

Question: I am new to node (v0.10) stack.
I am trying to achieve the following:
I have (hopefully) multilingual articles in the latest MongoDB such as:
_id
...more fields...
text: [
{lang: 'en', title: 'some title', body: 'body', slug: 'slug'},
....
]

Everytime I display an article in specific language I query as follows:
var query = Model.findOne({'text.slug': slug});
query.exec(function(err, doc){
async.each(doc.text, function(item, callback){
    if (item.lang == articleLang) {
        //populate the article to display
    }
});

res.render('view', {post:articleToDisplay});
});

Slug is unique for each language!
The problem I have is that mongo will return the whole doc with all subdocs and not just the subdoc I searched for. Now I have to choose to iterate over all subdocs and display the appropriate one on client side or use async.each on the server to get the subdoc I need and only send to the views that one. I am doing it with async on the server. Is that OK? Also async iterates asynchronously but node still waits for the whole loop to finish and then renders the view. Am I missing anything thinking that the user is actually blocked until the async.each finishes? I am still trying to wrap my head around this asynchronous execution. Is there a way I can possibly improve how I manage this code? It seems to be quite standard procedure with subdocs!
Thanks in advance for all your help.
Answer: To achieve what you want, you need to make use of the aggregation pipeline. Using a simple findOne() would not be of help,
 since you would then have to redact sub documents in your code rather than allowing mongodb to do it. find() and findOne() return the whole document when
 a document matches the search criteria.
In the aggregation pipleline you could use the $unwind and $match operators to achieve this.
$unwind:

Deconstructs an array field from the input documents to output a
  document for each element. Each output document is the input document
  with the value of the array field replaced by the element.

First unwind the document based on the text values array.
$match:

Filters the documents to pass only the documents that match the
  specified condition(s) to the next pipeline stage.

Then use the $match operator to match the appropriate documents.
db.Model.aggregate([
{$unwind:"$text"},
{$match:{"text.slug":slug,"text.lang":articleLang}}
])

Doing this would return you only one document with its text field containing only one object. such as: (Note that the text field in the output is not an array)
{ "_id" : ... ,.., "text" : { "slug" : "slug", "lang" : "en" ,...} }

Comment: Thanks!. If you could answer my question whether the async.each is blocking the app untill all options are iterated and that would constitute accepting this as the answer.
Comment: Yes, it still means you are iterating over all the array items asynchronously rather than sequentially. http://www.sebastianseilund.com/nodejs-async-in-practice - for better understanding of how the async works. the async.each().. would still execute asynchronously.But you would get your control back only when all the tasks are completed, i.e all the individual text fields are iterated, and that is when you are rendering your view. Rather, you could set some variable to identify that your match has been found and then call the final callback or exit by stopping all the other tasks.
Comment: @sunlover:tag for the above response.


Unable to Retrieve Custom Taxonomy Fields Using PHP

Question: I have added a custom image field to a Drupal 7 taxonomy called "field_uc_catalog_image2".
I am now attempting to get the path of that field using PHP with this code:
$normal_path= drupal_get_normal_path($_GET['q']);
$tid = array_pop(explode('/', $normal_path ));
if ( is_numeric( $tid ) ) {
  $term = taxonomy_term_load($tid);
  print $term->field_uc_catalog_image2['und'][0]['uri'] . '
';
}

However, I am getting the following error:

Notice: Undefined index: und in eval() (line 6 of C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\le\modules\php\php.module(80) : eval()'d code).

Whereas, this similar expression for the standard image works fine:
print $term->uc_catalog_image['und'][0]['uri'] . '
';

Do you have any suggestion?
Comment: try `print_r($term)` or `dpm($term)` if Devel is installed to find out what are loaded in `$term`
Answer: Using print_r($term) (as per Mohammad's suggest) I could see the correct expression was actually another one.
$term->field_image['und'][0]['uri']


How can I unit test performance optimisations in C?

Question: I've been working on a portable C library that does image processing.
I've invested quite some time on a couple of low level functions so as to take advantage of GCC auto-vectorization (SSE and/or AVX depending on target processor) mode while still preserve a somewhat portable C code (extensions used: restrict and __builtin_assume_aligned).
Now is time to test the code on windows (MSVC compiler). But before that I'd like to setup some kind of unit testing so as not to shoot myself in the foot and loose all my carefully chosen instructions to preserve GCC auto-vectorization code as-is.
I could simply #ifdef/#endif the whole body function, but I am thinking of a more long term solution that would detect upon compiler update(s) of any regression.
I am fairly confident with unit testing (there are tons of good framework out there), but I am a lot less confident with unit-testing of such low level functionality. How does one integrate performance unit testing in CI service such as jenkins ?
PS: I'd like to avoid storing hard-coded timing results based on a particular processor, eg:
// start timer:
gettimeofday(&t1, NULL);
// call optimized function:
...
// stop timer:
gettimeofday(&t2, NULL);
// hard code some magic number:
if( t2.tv_sec - t1.tv_sec > 42 ) return EXIT_FAILURE;

Comment: do you have non-optimized (generic)  functions? It would be better to compare execution time w/ them... meaning that `t_opt` expected to be less than `t_non_opt`... but even that is not a 100% guaranty. Other processes may do random disk access in parallel, your test could be preempted any time... and a bunch of other things may happened not in your tests...
Comment: Have you considered microbenchmarking frameworks like google benchmark or similar??
Comment: What are you aiming at?  Do you want to ensure that after your modifications your code remains correct (then you would be doing unit-testing) or do you want to check the performance of the resulting code (which is something different and may be approached in different ways)?  In the latter case, you might even want to print out the generated assembly code to compare it against your expectations.
Comment: @DirkHerrmann that's the whole point ! How do I print 'portable' assembly code ? This may depends on exact gcc version, thanks for additional details if you are familiar with generating assembly code.
Comment: @malat (maybe a bit off, but since you are used to GCC..) why does it have to be MSVC? why can't it be [mingw-w64](http://mingw-w64.org/doku.php) instead? (and therefore GCC *again*? not to mention, that you can write C99 or even better, C11 instead the very old (and limited) C89 which is the only standard MSVC supports as is)
Answer: Your problem basically boils down into two parts:

What's the best way to performance benchmark your carefully optimized code?
How to compare the results of the comparisons so you can detect if code changes and/or compiler updates have affected the performance of your code

The google benchmark framework might provide a reasonable approach to problem #1. It is C++, but that wouldn't stop you from calling your C functions up from it.
This library can produce summary reports in various formats, including JSON and good old CSV. You could arrange for these to be stored somewhere per run.
You could then write a simple perl/python/etc script to compare the results of the benchmarks and raise the alarm if they deviate by more than some threshold.
One thing you will have to be careful about is the potential for noise in your results caused by variables such as load on the system performing the test. You didn't say much about the environment you are running the tests in, but if it is (for example) a VM on a host containing other VMs then your test results may be skewed by whatever is going on in the other VMs.
CI frameworks such as Jenkins allow you to script up the actions to be taken when running tests, so it should be relatively easy to integrate this approach into such frameworks.
Answer: A way to measure the performance in a simple and repeatable way would be to run a benchmarking unit test through valgrind/callgrind. That will give you a number of metrics: CPU cycles, Instruction and Data read and write transactions (at different cache depths), bus-blocking transactions, etc. You would only have to check those values against a known-good starting value.
Valgrind is repeatable because it emulates the running of the code. It is of course (much) slower than directly running the code, but that makes it independent of system load, etc.
Where Valgrind is not available, as in Windows (though there are mentions of valgrind + wine + Windows programs on Linux), dynamoRIO is an option. It provides tools similar to Valgrind, like an instruction counter, and memory and cache usage analyzer. (Also available on Linux and seemingly half-ported to OS X as of this writing)
Comment: not portable on windows, but at least gives much more details than just the test timing.
Comment: There is mention of valgrind+wine setups, but yeah, that might get complicated.
Comment: @malat, if you are still working on this, I just found something that might be the equivalent of valgrind's various tools for Windows: http://dynamorio.org/ (check the "instruction counting tool inscount" and "multi-process online cache simulator drcachesim")


What is the problem with this foreach loop?

Question: why doesnt this array work? What do I do wrong? The result of my foreach loop is always either empty or just some weird numbers and signs. So what is wrong with my foreach loop?
$array = array();

while($row = mysqli_fetch_array($result)) {
    if(!empty($row["some"])) {
        $array["some"] = $row["some"];
        $array["some2"] = $row["some2"];
    }

}
foreach($array as $property=>$value) {
echo '
'.$value["some"].' - '.$value["some2"].'
'; }

Answer: $array will have only two properties, some and some2. Therefore your foreach loop doesn't make any sense. The foreach will loop two times, the first time with this:
$property = 'some';
$value = $row["some"];

and the second with this:
$property = 'some2';
$value = $row["some2"];

You will have to make $array multidimensional in your first loop by doing this:
while($row = mysqli_fetch_array($result)) {
    $new = array();
    if(!empty($row["some"])) {
        $new["some"] = $row["some"];
        $new["some2"] = $row["some2"];
        $array[] = $new;
    }
}

or shorter:
while($row = mysqli_fetch_array($result)) {
    if(!empty($row["some"])) {
        $array[] = array('some' => $row["some"],
                         'some2' => $row["some2"]);
    }
}

Answer: $array["some"] and $array["some2"] are specific array elements. You are overwriting them every iteration of your while loop.
Not sure what you're trying to actually accomplish but I think possibly this is what you want:
$array = array();

while($row = mysqli_fetch_array($result)) {
    if(!empty($row["some"])) {
        $array["some"][] = $row["some"];
        $array["some2"][] = $row["some2"];
    }

}
foreach($array["some"] as $property=>$value) {
  echo '
'.$value.' - '.$array["some2"][$property].'
';
}

or
$array = array();

while($row = mysqli_fetch_array($result)) {
    if(!empty($row["some"])) {
        $array[] = array('some' => $row["some"],
                         'some2' => $row["some2"]);
    }

}
foreach($array as $property=>$value) {
  echo '
'.$value['some'].' - '.$value['some2'].'
';
}

or similar...kinda depends on what you're ultimately trying to accomplish...
Comment: You are right! I totally didnt see that. So the right version would be $array[]["some"] = $row["some"]; wouldnt it be?
Answer: This doesn't explain the weird numbers and signs, but you are overwriting $array['some'] and $array['some2'] on each loop iteration.
Instead, try this:
while($row = mysqli_fetch_array($result)) {
    if(!empty($row["some"])) {
        $array[] = array("some"=>$row['some'], "some2"=>$row['some2']);
    }
}

Answer: $array[] = array('some' => $row["some"], 'some2' => $row["some2"]);

But it would be better to retrieve only these columns.
Answer: Emil has the right answer :D. I love how people post so fast on here lol.


Groupby Percentage from total

Question: I am trying to group by the region and finding the percentage of product1 , product2, and product3 from the total product.
Here is the code
a = df_2018.groupby(['ISIC4_ARABIC']).agg({'product1': ['sum'], 'product2': ['sum'], 'product3': ['sum']})

So in the end i will have product1 , product2, and product3 as percentage of total product and the total product as the number.
below is the image of the data frame
Comment: Please provide your sample data as text, not images.
Answer: Use:
cols=['produc1','product2','product3']
a[cols]=a[cols]/a[cols].sum(axis=1)

Comment: why did you put product 3 out from product 1 and 2
Comment: It was a mistake, sorry
Answer: IIUC:
s = a.iloc[:, 1:]
a.iloc[:, 1:] = s.div(s.sum(1), axis='rows')

Output (a):
  region  product1  product2  product3
0     CA  0.333333  0.333333  0.333333
1     MN  0.500000  0.250000  0.250000
2     OH  1.000000  0.000000  0.000000
3     NY  0.714286  0.142857  0.142857

Comment: thank you Quang . but i want to get product1 , product2, and product3 as percentage and the total product as the number.
Comment: @AzizAlreshidi you're welcome. Plz consider upvote and accept the answer if it helps.

Groupby Percentage from total


How to check if dataset has been used for a Neural Network

Question: I'm participating in a research by applying some computer vision processing on some images, and I got asked how I could put a watermark on the images in case someone else uses the dataset for purposes not intended on the paper.
Example: Our dataset mustn't be used to create a Convolutional Neural Network with Caffe.
What's the best way to test a dataset has been trained with that data? For example any kind of general test, or applying a watermark in every single image.
Comment: Interesting question, though I don't know whether it's really on-topic here ([you may want to look at Signal Processing.SE](https://dsp.stackexchange.com/), possibly flag the question for migration). That said, I think it's doubtful this can be done, especially if you want to defend against *multiple* possible "attacks", i.e., network architectures, algorithms, or even parameterizations.
Comment: It's a very interesting problem, I'd love to see how people approach solving it
Answer: This is not a real answer, but rather an idea.
The reason why I don't immediately dismiss the question as unsolvable: NN problems are usually underdetermined, i.e. num of observations is smaller than num of parameters. In this case, it's very difficult to get rid of noise in parameters.
Watermarks are basically noise, or not a signal, at least that's how they should appear to a naked eye. So, maybe you can come up with a watermark that will make into parameters of NN. Later once the model is built and deployed, you send a batch of watermarked images into NN, then observe the output. Maybe you can detect that the parameters are contaminated with a watermark by analyzing statistical characteristics of the output images.
For instance, you'll mark images of dogs and cats with different signatures in the training set. Then for testing NN for theft, you send the same images but with randomly assigned watermarks. If the output shows difference in accuracy of  detection of cats on the same images with different watermarks, it would mean that the NN used your database.


Full rotation yields opposite state

Question: A while back I learned about systems which could undergo a "full revolution" and end up in the opposite state they were in when they started. Two full revolutions were required in order to return to the origin.
Does anyone know what these systems are called? I would like to look into them further but I can't remember what they were called and I can't find it on Google.
Thanks
Comment: [Spinors](https://en.wikipedia.org/wiki/Spinor)
Answer: These are called spinors. They are used prominently in relativistic quantum mechanics and quantum field theory in physics.

Full rotation yields opposite state


What does the consistency condition mean in IPTW?

Question: From the paper On the Consistency Rule in Causal Inference: Axiom, Definition, Assumption, or Theorem?  Pearl (2010):

Informally, the consistency rule states that a person's potential outcome under a
  hypothetical condition that happened to materialize is precisely the outcome experienced
  by that person.

I have a hard time understanding this sentence. What does this mean? Is this related to endogeneity in standard econometrics?
Could someone help met out? Kind regards.
Answer: Imagine there is a link between a treatment level, $a$, and a potential outcome, $Y(a)$. For example, say the following links exist:
$$0 \rightarrow Y(0) \\1 \rightarrow Y(1) $$
Consistency says that when an individual receives a value of treatment, their observed outcome $Y$ is the potential outcome linked to that treatment. It's not some other value.
We can think of each individual having many potential outcomes inside them. The goal of causal inference is to estimate the difference between these potential outcomes; each difference corresponds to the causal contrast between the different treatments. When we assign an individual to a treatment value, we reveal one of their potential outcomes. Consistency says that the potential outcome that we reveal is the potential outcome that corresponds to the treatment actually received.
For some nice introductions from perspectives other than Pearl's, I recommend Cole & Frangakis (2009) and Hernán & Taubman (2008).


redirect all pages based on global boolean

Question: If I have a global variable that is false by default but changes later on, is it possible to automatically redirect using this variable? This is basically what I want:
@if (!boolean)
{
  <meta http-equiv='refresh' value='0; redirect_to_this_url'>
}

I've tried this, and it doesn't work (the controller loads forst and throws loads of errors based on this boolean) Please help.
Comment: it's not clear. If you want to check a status to stay in current page or redirect it to another page you use lots of way, for instance, you can use cooki and JS to do that.
Comment: I don't want to store using cookies, this is just in session cache. But when someone visits my site, I want them to be redirected to a certain page if `boolean` is false. I need this to happen **no matter what page they try to open**
Comment: Where is the boolean written to? If it is server-side then it would be much better to do this in the Controller rather than the view
Comment: @Stewart_R It's server side, and I know it should be in the controller, and that works well. But I want to respect DRY here and only have it in my code once. Is there a sort of 'global controller' that all requests go through? Would it be possible to redirect to a different controller using this?
Comment: You have a couple of options. Firstly, I should say that Controllers are just classes so you could have a base controller implementing your global redirect functionality then all your other controllers could inherit from it. It would probably be better for you to investigate Filters though: http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs both these options would allow you to stay DRY
Comment: you can use custom action filter for your controller , https://msdn.microsoft.com/en-us/library/gg416513(VS.98).aspx
   Or      http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-custom-action-filters
Comment: you can create Application level variable and store the value. In your view  you can this value. So, when this value becomes true, all users who visits the page will be redirected and when it is set to false, no redirection happens.
Comment: I think the answers to http://stackoverflow.com/questions/11726848/asp-net-mvc-4-intercept-all-incoming-requests cover your use case
Comment: Thank you all, but will someone please post this as an answer?? Also, @KarthikMR, that would mean multiple checks, which is a DRY violation
Comment: you can check only in your layout view
Comment: Please reread my question @KarthikMR. I already tried that, but the controller throws an error before the view gets parsed and rendered
Comment: you can use javascript to redirect. it would work in layout too. eg. if(//check variable) {window.location.href = urlLoginPage;}
Comment: I CAN'T USE THE VIEW @KarthikMR. Please listen. This cannot be in the view. It must be in the controller.
Comment: @Anonymouse - Why can't you use the JS code in your layout view. Any page that user requests will have layout view. So, you are checking the condition. What is the issue with that?
Comment: @KarthikMR Because the way ASP.NET MVC sites execute means that the controller gets executed first. If the controller relies on this value (which it does), then the controller will throw an error.
Comment: @Stewart_R Thank you for your answer. Please could you make an answer for this question? Thanks.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/110818/discussion-between-karthik-m-r-and-anonymouse).
Answer: This could be tackled using Action Filters
For example, consider what happens when we replace the default FilterConfig.cs file in the App_Start folder of an Asp.Net 4.5.2 MVC project with this:
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new RedirectActionFilter());
    }
}

public class RedirectActionFilter : IActionFilter
{
    static Random rng = new Random();
    static bool GetBool() => rng.Next() % 2 == 0;

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {

        if (GetBool())
        {
            filterContext.Result = new RedirectResult("http://www.bbc.co.uk");
        }

    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {

    }
}

Then the OnActionExecuted() method of our RedirectActionFilter class gets called before the Asp.Net application responds to the browser. As a result, if GetBool() returns true then we will redirect to bbc.co.uk otherwise nothing is changed and we would get the normal action result from whichever controller action is handling our request


on sequences of functions converging uniformly and their sequences of derivatives

Question: The question is : does there exist a sequence of derivable functions $f_n$ defined on $\mathbb{R}$, that converges uniformly to the zero function and such that the sequence of dérivatives converges pointwise to a function g that never vanishes?
Obviously, the sequence $(f_n ')$ cannot be bounded on every closed interval $[a,b]$. Otherwise, one can easily see by dominating convergence that $\int_a ^b g(t)dt=0$, and so $g$ must vanish somewhere on $[a,b]$, but I do not know what happens if we do not impose this condition on the sequence $(f_n ')$. I am bound to think this is impossible in the general cas, but I cannot see any counterexample. If you have any ideas, that will be helpful...
Answer: You may have seen user126154's answer. They demonstrate that if $f_n \to 0$ pointwise, $f_n : [0,1] \to \mathbb{R}$ is differentiable, and $f'_n$ is continuous on $[0,1]$, then $X = \{x \in [0,1] : g(x) = 0 \}$ is dense in $[0,1]$, where $f'_n \to g$ pointwise.
That means if a counterexample does exist, we are limited to discontinuous, unbounded sequences $(f'_n)$.

However, this could be impossible. To show that such a sequence cannot exist, here's an idea:
According to Theorem 2 in Haskell Curry's answer, the set $E_n$ of discontinuities of $f'_n$ is a meagre set.
Then, $E = \bigcup_{n=1}^\infty E_n$ is also a meagre set, with the property that every $f'_n$ is continuous on $D = \mathbb{R} - E$. By definition, $D$ is a comeagre set, which implies that int($D$) is dense in $\mathbb{R}$.
Maybe we could use the same argument in user126154's answer, by replacing $[0,1]$ with $D$? If so, it would prove that $X = \{x \in \text{int}(D) : g(x) = 0 \}$ is dense in $\text{int}(D)$, and hence, $X$ is dense in $\mathbb{R}$.
Consequently, not only does $g$ vanish somewhere, but $g$ vanishes on a dense subset of $\mathbb{R}$.


Unblock an automated blocked user

Question: I used Login Security module to block users after some login failures. It works fine however I need to unblock such users after certain time like after 1 hour/day. How would I do that as it has configurations to delete attempt from database but user isn't unblocked and it has to be active manually.
Please see below attached screen shot of module configuration.
Answer: I just developed a small module named as Auto Unblock Users to unblock users.
This will only work if the user is blocked by Login Security module.
Answer: What about unblocking the blocked user after an hour using Rules module?
Edited:
Use Rules module.
Create custom event for your particular module event (for example, "User Blocked after login failure"
Unblock users after one hour.
Comment: Bulk of users might be blocked earlier by site admin manually. I need to unblock those users who has 0 attempts in database only or blocked by using this module.
As you suggested by using Rules, every blocked user will be unblock who even never tried to logged in once.

Unblock an automated blocked user


How many distinct pairwise difference multisets exists?

Question: For all $K$-point integer-valued sets whose elements are between $1$ and $N$ and also distinct, how many distinct pairwise difference multiset exists?
Note that the difference is evaluated modulu N.
for example: for $(N,K)=(5,3)$ we have:
$\color{green}{\{1,2,3\} \rightarrow \{1,1,2,3,4,4\}}$
$\color{red}{\{1,2,4\} \rightarrow \{1,2,2,3,3,4\}}$
$\color{green}{\{1,2,5\} \rightarrow \{1,1,2,3,4,4\}}$
$\color{red}{\{1,3,4\} \rightarrow \{1,2,2,3,3,4\}}$
$\color{red}{\{1,3,5\} \rightarrow \{1,2,2,3,3,4\}}$
$\color{green}{\{1,4,5\} \rightarrow \{1,1,2,3,4,4\}}$
Note that other possible 3-point sets are shifted or reversed version of shown sets and lead to same pairwise difference multisets. So we can assume that the first element of set is $1$, without loss of anything. So for $(N,K)=(5,3)$ we have only 2 distinct pairwise difference multisets.
I'm looking for a formula which computes all distinct possible pairwise difference multisets for any pair $(N,K)$ ?
As I didn't know what is the most preferable site for this question, I posted in on these sites too: mathoverflow, Theoretical Computer Science
Comment: @Mahdi, this is the usual practice. You should have provided the links between copies yourself and should not have posted questions on multiple sites at the same time.
Comment: [cross-posted](http://cstheory.stackexchange.com/questions/18304/how-many-distinct-pairwise-difference-multisets-exists)
Comment: You did this to all of my posts Kaveh! Now I could not get any help! Please guide me what to do!
Comment: The comment above is only for information, so this post here remains answerable. A quick enumeration of values shows the numbers you are after to be those from http://oeis.org/A103441/table but unfortunately this does not come with a closed formula which you could use to compute these values.
Comment: I didn't get anything from the tables in the link you suggested! Would you mind guiding how they are related to my question ?
Answer: I used the following Python code to tabulate some numbers:
import sys, itertools
for n in range(1, 25):
    sys.stdout.write("{:3}:".format(n))
    for k in range(1, n + 1):
        r = set()
        for c in itertools.combinations(range(n), k):
            d = [0]*n
            for i, c1 in enumerate(c):
                for c2 in c[(i + 1):]:
                    d[c2 - c1] += 1
                    d[n + c1 - c2] += 1
            d = tuple(d)
            r.add(d)
        sys.stdout.write(" {:4}".format(len(r)))
    sys.stdout.write("\n")

Demo run of that code is also available at http://ideone.com/R0z3dg. Since you requested an explanation in a comment, here is how this works: The outer two loops iterate over reasonable values for $N$ and $K$, i.e. all the (non-empty) cells of the table. The choice of $0<K\leq N$ is somewhat arbitrary; I might as well have included $0$ or excluded $N$, since both of these will always lead to $1$. c then iterates over all possible combinations of $K$ elements taken from the set range(n) $=\{0,1,\dots,(N-1)\}$. These are your point sets. The combinations will be already sorted. The next two loops choose c1 and c2 from that combination such that c1 < c2. For each such pair, you have two differences. The difference c2 - c1 will already be in the range $[0, N)$. The other difference will be negative, so you add $N$ as part of your modulo semantics. For both of these differences, you increment the associated count in the multiset. So d[i] will indicate the number of times the difference i (mod $N$) has already been seen in the current combination c. Once this count is complete (i.e. the loops over c1 and c2 are done), you turn the mutable list into an immutable tuple which can be used as an element of the set r. The result for a given $N$ and $K$ is simply the size of that set r once all combinations c have been processed.
The resulting table looks like this:
  N↓ K→ 1    2    3    4    5    6    7    8    9   10 …
  1:    1
  2:    1    1
  3:    1    1    1
  4:    1    2    1    1
  5:    1    2    2    1    1
  6:    1    3    3    3    1    1
  7:    1    3    4    4    3    1    1
  8:    1    4    5    7    5    4    1    1
  9:    1    4    7   10   10    7    4    1    1
 10:    1    5    8   16   13   16    8    5    1    1
 11:    1    5   10   20   26   26   20   10    5    1    1
 12:    1    6   12   28   35   35   35   28   12    6    1    1
 13:    1    6   14   34   57   74   74   57   34   14    6    1    1
 14:    1    7   16   47   73  120   85  120   73   47   16    7    1 …
 15:    1    7   19   56  106  160  222  222  160  106   56   19    7 …
 16:    1    8   21   70  137  246  327  254  327  246  137   70   21 …
 17:    1    8   24   84  196  376  576  698  698  576  376  196   84 …
 18:    1    9   27  104  237  493  762 1121  701 1121  762  493  237 …
 19:    1    9   30  120  324  735 1311 1962 2338 2338 1962 1311  735 …
 20:    1   10   33  143  384  932 1778 2649 3651 2377 3651 2649 1778 …
 21:    1   10   37  165  507 1257 2609 4662 6006 7866 7866 6006 4662 …
 22:    1   11   40  195  601 1717 3576 6830 9860 13268 7944 13268 9860 …
 23:    1   11   44  220  759 2244 5302 10395 17105 23958 28216 28216 …
 24:    1   12   48  253  881 2635 6574 12844 21499 32342 42389 25220 …
 25:    1   12   52  286 1086 3622 9574 21389 39582 59132 85754 99638 …

The case from your example, $T(5, 2)=2$, can be read from row 5 column 2 of this table. If you omit the diagonal where $N=K$, i.e. drop the trailing 1 from each row, then the resulting triangle is exactly the one you find as the triangular array representation of OEIS sequence A103441. The statement of this sequence sounds a lot like your question, too:

$T(n,k) =$ number of bracelets of $n$ beads (necklaces that can be flipped over) with exactly two colors and $k$ white beads for which the set of distances among the white beads are different.

Unfortunately, there is no closed forula to accompany that sequence. So at least that encyclopedia does not know the formula you are looking for. There is some Mathematica code, but I guess that this does something as brute-force as what I did in Python above. If anyone here does find a closed formula, please make sure that OEIS gets updated with this information as well.
Since your comment below indicates different results on your part, and the first difference is for $N=8,K=4$, here are some details for that case, using the same notation you used in your original question. As you can see, I got $T(8,4)=7$ with the following point sets as wittnesses:
$$\{1,2,3,4\}\to\{1,1,1,2,2,3,5,6,6,7,7,7\}\\
\{1,2,3,5\}\to\{1,1,2,2,3,4,4,5,6,6,7,7\}\\
\{1,2,3,6\}\to\{1,1,2,3,3,4,4,5,5,6,7,7\}\\
\{1,2,4,6\}\to\{1,2,2,3,3,4,4,5,5,6,6,7\}\\
\{1,2,4,7\}\to\{1,2,2,3,3,3,5,5,5,6,6,7\}\\
\{1,2,5,6\}\to\{1,1,3,3,4,4,4,4,5,5,7,7\}\\
\{1,3,5,7\}\to\{2,2,2,2,4,4,4,4,6,6,6,6\}$$
Comment: I'm not familiar with Python but I wrote the code in Matlab and I've got different answers! The simple algorithm I've used is as follows: build all possible sets and calculate difference multiset of each one and store all of them. Then count number of distinct stored multisets. for $K=4$ and different $N$'s it outputs these :
$$N=4 \rightarrow 1$$
$$N=5 \rightarrow 1$$
$$N=6 \rightarrow 3$$
$$N=7 \rightarrow 4$$
$$N=8 \rightarrow 5$$
$$N=9 \rightarrow 9$$
$$N=10 \rightarrow 13$$
Would you mind giving me algorithm of your Python code ?
Comment: @MahdiKhosravi: I updated my answer to include both a detailed description of my algorithm (which is pretty straight-forward) and details on the $N=8,K=4$ case.
Comment: Yes You are right. My code was wrong and I corrected it. Thank you for your kind answers. How much time did you take on this field? Are you hopeful to find a formula instead of this table? In what context you faced this problem?
Comment: @MahdiKhosravi: I have never before thought about this problem. I just read your question, decided to have a closer look, wrote that piece of code and fed the result into the OEIS search. I originally would have left it as a comment, but since you asked for details, I elaborated. I doubt I'll find a closed formula soon, and I won't have much time to spend on finding one. Perhaps someone else will.
Comment: Nice coding. I am working to find the closed formula which may be out of reach. Also I propose combining charm bracelets with energy charges. (Histograms for charm bracelets). 12C6 charm bracelets = 34, but 26 different histograms. Also, 80 necklaces, 50 Dihedral, 35 histograms (15 isomeric pairs)


How I can pre-populate a webform field with the node title and node link?

Question: In some page I have inserted a link "Contact me for info" that links to a webform page.
I would that some fields of the webform form are be pre-populated with the node title and node link from the previous page.
How I do it?
Answer: You could also do this with a little bit of code:
<code>function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  // Check if the form is your webform, you could make it
  // more dynamic by checking the form title or something.
  if ($form_id == 'webform_client_form_1') {
    // Get the information from the previous page, the best option
    // to me seems to pass the node id via a parameter.
    $get = drupal_get_query_parameters();

    if (!empty($get['previous_page'])) {
      // Load the previous page.
      $previous_page = check_plain($get['previous_page']);
      $node = node_load($previous_page);

      // Check if the previous page is a valid node.
      if (!empty($node)) {
        // Enter the default values.
        $form['submitted']['YOUR_TITLE_FIELD']['#default_value'] = $node->title;
        $form['submitted']['YOUR_URL_FIELD']['#default_value'] = 'node/' . $node->nid;
      }
    }
  }
}
</code>
Answer: Use the PrePopulate module and Tokens to build dynamic links on your pages. When clicked, the link's content will be entered into those fields automatically.
https://www.drupal.org/project/prepopulate
There's an example on the project page.
Comment: I must pass the node title of the current page of the link, with prepopulate I can pass only a value that I manually write in the url
Comment: With the token module which you probably already have enabled, you can create the link using the current page's url.

http://www.example.com/node/contactmeURL?edit[webformtitle]=[current-page:title]

You'd need to  change the url and the title element but that's the idea.
Comment: As a sidenote, I'd add a hidden entity reference prepopulate field to the webform and fill it as well using the nid token just to help with admin so if you have lots of nodes, you have a link to the node. The entity reference prepopulate is slightly different.. Like "?nodeidfield=123". You put & in between each part then.


android bluetooth SPP connection terminates before sending all data

Question: This might be delicate:
I develop an App for Android 6 which may print several receipts on an Bixolon SPP-R-200II. First, the normal way works fine, connection, printing, etc. looks good.
Due to testings I faced one special error. Occasionally the print stops before being finished. The Log shows this:
06-20 15:04:17.456 5369-5393/? W/bt_rfcomm: port_rfc_closed RFCOMM connection in state 2 closed: Peer connection failed (res: 16)
06-20 15:04:17.457 5369-5397/? E/bt_btif_sock_rfcomm: find_rfc_slot_by_id unable to find RFCOMM slot id: 7
06-20 15:04:17.463 5369-5393/? I/bt_btm_sec: btm_sec_disconnected clearing pending flag handle:2 reason:8
06-20 15:04:17.463 5369-5393/? W/bt_l2cap: L2CA_SetDesireRole() new:x0, disallow_switch:0
    L2CA_SetDesireRole() new:x0, disallow_switch:0
06-20 15:04:17.463 5369-5387/? E/BluetoothRemoteDevices: state12newState1
06-20 15:04:17.463 5369-5387/? D/BluetoothRemoteDevices: aclStateChangeCallback: sending ACL disconnected intent
06-20 15:04:17.464 5369-5387/? D/BluetoothRemoteDevices: aclStateChangeCallback: State:DisConnected to Device:74:F0:7D:E4:8E:3C
06-20 15:04:17.466 5369-5369/? D/BluetoothMapService: onReceive
    onReceive: android.bluetooth.device.action.ACL_DISCONNECTED
06-20 15:04:17.468 5369-5369/? V/BluetoothPbapService: action: android.bluetooth.device.action.ACL_DISCONNECTED
06-20 15:04:17.472 5369-5369/? V/BluetoothFtpService: Ftp Service onStartCommand
    PARSE INTENT action: android.bluetooth.device.action.ACL_DISCONNECTED
06-20 15:04:17.475 5369-5369/? D/BluetoothDunService: parseIntent: action: android.bluetooth.device.action.ACL_DISCONNECTED
As I found out there were some issues with the BT stack from Android 4 and newer with devices having a BT-Module Gen 2 or 3. This seems to be the problem here, as old printers with BT Gen 1 work fine, the others amlost for 50% of the time.
Is there any workaround/fix?
Answer: Ok, it seems to be a fault with the printers, here ist my actually working solution:
First, I decompiled the Bixolon API from their SDK. I checked how they implemented the transmission and found out, that on several devices or from a specified API level of Android it is needed to send data in smaller packages. See code below:
From:
    osr.write(output);

Changed to:
    //this is needed for API lvl > 16 due to connection losses with big data
    if (output.length > 1024) {
    for (int i = 0; i < output.length; i += 1024) {
        osr.write(output, i, i + 1024 > output.length ? output.length - i : 1024);
        try
        {
            Thread.sleep(150);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    } else {
        osr.write(output);
    }

Keep in mind, osr is the OutputStream...


generator of lists from pandas dataframe

Question: I have a pandas dataframe like
   node    centroid
    1         1
    2         2
    3         4
    5         6
    7         2
    4         1
    8         4
    10        1

how can I create a generator of lists by this dataset in a way that nodes with the same centroid are in the same list?
I need to have the result like find-clique return(https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorithms.clique.find_cliques.html)
Answer: You use yield to make generators.
import pandas as pd
import random
df = pd.DataFrame({"node": [random.randint(1, 11) for _ in range(8)],
                   "centroid": [random.randint(1, 5) for _ in range(8)]})

def list_gen(df):
  for x in df.centroid.unique():
    yield df[df["centroid"] == x].node.values

[x for x in list_gen(df)]

This will give numpy arrays, but you can deconstruct those back into regular list simply by passing them to list.


Q about AbstractApplicationContext.getBeansOfType() and getBean()

Question: We have the following legacy 2.0.7 Spring code:
final Map<String, MyClass> secondaryFactories
     = (Map<String, MyClass>) context.getBeansOfType(MyClass.class,
                                                     false, true);

return (MyClass) context.getBean("myClass");

where context is an instance of
org.springframework.context.support.AbstractApplicationContext

Note that we ignore the return value of getBeansOfType().  This works just fine, but the problem is that the call to getBeansOfType() is time-consuming.  However, even though we ignore the return value of this call, if we try to eliminate this call, then the instance of MyClass returned by getBean() is not fully initialized.  (So, apparently, the call to getBeansOfType() is having some sort of side-effects that we need.)
We suspect that the call to getBeansOfType() is overkill and we could do something more lightweight so that the instance of MyClass obtained by the call to getBean() would be fully initialized (but it's not null and no exception is thrown).
So, is there a more efficient way of doing this?
Comment: What is BeanType.MY_CLASS.getName() ?
Comment: What version of Spring are you using? Sounds like a bug to me.
Answer: First of all I suggest turning on logging and seeing what goes on. Spring is usually quite helpful.
Second of all, one difference between context.getBeansOfType and context.getBean is that getBeansOfType does not query the parent context. If you have one, you might hit a difference here.
Third of all, I assume the 'driver' bean is lazily initialised. Do you have any sort of multi-threaded code running while the context is initialized? There have been reports of fixes late in the 2.5 cycle related to that. getBeansOfType might be just generating a delay or hitting a memory barrier so that the issue with getBean returning an uninitialised bean is hidden.
Fourth of all, you might want to - just for argument's sake - try running the application with Spring 2.5.6. If it works, you know the guilty party.
Comment: +1 for enabling debug-level logging, spring's very verbose at that level


Change One Cell's Data in mysql

Question: How can I change the data in only one cell of a mysql table.
I have problem with UPDATE because it makes all the parameters in a column change but I want only one changed. How?
Comment: What have you tried so far? Can you share the query you are using? Usually, you do not update "all the parameters in a column"
Answer: You probably need to specify which rows you want to update...
UPDATE
    mytable
SET
    column1 = value1,
    column2 = value2
WHERE
    key_value = some_value;

Comment: @weefwefwqg3, Ah, I see, sorry, an attack of myopia. Yes, that would be perfectly fine.
Comment: I was confused by this answer, thinking SET selected rows to change, and WHERE changed them.
Comment: @Brian Hooper: I do need to change the value, I mean to ask whether I can do this: `UPDATE mytable SET column1 = new_value WHERE column1 = old_value;` ??
Comment: can the condition in WHERE be column1 = old_value ?
Comment: @weefwefwqg3, yes, it can, but there is no point. If you aren't changing the value, just leave it out of the SET part.
Comment: Would using "WHERE ROW_NUMBER() = 1;"  work to update just the first row of the table? (MySQL version 8)
Comment: @Calab, probably it would; haven't tried it. But be careful, as "the First Row in the Table" may not be well-defined.
Answer: My answer is repeating what others have said before, but I thought I'd add an example, using MySQL, only because the previous answers were a little bit cryptic to me.
The general form of the command you need to use to update a single row's column:
UPDATE my_table SET my_column='new value' WHERE something='some value';

And here's an example.
BEFORE
mysql> select aet,port from ae;
+------------+-------+
| aet        | port  |
+------------+-------+
| DCM4CHEE01 | 11112 |
| CDRECORD   | 10104 |
+------------+-------+
2 rows in set (0.00 sec)

MAKING THE CHANGE
mysql> update ae set port='10105' where aet='CDRECORD';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

AFTER
mysql> select aet,port from ae;
+------------+-------+
| aet        | port  |
+------------+-------+
| DCM4CHEE01 | 11112 |
| CDRECORD   | 10105 |
+------------+-------+
2 rows in set (0.00 sec)

Comment: Thanks for this demonstration. The above query will update all the instances of CDRECORD in your column aet. However, when updating a specific cell in a specific column, it is better to do that based on the ID of the column, i.e., where ID=xx
Comment: It is usually best to use the rows primary key, the rows unique identifier (which is often the ID, but not always). Honestly it depends on what you want to do which defines the "best" practice
Answer: UPDATE will change only the columns you specifically list.
UPDATE some_table
SET field1='Value 1'
WHERE primary_key = 7;

The WHERE clause limits which rows are updated. Generally you'd use this to identify your table's primary key (or ID) value, so that you're updating only one row.
The SET clause tells MySQL which columns to update. You can list as many or as few columns as you'd like. Any that you do not list will not get updated.
Answer: UPDATE only changes the values you specify:
UPDATE table SET cell='new_value' WHERE whatever='somevalue'

Answer: Try the following:
UPDATE TableName SET ValueName=@parameterName WHERE
IdName=@ParameterIdName

Comment: Please add some explanation to your answer such that others can learn from it - what does that `@parameterName`  do?
Answer: UPDATE TABLE <tablename> SET <COLUMN=VALUE> WHERE <CONDITION>
Example:
UPDATE TABLE teacher SET teacher_name='NSP' WHERE teacher_id='1'

Answer: try this.
UPDATE `database_name`.`table_name` SET `column_name`='value' WHERE `id`='1';

Comment: Welcome to Stack Overflow! Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* it addresses the question.  Without that, your answer has much less educational value - remember that you are answering the question for readers in the future, not just the person asking now!  Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply.
Answer: Some of the columns in MySQL have an "on update" clause, see:
mysql> SHOW COLUMNS FROM your_table_name;

I'm not sure how to update this but will post an edit when I find out.
Comment: If there is an "on update" it will be in the "Extra" column of the table you get when executing the above command.

Change One Cell's Data in mysql


Combine duplicate elements and sum the amount

Question: I have an array object with incomes, for any duplicate incomes I want to have a single record which has a sum of all duplicates.
This the array object

const incomes = [
  {
    incomeType: 'DIVIDEND',
    incomeSubType: 'RECEIPT',
    payerName: 'Employer',
    expiryDate: '2022-03-10',
    regularAmountCalculated: {
      value: 2500,
      currencyCode: 'AUD'
    },
    irregularAmountCalculated: null,
    bonusCalculated: {
      value: 200,
      currencyCode: 'AUD'
    }
  },
  {
    incomeType: 'DIVIDEND',
    incomeSubType: 'RECEIPT',
    payerName: 'Employer',
    expiryDate: '2022-03-10',
    regularAmountCalculated: {
      value: 2500,
      currencyCode: 'AUD'
    },
    irregularAmountCalculated: null,
    bonusCalculated: {
      value: 200,
      currencyCode: 'AUD'
    }
  }
];

I am expecting the output to have a only on record for Dividend and calculated amount as 5000.
Expected output

const incomes = [
  {
    incomeType: 'DIVIDEND',
    incomeSubType: 'RECEIPT',
    payerName: 'Employer 1',
    expiryDate: '2022-03-10',
    regularAmountCalculated: {
      value: 5000,
      currencyCode: 'AUD'
    },
    irregularAmountCalculated: null,
    bonusCalculated: {
      value: 200,
      currencyCode: 'AUD'
    }
  },
];

I have written:
const totals:any = [];
statementOfIncomes.forEach(x => {
  const obj = totals.find(o => o.incomeType === 'DIVIDEND');
  if (obj) {
    obj.regularAmountCalculated.value = obj.regularAmountCalculated.value + x.regularAmountCalculated?.value;
  } else {
    totals.push(x);
  }
});

The error I get is
ERROR TypeError: Cannot assign to read only property 'value' of object '[object Object]'
Comment: I have tried same code and it's working fine as per you expected output
Answer: I would suggest using a Map to store all unique incomes.
You have to loop over your incomes, check if the map already has an entry based on the incomeType. If not, add it to the map, else get the existing value and add the regularAmount to it.
Last you have to convert your map back to an Array.
This has a runtime of O(2n) instead of O(n^2) as stated in your first approach.
const map = new Map();

incomes.forEach((income) => {
  if (!map.has(income.incomeType)) {
    map.set(income.incomeType, income);
  } else {
    const existingIncome = map.get(income.incomeType);

    existingIncome.regularAmountCalculated.value += income.regularAmountCalculated.value;

    map.set(income.incomeType, existingIncome);
  }
});

const uniqueIncomes = Array.from(map, ([_key, value]) => value);

// [
//   {
//     incomeType: 'DIVIDEND',
//     incomeSubType: 'RECEIPT',
//     payerName: 'Employer',
//     expiryDate: '2022-03-10',
//     regularAmountCalculated: { value: 5000, currencyCode: 'AUD' },
//     irregularAmountCalculated: null,
//     bonusCalculated: { value: 200, currencyCode: 'AUD' },
//   },
// ];


Where can I find the points per game throughout many NBA seasons?

Question: Where can I find the points per game (of both teams) throughout many NBA seasons?
To illustrate my point, what I mean is something like:

2000/01 average points per NBA game: 200;
2001/02 average points per NBA game: 210;
2002/03 average points per NBA game: 205;

so on...
Answer: On basketball-reference.com you can find many stats on NBA matches.
In the colum Points in the Game section you can find data you need (see the picture below and use x2 coefficient)


When does commutativity imply associativity in a set of operators?

Question: This question got me wondering: suppose $S$ is a set of operators such that for all $x, y \in S$, $x(y) \in S$.
For any $x,y \in S$, we say that $x \equiv y$ iff for all $z \in S$: $$x(z) = y(z)$$
We say that $S$ is associative if, for any $x, y, z \in S$: $$x(y(z)) \equiv (x(y))(z)$$
Finally, we say $S$ is fully commutative iff, for any two ordered tuples $T_1 = (x_1,y_1,z_1,w_1,\cdots)$ and $T_2 = (x_2,y_2,z_2,w_2,\cdots)$, where all elements of both tuples $\in S$, and where $T_2$ is any reordering of $T_1$: $$x_1(y_1(z_1(w_1(\cdots)))) \equiv x_2(y_2(z_2(w_2(\cdots))))$$
For example, $a(b(c(c))) \equiv c(b(c(a))) \equiv b(c(c(a))) \equiv \cdots$ where $a,b,c \in S$
If we treat $S$ as a group isomorphic to $\mathbb{Z}$ acting multiplicatively, for example, we know $S$ is fully commutative based on the nice commutivity of integers, e.g. $$1(4(16(12))) = 16(12(1(4)))$$
My questions are as follows:

Suppose $S$ is fully commutative. Does this imply $S$ is also associative?
If the answer to (1) is 'yes', is there a proof accessible to somebody who knows absolutely nothing about category theory (except the fact that it seems to pop up in problems involving abstract algebra a lot)?
If the answer is 'no', does a reasonably simple (i.e. non-graduate-level math) counterexample exist? What additional conditions on $S$ are needed to guarantee associativity?
Answer: Yes, full commutativity implies associativity, and there is a simple proof.
$$
\begin{align}
x(y(z))
&=z(x(y))\tag{$T_1=(x,y,z),T_2=(z,x,y)$}
\\&=z(w)\tag{Let $w=x(y)$}
\\&=w(z)\tag{$T_1=(z,w),T_2=(w,z)$}
\\&=(x(y))(z)
\end{align}
$$

Side note: Usually an operator refers to a function $x:V\to V$ for some set $V$. If $x$ and $y$ are two operators, then $x(y)=x\circ y$ is the composition of these functions. In this case, any set $S$ of operators is automatically associative, since function composition is associative; no total commutativity assumption is necessary.
Comment: There are commutative, non-associative magmas: https://en.wikipedia.org/wiki/Commutative_magma