How can I enforce a minimum length for private messages?

Question: I previously asked how to enforce a minimum length for fields and received some great answers.
Now, I would like to enforce a minimum length for private messages only when it is the first message in a conversation (the private message module calls "threads" of messages conversations).
Use case: I don't want users to be able to send messages consisting only of "hey" or "hi"; thus, I need to enforce a minimum length for the first message.  However, once users are talking to one another, it is completely possible that a reply could be "yes" or "no", etc., so follow-up messages should not be limited in length.
Looking through the Privatemsg API, it looks like this might be able to be done with hook_privatemsg_message_validate(), but I'm not much of a coder and I'm at a loss about how to proceed from here.
Answer: You will need to create a custom module to use that hook it will allow you to run custom validation on top of the standard validation done by private msg.
A hook allows you to add functionality to a module without having to hack the module causing issues when the original module needs to be updated. When a module makes a hook available it allows other modules to perform additional processing during the execution flow in this case additional validation
more on hooks here - http://drupal.org/node/292
As a minimum your module will need a info file telling Drupal about your new module and a module file containing the hook with your extra validation code.
You can see what to put in your info file here - http://drupal.org/node/1075072
This page will guide you through setting up your module folder and naming http://drupal.org/node/1074362
Now you have your module structure set up you need to add the hook_privatemsg_message_validate() to the module file
function MYMODULENAME_privatemsg_message_validate($message) {

}

Replace MYMODULENAME with the name of your module.
From looking at this page it looks like the original message id becomes the thread id if its a reply http://api.worldempire.ch/api/privatemsg/privatemsg.api.php/group/message_hooks/7-2
array (
 'mid' => 3517, // message id, identifies a message
 'author' => 27, // author id
 'subject' => 'Message subject',
 'body' => 'Body of the message',
 'timestamp' => 351287003, // unix timestamp, creation time
 'is_new' => 0, // If the message has been read by the user
 'thread_id' => 3341, // thread id, this is actually the mid from the first                          message of the thread
)

My guess is you could do something like this to test:
if($message['thread_id'] == 0 || empty($message['thread_id']) && strlen($message['body']) < 25) {
form_set_error("Message must be n chars long");
}

I'm not that familiar with the module so you might need to investigate by printing out the message array to confirm this.
Putting it all together it would look something like this
function MYMODULENAME_privatemsg_message_validate($message) {
    // Uncomment next line print out the message array if you need to confirm what contiton to use for checking if first msg or not
    // echo print_r($message);
    if (empty($message->thread_id) && strlen($message->body) < 25 /* Change this to whatever length you want*/) {
        form_set_error('body][value', t('Message must be n chars long.'));
    }
}

Hopefully thats enough to get you started
Comment: Patches are welcome :) (I'm the maintainer of that module...)
Comment: You are right looks like that page of the api docs is out of date


How do I show expectations according to this distribution?

Question: Let $A$ (or $X$) be
$\log A \sim N(\mu,\sigma^2)$,   (lognormal distribution)
I have to show
$$E[A] = \exp[\mu + (\sigma^2/2)]\mbox{ and }E[A^2] = \exp[2\mu + 2\sigma^2].$$
Do I have to use mgf of the normal dist. ?
It is easy to show E[$A^2$] since it is the second order derivative of the mgf.
Answer: One may start with $\log A=\mu+\sigma Z$ and $Z$ standard gaussian. Thus $A^x=\mathrm e^{x\mu}\cdot\mathrm e^{x\sigma Z}$ for every real number $x$, hence $\mathbb E(A^x)=\mathrm e^{x\mu}\cdot\psi(x\sigma)$ where $\psi(t)=\mathbb E(\mathrm e^{t Z})$. Furthermore,
$$
\psi(t)=\int_{-\infty}^{+\infty}\mathrm e^{tz}\cdot\mathrm e^{-z^2/2}\frac{\mathrm dz}{\sqrt{2\pi}}=\mathrm e^{t^2/2}\int_{-\infty}^{+\infty}\mathrm e^{-(z-t)^2/2}\frac{\mathrm dz}{\sqrt{2\pi}}=\mathrm e^{t^2/2}.
$$
Hence, for every real number $x$,
$$
\mathbb E(A^x)=\mathrm e^{x\mu+x^2\sigma^2/2}.
$$
Answer: Yes, the mgf would be an easy way to do this. Just replace $t = 1$ and you get the mean.
Comment: But replacing with _t= 1 instead of t_ = 0 like in normal dist, gives E[_A_] = ($\mu$ + $\sigma^2$)exp[$\mu$ + ($\sigma^2$/2)]


Android get users location

Question: I am building an application which requires to get users location. Since I don't have very big experience with android, I am now reading information on how to get things working.
I have created a test application for learning purposes.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    latitudeField = (TextView) findViewById(R.id.latitude);
    longitudeField = (TextView) findViewById(R.id.longitude);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);

    if (location != null) {
        onLocationChanged(location);
    } else {
        latitudeField.setText("Latitute not available");
        longitudeField.setText("Longitude not available");
    }
}

@Override
public void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(provider, 400, 1, this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
}

@Override
public void onLocationChanged(Location location) {
    int lat = (int) (location.getLatitude());
    int lng = (int) (location.getLongitude());
    latitudeField.setText(String.valueOf(lat));
    longitudeField.setText(String.valueOf(lng));
}

But I read that using getLastKnownLocation() isn't the best way because if you put your phone to sleep, go to another city than you won't get your location updates.
What would you suggest to use instead?
Comment: you are updating the request. Then when you chnage the location the automatically trigger your onLocationChnaged(). So in that way your location latitude and longitude changed
Comment: Sorry, but I didn't quite understand you...
Comment: You have overridden the onLocationChanged method which triggers when your location changes. In other words you will get updates even after you phone has been put to sleep.
Comment: @Karlis, isn't your problem solved yet?
Answer: I will suggest you to use GPSTracker. Even though you put your mobile on sleep or  turn off/on your phone, this will give you absolute location as you require.

Android get users location


Usando Group By no SAS Guide

Question: Estou tendo problemas na utilização do comando GROUP BY, no SAS.
Por definição, o SAS só aceita o GROUP BY se for utilizado no SELECT uma função de sumarização. Até aí, ok. Rodando a Proc abaixo, o resultado sai corretamente:
proc sql;
    create table tabela_nova as
    select  nr_prpt_vcld,
            (max(ult_acl_atv)) as ult_acl_atv format ddmmyy10.
    from    tabela_base
    group by nr_prpt_vcld
    ;
quit;

nr_prpt_vcld    ult_acl_atv
23157           02/01/2014
27175           03/07/2014
29350           17/02/2014
Porém, acrescentando mais 2 campos ao SELECT, (conforme abaixo) a Proc retorna o seguinte resultado:
proc sql;
    create table tabela_nova as
    select  nr_prpt_vcld,
            nr_cvn_srvc,
            cd_cli_srvc,
            (max(ult_acl_atv)) as ult_acl_atv format ddmmyy10.
    from    tabela_base
    group by nr_prpt_vcld
    ;
quit;

nr_prpt_vcld   nrcvn_srvc   cd_cli_srvc   ult_acl_atv
    23157           140594        504217876  02/01/2014
    23157           147914        510003171  02/01/2014
    23157           153120        511284856  02/01/2014
    27175           140676        203940185  03/07/2014
    27175           141805        931007593  03/07/2014
    27175           150291        510955695  03/07/2014
    29350           137242        508122116  17/02/2014
    29350           145502        30139405   17/02/2014
Já tentei adicionar os campos novos ao GROUP BY, usar HAVING, mas nada resolveu. Ainda não consegui entender como funciona o GROUP BY no SAS.
Alguém pode me ajudar?
O resultado esperado é o seguinte:
nr_prpt_vcld   nr_cvn_srvc       cd_cli_srvc ult_acl_atv
    23157           153120        511284856  02/01/2014
    27175           150291        510955695  03/07/2014
    29350           137242        508122116  17/02/2014

Ou seja, os valores nr_cvn_srvc e cd_cli_srvc que estão na data mais recente (ult_acl_atv), agrupado pelo nr_prpt_vcld.
Comment: Parece que ele implicitamente adicionou os novos campos no `group by`, em vez de retornar um erro (o que, creio eu, seria o que uma consulta SQL num BD normal faria). A propósito, esse foi o resultado obtido, certo? Qual seria o resultado esperado?
Comment: Sugestão: edite sua pergunta acrescentando os detalhes relevantes, não tente postar como comentário. Se estiver com dificuldade na formatação, selecione o texto e use o botão "Amostra de código" (que se parece com isto: **{ }**), e ele ficará formatado como código (em fundo cinza, com fonte monoespaçada).
Answer: TL;DR - (Workaround) use subqueries:
select  t1.nr_prpt_vcld                               as nr_prpt_vcld,
        (select t2.nrcvn_srvc
             from tabela_base t2
             where t2.nr_prpt_vcld = t1.nr_prpt_vcld
             order by t2.ult_acl_atv desc
             limit 1
        )                                             as nrcvn_srvc,
        (select t2.cd_cli_srvc
             from tabela_base t2
             where t2.nr_prpt_vcld = t1.nr_prpt_vcld
             order by t2.ult_acl_atv desc
             limit 1
        )                                             as cd_cli_srvc,
        (max(t1.ult_acl_atv))                         as ult_acl_atv
    from    tabela_base t1
    group by t1.nr_prpt_vcld

Exemplo no SQLFiddle.

Tenho pouca familiaridade com o SAS, mas pelo que eu entendi, ele possui conformidade com os padrões SQL. Vou responder de forma mais didática, de modo que você consiga identificar onde pode estar errando e o que fazer para corrigir:
Visão geral sobre queries SQL
De forma abstrata, pode-se dizer que uma consulta executa os seguintes passos, nessa ordem:

Descobre a(s) tabela(s) a se consultar, fazendo as junções aplicáveis;
Ex.: from tabela_base
nr_prpt_vcld   nrcvn_srvc   cd_cli_srvc   ult_acl_atv foo
23157           140594        504217876  30/12/2013   bar
23157           147914        510003171  01/01/2014   bar
23157           153120        511284856  02/01/2014   bar
27175           140676        203940185  01/07/2014   bar
27175           141805        931007593  02/07/2014   bar
27175           150291        510955695  03/07/2014   bar
29350           137242        508122116  16/02/2014   bar
29350           145502        30139405   17/02/2014   bar
99999           999999        999999999  18/02/2014   baz

Filtra as linhas retornadas, conforme a condição where;
Ex.: where foo = bar
nr_prpt_vcld   nrcvn_srvc   cd_cli_srvc   ult_acl_atv foo
23157           140594        504217876  31/12/2013   bar
23157           147914        510003171  01/01/2014   bar
23157           153120        511284856  02/01/2014   bar
27175           140676        203940185  01/07/2014   bar
27175           141805        931007593  02/07/2014   bar
27175           150291        510955695  03/07/2014   bar
29350           137242        508122116  16/02/2014   bar
29350           145502        30139405   17/02/2014   bar
-----           ------        --------   ----------   baz (X)

Agrupa conforme o critério da cláusula group by;
Ex.: group by no_prpt_vcld
nr_prpt_vcld   nrcvn_srvc   cd_cli_srvc   ult_acl_atv foo  tupla de agrupamento

23157           140594        504217876  31/12/2013   bar \
23157           147914        510003171  01/01/2014   bar  (23157)
23157           153120        511284856  02/01/2014   bar /

27175           140676        203940185  01/07/2014   bar \
27175           141805        931007593  02/07/2014   bar  (27175)
27175           150291        510955695  03/07/2014   bar /

29350           137242        508122116  16/02/2014   bar \(29350)
29350           145502        30139405   17/02/2014   bar /

"Achata" os grupos, transformando cada um em uma linha só, acrescentando colunas de acordo com as funções de agregação
Ex.: (max(ult_acl_atv)) as ult_acl_atv
nr_prpt_vcld   nrcvn_srvc   cd_cli_srvc   ult_acl_atv foo
23157          [Achatado]   [Achatado]    02/01/2014  [Achatado]
27175          [Achatado]   [Achatado]    03/07/2014  [Achatado]
29350          [Achatado]   [Achatado]    17/02/2014  [Achatado]

Filtra de novo, agora as linhas "achatadas" (e não as originais)
Ex.: having ult_acl_atv < '06/06/2014' (sintaxe imprecisa)
nr_prpt_vcld   nrcvn_srvc   cd_cli_srvc   ult_acl_atv foo
23157          [Achatado]   [Achatado]    02/01/2014  [Achatado]
-----          ----------   ----------    03/07/2014  ---------- (X)
29350          [Achatado]   [Achatado]    17/02/2014  [Achatado]

Escolhe as colunas a retornar; só pode usar colunas agrupadas (i.e. que faziam parte do group by ou agregações de outras colunas (i.e. que tiveram algum valor definido após o "achatamento").
Ex.: select nr_prpt_vcld, (...) as ult_acl_atv
nr_prpt_vcld   ult_acl_atv
23157          02/01/2014
29350          17/02/2014

Como isso se aplica ao seu caso
Como você pode ver, não dá pra acrescentar as colunas nrcvn_srvc e cd_cli_srvc pois elas foram "achatadas" ao se pegar várias linhas da tabela e transformar em uma só. O máximo que você pode fazer, é agregar elas também, se for isso que você quer. Ex.:
select  nr_prpt_vcld,
        (min(nrcvn_srvc)) as nrcvn_srvc,
        (sum(cd_cli_srvc)) as cd_cli_srvc,
        (max(ult_acl_atv)) as ult_acl_atv format ddmmyy10.

    nr_prpt_vcld   nrcvn_srvc   cd_cli_srvc   ult_acl_atv
    23157          140594       1525505903    02/01/2014
    29350          137242       538261521     17/02/2014

Ou, adicionar uma (ou mais) delas no grupo - mas fazendo isso, o agrupamento será diferente. Ex.:
group by nr_prpt_vcld, nrcvn_srvc

    nr_prpt_vcld   nrcvn_srvc     cd_cli_srvc ult_acl_atv  foo           tupla de agrupamento

    23157           140594        [Achatado]  31/12/2013   [Achatado] => (23157,140594)

    23157           147914        [Achatado]  01/01/2014   [Achatado] => (23157,147914)

    23157           153120        [Achatado]  02/01/2014   [Achatado] => (23157,153120)

    27175           140676        [Achatado]  01/07/2014   [Achatado] => (27175,140676)

    27175           141805        [Achatado]  02/07/2014   [Achatado] => (27175,141805)

    27175           150291        [Achatado]  03/07/2014   [Achatado] => (27175,150291)

    29350           137242        [Achatado]  16/02/2014   [Achatado] => (29350,137242)

    29350           145502        [Achatado]  17/02/2014   [Achatado] => (29350,145502)

Etc. Se você acrescenta outros campos na cláusula group by, ele vai agrupar pela tupla de campos - sendo que cada combinação diferente dos mesmos vai gerar um agrupamento, que posteriormente será achatado e poderá ter seus valores agregador.
Normalmente, uma consulta tal como a que você fez geraria um erro no SQL. Mas aparentemente, o que o SAS fez foi acrescentar implicitamente os demais campos na condição de agrupamento, de modo que sua consulta foi feita como se o group by estivesse assim:
group by nr_prpt_vcld, nrcvn_srvc, cd_cli_srvc

De modo que somente linhas que tivessem esses 3 valores idênticos é que fariam parte do mesmo agrupamento. Se não existe mais de uma linha com essas condições, o resultado é como se ele não tivesse agrupado nada, simplesmente retornado cada linha separadamente...
Workaround
Não sei se o que você quer fazer é possível dentro da própria cláusula group by: obter o valor de uma coluna correspondente ao máximo de outra coluna. Um workaround seria usar duas subqueries, uma para cada coluna; em cada uma delas, pega-se o valor da coluna correta correspondente ao valor máximo da data, para um código específico:
select t2.nrcvn_srvc
    from tabela_base t2
    where t2.nr_prpt_vcld = ### um código fixo ###
    order by t2.ult_acl_atv desc
    limit 1

Isso é feito na seção select - quando o agrupamento já foi feito e se está montando a linha com os resultados. Ordena-se as linhas de forma descrescente pela data (de modo que a primeira será a mais recente), e se limita a quantidade de resultados a 1, de modo que só a maior delas será retornada. Pega-se o campo que você quer e usa-o como o valor da coluna:
select  t1.nr_prpt_vcld       as nr_prpt_vcld,
        (select ...)          as nrcvn_srvc,
        (select ...)          as cd_cli_srvc,
        (max(t1.ult_acl_atv)) as ult_acl_atv

Resultado final (note que dei um apelido para a tabela original):
select  t1.nr_prpt_vcld                               as nr_prpt_vcld,
        (select t2.nrcvn_srvc
             from tabela_base t2
             where t2.nr_prpt_vcld = t1.nr_prpt_vcld
             order by t2.ult_acl_atv desc
             limit 1
        )                                             as nrcvn_srvc,
        (select t2.cd_cli_srvc
             from tabela_base t2
             where t2.nr_prpt_vcld = t1.nr_prpt_vcld
             order by t2.ult_acl_atv desc
             limit 1
        )                                             as cd_cli_srvc,
        (max(t1.ult_acl_atv))                         as ult_acl_atv
    from    tabela_base t1
    group by t1.nr_prpt_vcld

Usando Group By no SAS Guide


Running a JAR from a bash script in a cronjob

Question: For some reason my cronjob is not working:
<code>4 20 * * * /home/ubuntu/db_backup/myScript.sh 1 > /home/ubuntu/db_backup/cron_log.txt
</code>
And my bash script looks like this:
<code>#! /bin/bash
mysqldump -h anotherhost -P 3306 -u usen -pmypass --all-databases > $1.sql
java -jar myJar.jar param1 $1.sql
</code>
So the jar file takes in 2 parameters, the first one i want always to be the same, the second one comes from the first bash parameter. Inside /var/spool/mail/ubuntu I see this error:
Unable to access jarfile myJar.jar
I set the crontab up under user: ubuntu
owner and group of the jar file is ubuntu and it has octal permissions of 700.
What am I doing wrong?
Answer: Try with full paths:
<code>#! /bin/bash
mysqldump -h anotherhost -P 3306 -u usen -pmypass --all-databases > /path/$1.sql
java -jar /path/myJar.jar param1 /path/$1.sql
</code>
Comment: Thank you for the response, I will try this, do you think I could try full path for the jar file too?
Answer: You should use absolute paths! I think neither the jar-file nor the sql-file can be found...
<code>#! /bin/bash
SQLFILE=/path/to/file/$1.sql
mysqldump -h anotherhost -P 3306 -u usen -pmypass --all-databases > $SQLFILE
java -jar /path/to/myJar.jar param1 $SQLFILE
</code>
Comment: Yep it works, I'm afraid I'll have to accept hmontoliu's answer since it was a bit quicker +1 tho cheers!


www.text not showing complete data in android

Question: I'm using the following code to get the text from a web page:
    private IEnumerator FetchText() {
        WWW www = new WWW(URL);

        yield return www;

        if(www.error == null) {
            myText.text = www.text.Length.ToString();
        }
        ...
    }

When I run this in Unity, I get 185616 characters long string. But when I run this in android device, I get only 47133 characters. Is it because that web page behaves differently in Windows and Android? If yes, how can I fetch the same content from android as I'd be getting from desktop PC.
Thanks.
Comment: Its very likely that the problem is the web-site/webservice detecting your User-Agent. They can also use other headers to change the reponse. Does this code work in the Editor?
Comment: Yes, it works in Editor.
Comment: Are you allowed to post the url? If so, post it like it is.
Comment: I can't post the url but I can confirm that when I open that page in my PC, the view is different. And when I open that in my android phone, the page is much smaller with different view.
Comment: Does the url contain a username and password? If not then the problem is likely what [tier1](http://stackoverflow.com/a/41348108/3785314) said.
Comment: No, there is no authentication required to access the page. Can you help me to implement @tier1's solution in Unity? I am not sure how to set headers in Unity.
Comment: Try checking if `www.isDone` is actually `true`, i do expect it to be true after the yield, but i have seen cases where it is not.
Comment: You can check the implementation. If that doesn't work then the problem is something I cannot help with since I don't have the url and therefore cannot test it.
Comment: @Paradox Thanks for your advice, I'll check that in a while.
Answer: It's possible that the URL you are trying to fetch is detecting your user agent and sending you to some kind of mobile site with a smaller response body.
I'm not very familiar with the library you're using but you might want to try manually setting the User-Agent header.
For example:

User-Agent: Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko
Comment: I'll try that and will get back to you.
Answer: Implementation of tier1's answer.
POST Request:
private IEnumerator FetchText()
{
    string URL = "www.yahoo.com";
    string userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";

    Dictionary<string, string> headers = new Dictionary<string, string>();
    headers.Add("User-Agent", userAgent);
    string postData = "test";
    string data = "data=" + postData;

    WWW www = new WWW(URL, Encoding.UTF8.GetBytes(data), headers);
    yield return www;

    if (string.IsNullOrEmpty(www.error))
    {
        //myText.text = www.text.Length.ToString();
        Debug.Log("Got: " + www.text);
    }
    else
    {
        Debug.Log("Error: " + www.error);
    }
}

GET Request:
Setting the WWW byte[] postData parameter to null will make it a GET request.
private IEnumerator FetchText()
{

    string userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
    string URL = "www.yahoo.com";

    Dictionary<string, string> headers = new Dictionary<string, string>();
    headers.Add("User-Agent", userAgent);

    WWW www = new WWW(URL, null, headers);
    yield return www;

    if (string.IsNullOrEmpty(www.error))
    {
        //myText.text = www.text.Length.ToString();
        Debug.Log("Got: " + www.text);
    }
    else
    {
        Debug.Log("Error: " + www.error);
    }
}

According your original code, you need the GET request method. This will masquerade as request from a Chrome browser. You can get your User-Agent from here.
Comment: I'll try it now and will let you know.
Comment: I think you might help me with that: http://stackoverflow.com/questions/41885413/extract-byte-arrays-of-individual-frames-from-byte-array-of-a-gif-file


How to compute this definite improper integral using the Residue Theorem??

Question: I have been trying to compute this integral:
$$
\int_0^\infty \frac{\log^{2}\left({\left\vert{\tan\left({x}\right)}\right\vert}\right)}{1 + x^{2}}\,\mathrm{d}x
$$
using the Residue Theorem but have not been successful.
I tried to use the classical upper semi-circular contour, but realized that it would not work because $\log^{2}\left({\left\vert{\tan\left({x}\right)}\right\vert}\right)$ has singularities on the contour and is therefore not holomorphic on/in that contour.
Does anybody have any ideas of what kind of contour I should use?
I don't think we have to worry about the branches of the logarithm function because it's argument will always be real. Is that correct?
Answer: Let us consider a general family of integrals
$$ I(a) = \int_{0}^{\infty} \frac{\log^2 \left| \tan(x/2) \right|}{a^2 + x^2} \, dx. $$
Notice that OP's integral equals $2I(2)$ by a simple substitution. Now we make the following very simple observation:
$$ \forall x \in \mathbb{R} \ : \quad
\log^2 \left| \tan(x/2) \right|
= \operatorname{Re}\left[ \log(\tan (x/2)) \log(\tan(-x/2)) \right]. $$
By this observation and symmetry, we find that
\begin{align*}
I(a)
&= \frac{1}{2} \operatorname{Re}\left[  \int_{-\infty}^{\infty} \frac{1}{a^2 + x^2} \log\left( i \frac{1 - e^{ix}}{1 + e^{ix}} \right) \log\left( -i \frac{1 - e^{ix}}{1 + e^{ix}} \right) \, dx \right] \\
&= \operatorname{Re}\left[ \pi i \mathop{\underset{z=ia}{\mathrm{Res}}} \frac{1}{a^2 + z^2} \log\left( i \frac{1 - e^{iz}}{1 + e^{iz}} \right) \log\left( -i \frac{1 - e^{iz}}{1 + e^{iz}} \right) \right] \\
&= \operatorname{Re}\left[ \frac{\pi}{2a}\log\left( i \frac{1 - e^{-a}}{1 + e^{-a}} \right) \log\left( -i \frac{1 - e^{-a}}{1 + e^{-a}} \right) \right] \\
&= \frac{\pi}{2a} \left( \frac{\pi^2}{4} + \log^2 \left( \tanh(a/2) \right) \right).
\end{align*}
In the second line, we utilized the fact that the integrand extends to a holomorphic function on the upper half-plane $\mathbb{H}$ which vanishes sufficiently fast near $\infty \in \partial \mathbb{H}$ along appropriately chosen contours.


Me podem corrigir este css por favor!

Question: Usei CSS deste link, mas deram muitos erros:
Link 1 Link 2 Link 3
import "bourbon";

break-medium: 980px;
nav-width: 240px;
site-width: 1600px;

@import url(https://fonts.googleapis.com/css?family=Open+Sans:700,300,600,800,400);

html,
body {
  margin: 0;
  padding: 0;
  background: lighten(#3a4043, 15%);
  font-family: 'Open Sans', sans-serif;
}

.l-site {
  margin: 0 auto;
  max-width: site-width;
  position: relative;
  z-index: 1;

  before {
    content: "";
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    width: 50%;
    display: block;
    background: #3a4043;
    z-index: 1;
  }
}

.l-page {
  position: relative;
  margin-left: nav-width;
  background: #fff;
  z-index: 2;
  box-shadow: 1px 0 25px rgba(0,0,0,0.25);
  @include transition(0.35s);
}

.l-nav {
  position: absolute;
  width: nav-width;
  display: block;
  background: #3a4043;
  top: 0;
  bottom: 0;
  left: 0;
  z-index: 3;
}

.band {
  h1 {
    margin: 0;
    padding: 0 0 10px;
    color: #fff;
    font-size: 32px;
  }

  p {
    margin: 0;
    padding: 0;
    color: #fff;
    font-size: 17px;
  }
}

.band-container {
  left: 0;
  right: 0;
  margin: 0 auto;
  min-height: 85vh;
  max-width: 960px;
  display: table;
  position: relative;
  padding: 0 3em;
}

.band-inner {
  display: table-cell;
  vertical-align: middle;
  padding: 3em 0 4em;
}

.band-a {
  background: #69D2E7;
}

.band-b {
  background: #F9D423;
}

.band-c {
  background: #F38630;
}

.band-d {
  background: #FF4E50;
}

.nav {
  width: (nav-width - 60);
  position: fixed;
  top: 0;
  bottom: 0;
  margin: 0;
  padding: 30px;
  overflow: auto;

  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li {
    margin: 0;
    padding: 0;
    @include transition(0.25s);
  }

  a {
    color: #fff;
    text-decoration: none;
    font-size: 20px;
    font-weight: 800;
    display: block;
    padding: 10px 0;
  }

  .nav-primary {
    opacity: 1;

    :hover {
      opacity: 0.7;
    }
  }

  .nav-secondary {
    opacity: 0.4;

    :hover {
      opacity: 0.7;
    }
  }
}

.menu {
  display: none;
  position: fixed;
  top: 25px;
  left: 1.5em;
  width: 24px;
  height: 24px;
  cursor: pointer;
  z-index: 10;

  hover {
    .menu-hamburger:before,
    .menu-hamburger:after {
      width: 24px;
    }
  }

 .is-active {
    .menu-hamburger {
      background: none;
    }
    .menu-hamburger:before,
    .menu-hamburger:after {
      top: 0;
      width: 24px;
      -webkit-transform: rotate(45deg);
          -ms-transform: rotate(45deg);
              transform: rotate(45deg);
    }
    .menu-hamburger:after {
      -webkit-transform: rotate(-45deg);
          -ms-transform: rotate(-45deg);
              transform: rotate(-45deg);
    }
    .menu-hamburger:hover {
      -webkit-transform: scale(1.2);
          -ms-transform: scale(1.2);
              transform: scale(1.2);
    }
  }
}

.menu-hamburger {
  position: relative;
  width: 24px;
  height: 4px;
  margin: 10px 0;
  background: #fff;
  border-radius: 4px;
  transition: all 300ms cubic-bezier(0.68, -0.55, 0.265, 1.55);

  before,
  after {
    content: '';
    display: block;
    width: 24px;
    height: 4px;
    background: #fff;
    position: absolute;
    border-radius: 4px;
    transition: all 300ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
  }
  before {
    top: -8px;
    left: 0;
    width: 22px;
  }

  :after {
    top: 8px;
    width: 16px;
    left: 0;
  }
}

@media screen and (max-width: break-medium) {
  .menu {
    display: block;
  }

  .l-site {
    .is-open {
      overflow: hidden;

      .l-page {
        @include transform(translateX(nav-width));
      }
    }
  }

  .l-page {
    margin-left: 0;
    z-index: 3;
  }

  .l-nav {
    z-index: 2;
  }

  .band-container {
    padding: 0 1.5em;
  }
}

Comment: [Link](http://prntscr.com/n91ykh) [Link](http://prntscr.com/n91z2v) [Link](http://prntscr.com/n91za1)
Comment: Poderia incluir no post um print do erro que ele acusa?
Answer: O problema aí é que você não está fechando as chaves {}. Como você disse que é CSS, não pode haver elementos dentro de outros elementos, desta maneria que está escrito, só é aceito em CSS pré-processados como LESS ou SASS por exemplo.
ERRADO
.band {
   h1 {                   <- PROBLEMA AQUI
     margin: 0;
     padding: 0 0 10px;
     color: #fff;
     font-size: 32px;
   }

   p {
    margin: 0;
    padding: 0;
    color: #fff;
    font-size: 17px;
  }
}

CORRETO
h1 {                      <- ELEMENTO ABRE
   margin: 0;
   padding: 0 0 10px;
   color: #fff;
   font-size: 32px;
}                          <- ELEMENTO FECHA

p {                        <- ELEMENTO ABRE
  margin: 0;
  padding: 0;
  color: #fff;
  font-size: 17px;
}                          <- ELEMENTO FECHA

Comment: O código não está errado, só não é CSS. `@include transition(0.35s);` é um mixin. Você copiou esse código que algum lugar e não está sabendo o que é. tentar colocar seu código num [compilador online](http://beautifytools.com/scss-compiler.php) pra ter o CSS pronto.
Comment: E está escrito que é SCSS, faltou atenção.
Comment: Você está aninhando regras umas dentro das outras e isso não é possível de se fazer com CSS.
Tem certeza que você escreveu CSS, não seria SCSS?
Comment: José, nesse mesmo link que você acabou de mandar você pode clicar no menu do CSS e clicar em **View compiled CSS**.
Comment: é só isso??????
Comment: olhe, eu fui ver ao meu código e todas as chaves estão fechadas!
Comment: não, quero css, me podia mandar o código certo, por favor?
Comment: obrigado mas agora, o que faço aqui:
 ```
   break-medium: 980px;
nav-width: 240px;
site-width: 1600px;
```e aqui
 ```
     hover {
    .menu-hamburger:before,
    .menu-hamburger:after {
      width: 24px;
    }
  }``
Comment: Você provavelmente está escrevendo em algum pré-processador, não estou entendendo pq quer reescreve-lo em CSS, pois isso será compilado e transformado em CSS.
Comment: Está a ver este link [Link](https://codepen.io/adriangyuricska/pen/bNXaBj) a parte de css é a que eu tirei, mas quando eu passei para o visual studio code, começou a dar erros!
Comment: ok, obrigado!!!
Comment: mas espere, eu tenho de tirar os & e $ do código?
Comment: O que é que eu tenho de fazer para tirar o mixin?

Me podem corrigir este css por favor!


Drupal ignores my table definition when installing a module

Question: What am I doing wrong? This is what I have in commerce_xpay.install.
function commerce_xpay_schema() {
    $schema = array();

    $schema['commerce_xpay_ipn'] = array(
            'description' => 'Stores processed IPNs.',
            'fields' => array(
                    'ipn_id' => array(
                            'description' => 'Serial numeric ID of the IPN in the local database.',
                            'type' => 'serial',
                            'unsigned' => TRUE,
                            'not null' => TRUE,
                    ),
                    'transaction_id' => array(
                            'description' => 'The X-Pay transaction ID.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'terminal_id' => array(
                            'description' => 'The X-Pay terminal id',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'response' => array(
                            'description' => 'The response of the server',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'payer_email' => array(
                            'description' => 'The e-mail of the payer.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'transaction_date' => array(
                            'description' => 'The date of the transaction.',
                            'type' => 'date',
                            'not null' => TRUE,
                    ),
                    'card_type' => array(
                            'description' => 'The type of the card used in the transaction.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'amount' => array(
                            'description' => 'The amount of the transaction.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'transaction_type' => array(
                            'description' => 'The type of the transaction.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'mac' => array(
                            'description' => 'The amount of the transaction.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'currency' => array(
                            'description' => 'The currency used for the transaction.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'order_id' => array(
                            'description' => 'The order ID the payment belongs to.',
                            'type' => 'int',
                            'unsigned' => TRUE,
                            'not null' => TRUE,
                            'default' => 0,
                    ),
                    'txn_id' => array(
                            'description' => 'The payment transaction ID the payment belongs to.',
                            'type' => 'int',
                            'unsigned' => TRUE,
                            'not null' => TRUE,
                            'default' => 0,
                    ),
                    'created' => array(
                            'description' => 'The Unix timestamp when the IPN was received.',
                            'type' => 'int',
                            'not null' => TRUE,
                            'default' => 0,
                    ),
                    'changed' => array(
                            'description' => 'The Unix timestamp when the IPN was last updated.',
                            'type' => 'int',
                            'not null' => TRUE,
                            'default' => 0,
                    ),
                    'test_ipn' => array(
                            'description' => 'Boolean indicating whether or not this was a test IPN sent by the Sandbox.',
                            'type' => 'int',
                            'size' => 'tiny',
                            'not null' => TRUE,
                            'default' => 0,
                    ),
            ),
            'primary key' => array('ipn_id'),
            'foreign keys' => array(
                    'order_id' => array(
                            'table' => 'commerce_order',
                            'columns'=> array('order_id' => 'order_id'),
                    ),
                    'txn_id' => array(
                            'table' => 'commerce_payment_transaction',
                            'columns'=> array('payment_id' => 'payment_id'),
                    ),
            ),
            'indexes' => array(
                    'transaction_id' => array('transaction_id'),
            ),
    );

    return $schema;
}

Comment: Do you completely disable *and* uninstall the module between your attempts? Your schema definition will not be called again once your module has been installed.
Comment: @marcvangend i simply disable the module withouth uninstalling it, so this might be the issue. Since i'm developing a custom module, to simulate an install i need to package the module and install it through the interface?
Answer: It's hard to know without seeing an error message, but at first glance I'd guess it's because of the transaction_date column.
date is not a valid data type in Drupal 7 (see Data Types). You can either use an int column and store a UNIX timestamp, or use the mysql_type property instead of type, and set that datetime.
Comment: This is true, there is no error message but that is because i wasn't uninstalling the module before re-installing it i'm afraid
Comment: Ah ok! I'd advise installing the Devel module...then you can go to http://mysite.com/devel/reinstall and get your module re-installed automatically
Comment: Perfect, everything works correctly.


Sorting dynamic Array of Array of Double in Delphi

Question: I create a dynamic matrix in Delphi:
AMatrix : Array of Array of Double;

and let's suppose that I initialize it this way.
SetLength(Amatrix,1000,10);

And fill this matrix using some values.  Now, I want to sort the 1000 items on the first dimension on a specific value stored in a specific position on the second dimension (from 0 to 9).
Is there a way to create a TComparer that can be applied directly on the Amatrix without the need to create other data structures (TList or TArray)?
Comment: As far as I know rearranging these kind of arrays requires a lot of memory copying while moving entries from one point in to array to another. If you dont need to soort the actual array, but only need a sorted reference list tothe data in the array I can post a nice example
Comment: Yes, I do know how to create arrays, and I did wrote quicksort, insertion sorts, and all kinds of sorting in the past.  I worked a little bit with TComparer but could not find the way to create a TComparer to sort an dynamic Array of Array
Comment: I can perfectly understand the question and the problem behind it. It should be reopened to allow suitable answers.
Answer:
Is there a way to create a TComparer<T> that can be applied directly on [a variable of type array of array of Double] without the need to create other data structures (TList or TArray)?

Let's try it, but we'll use integers for simplicity:
program FailedAttempt;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils, Math, Generics.Defaults, Generics.Collections;

var
  A: array of array of Integer;

begin

  A :=
    [
      [5, 2, 1, 3, 6],
      [1, 2, 6, 3, 2],
      [1, 6, 7, 8, 3],
      [5, 7, 4, 2, 1],
      [0, 4, 9, 0, 5],
      [4, 1, 8, 9, 6]
    ];

  TArray.Sort<array of Integer>(A,
    TComparer<array of Integer>.Construct(
      function(const Left, Right: array of Integer): Integer
      begin
        if Left[2] < Right[2] then
          Result := -1
        else if Left[2] > Right[2] then
          Result := +1
        else
          Result := 0;
      end
    )
  );

  for var i := 0 to High(A) do
  begin
    Writeln;
    for var j := 0 to High(A[i]) do
      Write(A[i, j]);
  end;

  Readln;

end.

Unfortunately, this won't compile, since array of Integer isn't a valid type you can use as T. Notice how this is just like how you cannot use array of Integer as the return type of a function. And the solution is the same, too: Create a type defined as array of Integer.
program Solution1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils, Math, Generics.Defaults, Generics.Collections;

type
  TIntArray = array of Integer;

var
  A: array of TIntArray;

begin

  A :=
    [
      [5, 2, 1, 3, 6],
      [1, 2, 6, 3, 2],
      [1, 6, 7, 8, 3],
      [5, 7, 4, 2, 1],
      [0, 4, 9, 0, 5],
      [4, 1, 8, 9, 6]
    ];

  TArray.Sort<TIntArray>(A,
    TComparer<TIntArray>.Construct(
      function(const Left, Right: TIntArray): Integer
      begin
        if Left[2] < Right[2] then
          Result := -1
        else if Left[2] > Right[2] then
          Result := +1
        else
          Result := 0;
      end
    )
  );

  for var i := 0 to High(A) do
  begin
    Writeln;
    for var j := 0 to High(A[i]) do
      Write(A[i, j]);
  end;

  Readln;

end.

But in modern versions of Delphi, you don't need to create your own type (and, indeed, that is a bad idea, since different such types are not compatible). Instead, just use TArray<Integer> which is indeed defined as array of Integer -- this is a dynamic array of integers, just like your array of Integer:
program Solution2;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils, Math, Generics.Defaults, Generics.Collections;

var
  A: array of TArray<Integer>;

begin

  A :=
    [
      [5, 2, 1, 3, 6],
      [1, 2, 6, 3, 2],
      [1, 6, 7, 8, 3],
      [5, 7, 4, 2, 1],
      [0, 4, 9, 0, 5],
      [4, 1, 8, 9, 6]
    ];

  TArray.Sort<TArray<Integer>>(A,
    TComparer<TArray<Integer>>.Construct(
      function(const Left, Right: TArray<Integer>): Integer
      begin
        if Left[2] < Right[2] then
          Result := -1
        else if Left[2] > Right[2] then
          Result := +1
        else
          Result := 0;
      end
    )
  );

  for var i := 0 to High(A) do
  begin
    Writeln;
    for var j := 0 to High(A[i]) do
      Write(A[i, j]);
  end;

  Readln;

end.

If you really cannot change the definition of A, you can use casting:
program Solution3;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils, Math, Generics.Defaults, Generics.Collections;

var
  A: array of array of Integer;

begin

  A :=
    [
      [5, 2, 1, 3, 6],
      [1, 2, 6, 3, 2],
      [1, 6, 7, 8, 3],
      [5, 7, 4, 2, 1],
      [0, 4, 9, 0, 5],
      [4, 1, 8, 9, 6]
    ];

  TArray.Sort<TArray<Integer>>(TArray<TArray<Integer>>(A),
    TComparer<TArray<Integer>>.Construct(
      function(const Left, Right: TArray<Integer>): Integer
      begin
        if Left[2] < Right[2] then
          Result := -1
        else if Left[2] > Right[2] then
          Result := +1
        else
          Result := 0;
      end
    )
  );

  for var i := 0 to High(A) do
  begin
    Writeln;
    for var j := 0 to High(A[i]) do
      Write(A[i, j]);
  end;

  Readln;

end.

Finally, I should also point out the obvious: it is possible to sort your data without using a TComparer<T>. (Indeed, you were forced to do so before generics were introduced in Delphi 2009.)
Comment: Thanks!  This is exactly what I am looking for. Will try to study it a little bit, but it works great.
Comment: What does that CompareValue overload do about the epsilon argument?
Comment: @DavidHeffernan: In my example code I use integers, so there is no epsilon argument. If you use floating-point numbers, the default value `Epsilon = 0.0` will be used. This doesn't mean that the actual comparison uses `0.0` as the epsilon; instead, a fairly sensible default value will be used. Specifically, `CompareValue` passes `Epsilon` to `SameValue` which will replace `Epsilon`, if `0.0`, by `Max(Min(Abs(A), Abs(B)) * DoubleResolution, DoubleResolution)` if you use doubles. `DoubleResolution` is defined as `1E-12`.
Comment: Of course one's particular application might require some other epsilon, or some other kind of comparison altogether.
Comment: @Andreas That function is completely inappropriate to use for ordering. It will lead to access violations since the implied equality relation will not be transitive.
Comment: @DavidHeffernan: I agree, but in the integer case it is transitive. (And whether or not lack of transitivity leads to AVs depends on the particular algorithm used.)
Comment: The question is about floating point, and the sort algo that your answer uses requires a transitive relation. So, no, it doesn't depend. The operator you are looking for is classic less than, greater than and equals.
Comment: @DavidHeffernan: Yes, I automatically transformed the Q from `array of array of Double` to `array of array of Integer` in my head because to me the core issue was about the type system and dynamic arrays, not `Double`s, and I always try to find a problem in its "purest" form. But you are of course right that the original Q was about double and that my original A -- although perfectly correct -- would likely fool readers into doing something wrong. You are right absolutely right about that.
Answer: Using @R.Hoeck idea I wrote a simple demo program which create a two dimensions array of double, fill it with random data and sort it using a given column as key.
Sorting is done by creating a list of index/value for the column and then sorting the list.
After sorting, data from unsorted array is copied to another array which will become sorted.
unit MatrixDemoMain;

interface

uses
  Winapi.Windows, Winapi.Messages,
  System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
  System.Generics.Defaults,
  System.Generics.Collections;

type
    TMyRecord = record
        Index : Integer;
        Value : Double;
    end;
    TDynArray2OfDouble = array of array of Double;

    TForm1 = class(TForm)
        Button1: TButton;
        Memo1: TMemo;
        procedure Button1Click(Sender: TObject);
    private
        procedure DisplayArray(const Title : String;
                               const Arr   : TDynArray2OfDouble);
    end;

var
    Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
    AMatrix      : TDynArray2OfDouble;
    SortedMatrix : TDynArray2OfDouble;
    I, J         : Integer;
    SortCol      : Integer;
    Rec          : TMyRecord;
    List         : TList<TMyRecord>;
begin
    // Give dimension to unsorted array
    SetLength(AMatrix, 10, 3);
    // Give dimension to the sorted array
    SetLength(SortedMatrix, High(AMatrix) + 1, High(AMatrix[0]) + 1);
    // Select column to use as sort key
    SortCol := 2;

    // Fill matrix with random data
    for I := 0 to High(AMatrix) do begin
        for J := 0 to High(AMatrix[0]) do
            AMatrix[I, J] := Random(1000);
    end;
    DisplayArray('Unsorted:', AMatrix);

    // Create a list to sort data
    List := TList<TMyRecord>.Create;
    try
        for I := 0 to High(AMatrix) do begin
            Rec.Index := I;
            Rec.Value := AMatrix[I, SortCol];
            List.Add(Rec);
        end;
        // Sort the list
        List.Sort(TComparer<TMyRecord>.Construct(
                    function(const Left, Right: TMyRecord): Integer
                    begin
                        if Left.Value = Right.Value then
                            Result := 0
                        else if Left.Value > Right.Value then
                            Result := 1
                        else
                            Result := -1;
                    end)
                  );

        // Copy data from unsorted matrix using sorted list
        for I := 0 to High(AMatrix) do
            SortedMatrix[I] := AMatrix[List[I].Index];

        DisplayArray('Sorted on column ' + SortCol.ToString, SortedMatrix);
    finally
        FreeAndNil(List);
    end;
end;

// This procedure will display an array into the memo
procedure TForm1.DisplayArray(
    const Title : String;
    const Arr   : TDynArray2OfDouble);
var
    I, J    : Integer;
    Buf     : String;
begin
    Memo1.Lines.Add(Title);
    for I := 0 to High(Arr) do begin
        Buf := I.ToString + ') ';
        for J := 0 to High(Arr[0]) do
            Buf := Buf + Arr[I, J].ToString + '  ';
        Memo1.Lines.Add(Buf);
    end;
end;

end.

Running the demo will display this result in the memo:
Unsorted:
0) 293  547  16
1) 238  503  543
2) 428  950  663
3) 150  444  739
4) 160  388  373
5) 945  382  417
6) 863  818  392
7) 344  131  617
8) 91  458  330
9) 370  717  191
Sorted on column 2
0) 293  547  16
1) 370  717  191
2) 91  458  330
3) 160  388  373
4) 863  818  392
5) 945  382  417
6) 238  503  543
7) 344  131  617
8) 428  950  663
9) 150  444  739

Comment: Well, I was looking for a way to sort the matrix directly without the need to use an external index or a second matrix, just like one could do on a simple dynamic array,  In other word, I would like to create a TComparer that would be applied directly on the Array of Array.
Comment: @NormandP. Then it is trivial... and very inefficient as R.Hoeck said because large chunk of data will be moved around as the sort progress. The code will look simpler but performance will drop.
Comment: If needed, I will compare performances on large matrices and may end up with a more trivial solution or go back to my previous implementation (which involves sorting pointers of rows). I cannot duplicate the matrix without the risk of "out of memory" errors.  I often deal with huge matrices.
Comment: "I often deal with huge matrices" Maybe "array of array of double" is not the best data representation if performance matters. Everything depends on what operation you need to do. btw: I duplicated the matrix after sorting to simplify as I understood your problem was sorting not matrix handling. But of course after sorting, the list can be use to swap rows instead of copying it.


How can I get a less directional sound from a loudspeaker?

Question: Normally I play on stage with my pedalboard DI'ed straight in to the desk and use a stagefront wedge monitor for all my sound but some venues don't work like this. In these cases I use the standard Marshall stack behind me. Now, I like the sound of a Marshall, but if it is too low or off to one side the frequency rolloff makes it very hard to hear some of the higher frequencies.  I have the same problem in practice, where I use a small Marshall combo amp: it is at floor level so unless I angle it right up, I only hear the bass frequencies.
The obvious solution is to stick with what works - angled monitors - or possibly to buy earpieces, but are there any other trick of the trade folks use to get around the problem?
Answer: Although some people would disagree to it's very existence, beaming is something you aren't really going to be able to properly tame. It's the nature a speaker cone to "beam" and people sell some nifty little gadgets that are supposed to fix the problem. Those gadgets may help you out a little bit, and as a matter of fact my friends old Matchless DC-30 has a similar beam blocking design built directly into the frame of the amplifier, but in the end you can't completely get rid of it. Especially at high volumes.
Marshall amps are just fine on the highs. Trust me, I've lost some of my hearing because of them ;). What's likely happening is that you are hearing the bass frequencies more due to the directionality of the speakers. Bass frequencies tend to roll off the outside of the cone and spread out at a wide angle, while all of the middle and high frequencies are being 'beamed' outward from the center at a much narrower angle relative to the axis of the cone. I have read articles where guys say this isn't how it works, but in the end I'll trust my ears first. Since the amplifier is at a lower elevation than your head, you're hearing the frequencies that more readily spread at a wider 'view angle.'** Stick your head down in front of the speaker (with the volume low mind you) and play a bit. You'll hear something 100% different that your usual stage mix. This, among many other more obvious reasons, is why people mike their cabinets and combos in isolation away from the stage. It reduces stage volume--which makes the engineer types happy--and allows for more of the true sound of the combo/cabinet picked up by your mike of choice to saturate the PA.
The ways I used to get around beaming (when I had to) were low volume + floor wedges or in-ear monitors with the amplifier isolated and properly miked--and really that's the industry standard way. Not many professional folks are playing with working half or full stacks on stage these days; it usually just serves to piss the sound engineer of proper. The problem with floor wedges is they can get really muddy, especially if you don't do a thorough sound check. In this case definitely work with the engineer at the venue to get a good mix that you're happy with. Ideally, you'd be using in-ear monitors with your own separate channel. There's really no better way to play once you get used to them. With wedges you have to stay glued to the 'view angle'** of your monitor or you loose yourself, and in-ears generally fix that problem. The only thing you have to worry about there is a dead battery :D.
If in-ears aren't an option, then when you're setting up for a gig ask whoever owns the equipment if you can isolate the amp and mike it. If they won't let you move it, then just turn it such that if faces away from the stage, mike it, get a proper monitor mix, and you're off to the races. Beaming will also kill your crowd's hearing--so this will do the naive kids that like to stand directly in front of very loud speakers a favor their mother will thank you for.
If miking and mixing to your own monitor mix isn't an option then you are in a less than ideal situation so simply make the best of it and rock on. Angling the cabinet can help, but it still won't get you as good a mix as wedges or in-ears could.
** You can think of the way that sound spreads from a speaker cone just like the view angle on an old projection television. As you move past, say 180 degrees, the picture goes away. Same think with a speaker. As you move past a certain angle relative to the center of the cone some frequencies will disappear.
Comment: Also (as I understand it) high frequency sounds are more directional than low frequency sounds by their nature, which is a phenomenon independent of speaker/mic beaming.
Answer: The Jay-Mitchell-Donut seems to work quite well. Haven't tried it myself though, but may do so in the near future.
Comment: I totally have the acoustic foam to try this out. I bought it a year ago, but it has remained on my project to-do list. Ah the evils of corporate America keeping the good musician down by burning all his time :P.
Comment: +1 if for anything but the link to TGP :P. I think this is another one of those topics in Guitardom where there is conflicting information on the web. That site says that speakers don't beam, while Weber's site (who has been making speakers for years) does. So, take it with a grain of salt.
Answer: I have a 40-50w tube openback combo with a 98dB 12 inch speaker. It is loud but very directional even placed on the floor.
In the rehersal room i have it standing on top of a unused small 15" bass cab and that works well. Live though on a small crowded stage placed on the floor i have to play far too loud in able to hear myself.
12" and 15" are very directional. A PA speaker with a 1" driver and a 12" will have its crossover at roughly 2 kHz. The frequncies you see from a guitar speaker from 2kHz is far too beamy.
The 10" inch is slightly getter in this regard. It is less bassy but adding 4 of them like a fender super reverb or bassman works well.
Not many smaller speaker quality cabs available. Blackstar makes a small 4X8 closed back cab. Two of them stacked vertically would give you a big but less directional sound.
Answer: There's no way for me to know about your rehearsal set-up, but I'm aware that placing a cabinet in the corner of the room can effectively acoustically load the speaker in such a way that the whole room feels more like you are standing right in front of the speaker. Also the efficiency is increased by this placement and will likely mean you don't need to crank it up just to hear it.
Some have left the cabinets on the floor, others place a road crate underneath the amp to be more on axis to the speakers. Give it a try and see what you think.


How disable view page functionality and revert to pure view with master display?

Question:
On view setting page

I have view with menu link and path. I want to turn it off, revert to basic view master. I've try to remove menu, but didn't change anything. Then I try to remove path but is mandatory. Clone view make same view with page path.
Only solution I can see is create new view and repeat settings (I don't want to do that!), another is to just change path to some useless one so it dons't conflict with my menu links (paths). Any ideas?
Comment: A 'page' view needs a path by definition - if your view shouldn't have a path, you should probably use one of the other display types
Comment: It dose not! You can create one in D7 where you are asked in the beginning (via checkboxes) do you want  support for `page` and/or `block`. I have view without path and I'm using it programmatically. I'm embedding view via `views_embed_view('view_name')`. Display name for my view without page is `master`, where normally you can see something like `page`, `attachment` or `block`. BTW can you point to this definition?
Comment: Proof that view don't need path.
http://postimg.org/image/yp10jn4rn/
Comment: I didn't say a view needs a path - I said a 'page' view needs a path
Comment: So do you understand my problem?
Comment: Not really - if you don't need a page view, just don't create a page view!
Comment: @Clive but the problem is I've already create this page!  And I want to revert from view display type `page` to `master`. Removing `page` display type is the solution, so I don't need to provide path link but still have view to reuse and don't need to create manually again the same view.
Answer: While creating a view uncheck Create a page checkbox and check create a block checkbox;
If you already have created a View, you can add new display as shown in figure below:
Comment: Yes, but I was in opposite situation. I've create view with page (several weeks ago). Tweak `page` display type. After-while I realize I don't want `page` functionality any more and I want to remove it.
Answer: I just realize that all you need is to remove current display type, like show on attached screenshot. So when you have only e.g. page display type after removal it'll become master again.


Symfony2: Choose a service depending on an object classname

Question: I am building a quiz app with Symfony2. For this example, let's say I have two question Entities both extending a Question abstract class

TrueFalseQuestion
MultipleSelectQuestion

I want to build services to check if a user response is correct or not. I will have TrueFalseQuestionChecker and a MultipleSelectQuestionChecker.
What is the better way to choose which one of the service to load ?
In my controller I could do:
if($question instance of MultipleSelectQuestion::class){
    $checker = $this->get('multiple_select_question_checker');
} else if($question instance of TrueFalseQuestion::class){
    $checker = $this->get('true_false_question_checker');
}

$checker->verify($question);

But I find it very "ugly" to do this in my controller because I will have a list of like 10 question types and I will have to do this for a serializer service, for the answer checker service and maybe for other services.
Is there a proper way to deal with an association between a service and an Entity.
I'm thinking of implementing my own annotation, something like that:
/**
* @MongoDB\Document
* @Question(serializer="AppBundle\Services\TrueFalseQuestionSerializer",
* responseChecker="AppBundle\Services\TrueFalseQuestionChecker"
*/

public class TrueFalseQuestion extends Question
{
...
}

Am I missing something already include in Symfony ? Or is my idea of doing one service by question type bad ?
Edit: Working solution thanks to @Tomasz Madeyski
src/AppBundle/Document/TrueFalseQuestion
/**
 * Class TrueFalseQuestion
 *
 * @MongoDB\Document(repositoryClass="AppBundle\Repository\TrueFalseQuestionRepository")
 * @QuestionServices(serializer="app.true_false_question_serializer")
 */
class TrueFalseQuestion extends Question
{
...

src/App/Bundle/Annotation/QuestionServices.php
<?php
namespace AppBundle\Annotation;

/**
 * @Annotation
 */
class QuestionServices
{
    private $checker;

    private $serializer;

    public function __construct($options)
    {
        foreach ($options as $key => $value) {
            if (!property_exists($this, $key)) {
                throw new \InvalidArgumentException(sprintf('Property "%s" does not exist', $key));
            }

            $this->$key = $value;
        }
    }

    public function getService($serviceName)
    {
        if (isset($this->$serviceName)) {
            return $this->$serviceName;
        }
        throw new \InvalidArgumentException(sprintf('Property "%s" does not exist', $serviceName));

    }

}

src/AppBundle/Services/QuestionServicesFactory.php
<?php

namespace AppBundle\Services;

use Doctrine\Common\Annotations\Reader;
use ReflectionClass;
use AppBundle\Annotation\QuestionServices;
use Symfony\Component\DependencyInjection\ContainerInterface;

class QuestionServicesFactory
{
    const SERVICE_SERIALIZER = 'serializer';
    const SERVICE_CHECKER = 'checker';

    public function __construct(Reader $reader, ContainerInterface $container)
    {
        $this->reader    = $reader;
        $this->container = $container;
    }

    /**
     * @param string $questionClass
     * @param        $serviceName
     *
     * @return object
     * @throws \Exception
     */
    public function getQuestionService($questionClass, $serviceName)
    {
        if (!class_exists($questionClass)) {
            throw new \Exception(sprintf("The class %s is not an existing class name", $questionClass));
        }

        $reflectionClass  = new ReflectionClass($questionClass);
        $classAnnotations = $this->reader->getClassAnnotations($reflectionClass);

        foreach ($classAnnotations as $annotation) {
            if ($annotation instanceof QuestionServices) {
                $serviceName = $annotation->getService($serviceName);

                return $this->container->get($serviceName);
            }
        }
        throw new \Exception(sprintf("Annotation QuestionServices does not exist in %s", $questionClass));
    }
}

service declaration
   <service id="app.question_services_factory"
             class="App\Services\QuestionServicesFactory">
        <argument type="service" id="doctrine_mongodb.odm.metadata.annotation_reader"/>
        <argument type="service" id="service_container"/>
    </service>

in controller
    $questionServiceFactory = $this->get('app.question_services_factory');
    $questionSerializer     = $questionServiceFactory->getQuestionService(
        TrueFalseQuestion::class,
        QuestionServicesFactory::SERVICE_SERIALIZER
    );

Answer: This is basically a bit opinion based question but: @Allesandro Minoccheri answer will work but it has one downside: adding new type of question and question checker will require modifying ServiceClassSearcher for each new pair - so this is a bit against SOLID rules.
I think that Question should know what type of checker should check it, so ideally I would inject QuestionChecker into Question. Since Question is an entity and DI is not possible here I would say that using annotation to specify what type of checker is responsible for checking given question is a good way to do it. Once you have annotation you only need to add class which will parse it and get instance of your checker. This way, once you want to add new type of question you don't need to modify any of existing code.
Also I would suggest to use question checker service name instead of class name as it will be easier to use.
A class to parse annotation and get question checker can look something like:
use Doctrine\Common\Annotations\Reader;

class QuestionCheckerFactory
{
    public function __construct(Reader $reader, ContainerInterface $container)
    {
        $this->reader = $reader;
        $this->container = $container;
    }

    public function getQuestionChecker(Question $question)
    {
        $reflectionClass = new ReflectionClass(get_class($question));
        $classAnnotations = $annotationReader->getClassAnnotations($reflectionClass);

        foreach($classAnnotations as $annotation) {
            if ($annotation instanceof \Your\Annotation\Class) {
                //now depending on how your Annotation is defined you need to get question checker service name
                $serviceName = ...
                return $this->container->get($serviceName);
            }

        }

        throw new Exception();

    }
}

Note: I wrote this code out of my head so there might be some parsing errors, but the general idea is here.
You can check this blog post about using custom annotations
Comment: It could be a good way too, I would like to view It implemented a little bit
Comment: Yes it is an opinion based question ! When you say 'Question' are you referring to Entities extending Question ? I will have SomeInteractionQuestion extends Question with an annotation in SomeInteractionQuestion specifying the service name to load ? And in my controller I will read the annotations of my question class and load the correct service based on the annotation ?
Comment: guys, check my edit. @iBadGamer: yes, by saying Question I refer to Entities extending abstract Question class
Comment: Ok I like this solution and will git it a try. I never used custom annotations but this is the opportunity to do so. Thank you guys ! I will get back to you to confirm it is working as expected
Comment: I have edited my question with the working solution, thank you ! In your code you only have to replace $classAnnotations = $annotationReader->.. by $classAnnotations = $this->reader->...
Answer: I suggest to you to use a class to get the service something like this:
$serviceClass = new ServiceClassSearcher();
$serviceName = $serviceClass->getServiceName($question);
$checker = $this->get($serviceName);

Inside your class you can make something like this:
class ServiceClassSearcher
{
   private $service = [
      'MultipleSelectQuestion' => 'multiple_select_question_checker',
      'TrueFalseQuestion' => 'true_false_question_checker'
   ];

   public function __construct()
   {
   }

   public function getServiceName($serviceInstance)
   {
       foreach ($this->service as $instance => $serviceName) {
           $className = instance . '::class';
           if($question instance of $className){
               return $value;
           }
       }

       return null; //is better to throw an exception for a class not found
   }
}

Answer: I believe you are looking for is the Factory Pattern
The factory:
class QuestionCheckerFactory
{
    public function __construct() // inject what you need to created the services
    {
    }

    public function get(Question $q)
    {
        if($q instance of TrueFalseQuestion)
        {
            return new TrueFalseQuestionChecker(...);
        }

        throw new \Exception('Not implemented ...');
    }
}

$checker = $this->get('question.checker.factory')->get($question);
$checker->verify($question);

Comment: But where will I put my services dependencies ? I find it weird to instantiate a service with 'new TrueFalseQuestionChecker(...)' instead of getting it from the service container
Comment: You could inject the container in the QuestionCheckerFactory
Comment: again, adding new type of `Question` requires modyfing `QuestionCheckerFactory` which is against SOLID rules
Comment: Wich one ? What you've written above (with annotations) is just an automated version of what's written here (or what am I missing ?)
Comment: Open close principle. Yes, it is automated version of what you've written and that's why it has an advantage: when you want to add new Question / QuestionChecker pair only thing you need to do is add them, without modyfing QuestionCheckerFactory. In your case you may end up with list of dozen `if`s
Comment: Yes I see, however. I believe this is beautifully put https://stackoverflow.com/a/7876804/4640433.
Comment: Another way around it could be to use the Strategy Pattern instead


Does all source code need to be PCI compliant?

Question: We have never transmitted, processed or stored credit card information in the past as we did everything via PayPal so we never needed to be PCI compliant.
However, we are launching a new online store and by having a seamless checkout where credit card information in processed without redirected to PayPal, we need PCI compliance now.
We are going to consult a Qualified Security Assessor Company to guide us through getting and maintaining PCI compliance. However, I wanted to get a decent idea of what i'm looking at before consulting them, before they try to sell you every service in the house that you may not need.
In terms of PCI compliance, I understand it needs to be done on the software and hardware level and meet the 12 points + required. We are going with Magento Professional as it has a PCI compliant payment system, and we are going with a PCI compliant web hosting company (dedicated server). But in terms of software, do you need PCI compliance on EVERYTHING? Or just the software that transmits, store and processes credit card information?
For example, according to Magento, the Payment Software is PCI compliant, while the Magento Platform is not. So this allows you to make changes, modifications and customisations to Magento without affecting the PCI compliance of the payment software.
In other words, i'm asking, do you only need PCI compliance on the source code/software that deals with transmitting, processing and storing credit card information? These 'Qualified Security Assessor Companies' give the impression that all source code needs to be checked for PCI compliance, which is impossible!
For example, in the case of Magento, can I make changes and modifications to it and still remain PCI compliant? So long as the payment module is untouched since it is PCI compliant and the web hosting, server and OS is PCI compliant?
I mean the php, javascript, mysql stuff that does not deal with credit cards don't need to be compliant do they? they will be on the same server of course.
Comment: Do like Skype, isolate a separate server where you deal with card data. Have a look at this project: https://github.com/joelonsql/pci-blackbox
Answer: The basic answer is that it depends.  In general, only the source code that deals (or can deal) with the sensitive and protected data of PCI needs to be PCI compliant.  However, this means that if other areas of your code have access into the secure areas, you need security there as well.  If another area of your application were to be vulnerable to SQL injection, for instance, it might compromise your credit card systems.  That is why some people will lean towards PCI compliance for all software.  There has to be some assurance that a poorly-written piece of software can be exploited to compromise the safety of the data.
I say it depends because there is always some room for interpretation by those doing the inspection.  However, the good news is that of all the standards, PCI seems to be the most direct and specific about what you need to do and what you cannot do.  Here is more information about what PCI says directly:
https://www.pcisecuritystandards.org/documents/infosupp_6_6_applicationfirewalls_codereviews.pdf
The basic issue here is to be sure that the site cannot be exploited anywhere.  If you develop sufficient "firewalls" between your application areas (credit card data versus normal website), it will go a long way towards showing that you only need to scan some code.  Also, as the above document states, you don't have to do a source code review in order to be PCI compliant.  However, your application needs to be extensively tested to be sure it is safe from typical vulnerabilities.
Answer: I can't speak to the legal details of PCI compliance, but if I were an auditor of your system I would squawk very loudly if any non-certified code runs as the same userid that runs the certified code.
I'd also look pretty closely at what setuid/setgid executables are on the system, what runs as root or with elevated capabilities(7) that could influence the PCI-compliant software, and I'd probably demand mandatory access control tools such as  AppArmor, SElinux, TOMOYO, or SMACK, and an appropriate configuration that prevents tampering with the PCI-compliant portions of the server by untrusted execution domains.
Comment: Whilst this might be true, its kinda irrelevant to the original quesiton


How to add a CSS class to some certain pages depending on the path alias?

Question: I'm trying to add a CSS class to some certain pages for some certain menu styling depending on the current alias path. It works well with the following function but I'm wondering is there another way to split the current alias parts so I can use them as arguments? Here's my present function:
function mytheme_preprocess_html(&$vars) {

  $path = drupal_get_path_alias($_GET['q']);
  $aliases = explode('/', $path);

  if (isset($aliases[2]) && $aliases[2] === 'foo') {
    $vars['classes_array'][] = 'bar';
  }
}

Answer: You should be using Drupal's arg function:
https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/arg/7
Something like this should work:
function mytheme_preprocess_html(&$vars) {

    if (arg(2, drupal_get_path_alias()) == 'foo') {
        $vars['classes_array'][] = drupal_clean_css_identifier(arg(2, drupal_get_path_alias()));
    }
}

Added drupal_get_path_alias() as an arguement of arg() as suggested by @koivo
Answer: There was one answer from a guy which now is deleted suggesting to use arg(2) instead. I commented after trying it out that arg() doesn't seem to work with alias paths. Well, I now found out it does and that's how by passing the Drupal alias path into the arg() function:
if (arg(2, drupal_get_path_alias()) === 'foo') {
  $vars['classes_array'][] = 'bar';
}


Setting $cookie_domain variable for specific folder structure

Question: During configuration of Ckeditor I have to setup the cookie domain variable. I have added my site in subfolder like www.example.com/mynewsitefolder, where www.example.com is my current and running site.
First I tried something like $cookie_domain = '.example.com/mynewsitefolder'; but that doesn't allow me to log in.
How can I set it, so it works on a sub-folder?
Answer: The short answer is that you cannot set cookie domain to such a value. See http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-domain
As a workaround, you can use this in settings.php (around where $cookie_domain is set:
$cookie_domain = ".example.com";
// Set cookie_path ourselves as Drupal doesn't.
ini_set('session.cookie_path', '/mynewsitefolder/');

$cookie_domain is eventually used to set session.cookie_domain but there is nothing in Drupal code base to set session.cookie_path and so we directly set that in settings.php itself.


Improving the Page Speed on Wordpress (GT metrix and Google analytics)

Question:
Defer parsing of JavaScript

**JS    HIGH**

What's this mean?
1.8MiB of JavaScript is parsed during initial page load. Defer parsing JavaScript to reduce blocking of page rendering.

Specify a cache validator

**SERVER    HIGH**

What's this mean?
The following resources are missing a cache validator. Resources that do not specify a cache validator cannot be refreshed efficiently. Specify a Last-Modified or ETag header to enable cache validation for the following resources:
I need your help in fixing these issues over my webpages, it seems these are the main issues that are popping up and also the fact  that we wanted to display our videos on webpage that is wordpress based, is there any way that we can go around doing the same with minimum load time.
Answer: For the "defer parsing of Javascript" issue. You simply need to add the "defer" parameter to your script tags. You can do this with a plugin like Async Javascript or you can simply add the following to your functions.php file:
function defer_parsing_of_js( $url ) {
     if ( is_user_logged_in() ) return $url; //don't break WP Admin
     if ( FALSE === strpos( $url, '.js' ) ) return $url;
     if ( strpos( $url, 'jquery.js' ) ) return $url;
     return str_replace( ' src', ' defer src', $url );
}
add_filter( 'script_loader_tag', 'defer_parsing_of_js', 10 );

For the cache validator issue, the solution will be different based on whether your server is running Apache or NGINX.
For Apache, you'll need to add the following to your .htaccess file:
<filesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
     Header set Cache-Control "max-age=604800, public"
</filesMatch>

For NGINX, you'll need to add the following to your /etc/nginx/nginx.conf file:
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
     add_header Cache-Control "public";
}

Source: defer parsing of JS
Source: cache validator


C# - Getting pitch, channel, and timing of notes from Midi file

Question: I've been downloading and messing about with libraries for hours. I can't find any that can get all the attributes I need. Does such a library exist?
Comment: Maybe, but StackOverflow is the wrong place to ask, as these kinds of questions are considered off-topic. If you find one and have a question about though, feel free to ask!
Comment: possible duplicate of [How to read MIDI file in C#?](http://stackoverflow.com/questions/2845825/how-to-read-midi-file-in-c)
Answer: NAudio is the most popular audio library for .NET and you can use it to read MIDI files as well.
You can read a MIDI file with this syntax:
<code>MidiFile mf = new MidiFile(open.FileName, false);
</code>
And then get the timing, calculate the pitch, check if it is a NoteOn/NoteOff etc.
Here you can find some details:
https://naudio.codeplex.com/discussions/562256


Would relocating css styles inline decrease render time for my apps pages

Question: In my rails(3.1.1) app i have pages that render a lot of data and information, currently i takes roughly 720ms-1480ms(i suspect it will be larger in the future) to render the whole page, there is also quite a bit of css that i use as well. I need to reduce the render time significantly.
Could i decrease the render time if i take out all the styles from the css file and put them inline?
Would this decrease in time have a substantial impact on rendering out pages?
What could i do to reduce render time of the pages?
Thanks
Comment: Are you sure all the HTML/CSS/JS code is 100% downloaded and ready to be rendered *before* the 720ms-1480ms starts? Does it really take that long *just to render*?
Answer: Keep the CSS as a separate file, it will (and should) be cached and in the long run will be faster than inline styles (when viewing other pages that use those styles).
Answer: Inline css will not improve your page rendering speed. Infact it will hamper, since css file will not be cached.
You can do many things to improve page rendering speed, like
1: Compressing js and css files. rails 3.1 assests pipeline automatically does this.
2: caching js and css file
 and much more.
Use a tool like YSlow to analyse the issues and follow its suggestions.


Statistics Probability of registered American voters sung only in English

Question: A recent Fox News/Dynamic Opinion Poll reported that 58 % of registered American voters believe that the U.S. National Anthem should only be sung in English. Two registered American voters are randomly chosen. What is the probability that
(a) both feel the anthem should be sung in only in English?
(b) both do not hold the view the anthem should be sung only in English ?
(c) One more registered American voter is randomly chosen. How likely is it that none of the three American registered voters will agree that the U.S. National Anthem should only be sung in English?

a) mean = np
0.58 * 2 = 1.16 probability that it should be sung in English

b) To find that the anthem should not be in English I used Poisson
x = 2 since 2 Americans
P(X = x) = e^−λ * (λ)^x / x!
<code>     = e^−1.16 * (1.16)^2 / 2!
</code>
to get 0.2109

c) I used poisson again
x = 3 Americans
e^−1.16 * (1.16)^3 / 3!
to get 0.0815
What are the accurate solutions and answers? I feel so wrong here
Comment: a) is wrong probabilities can never exceed 1.
Answer: You can use the simple probability multiplication rule.
a) $.58\times.58=.3364$
b) $.42\times.42=.1764$
c) $.42\times.42\times.42=.074088$
Note: Usually you would have to subtract one from the remaining and the total, but there are so many registered American voters that that amount in this problem would be negligible.
Comment: Thank you, have a good night! I'm going to try to remember in 10 mins to accept your answer, can't accept it yet


Finding a different pattern from the determined pattern

Question: I have set the determined set of pattern that is like this (0.12,0.14,1.00,0.1,1.82), and I want to figure out whether 1000 other sets of 5 points follow the same pattern as the above (which is increasing, then decreasing, and then increasing in the determined pattern).
What kind of algorithms/methods should I try?
The goal is to detect the sets that don't follow the same pattern and behave differently from the determined pattern.
Thanks!
P.s. A quick method using R or Python would be nice.
Comment: First you have to define exactly what you mean by "following the pattern". I thought @StatStudent's answer was excellent, but then you added more detail.
Answer: How about this?  Each of the rows is checked for the pattern of increasing, increasing, decreasing, increasing and outputs the results as TRUE or FALSE.
<code>x<-data.frame(matrix(runif(1000*5), 1000, 5))
x$results<-(x[2]>x[1] && x[3]>x[2] && x[4]<x[3] && x[5]>x[4])
head(x)

> head(x)
         X1        X2        X3         X4        X5    result
1 0.6812421 0.6179089 0.4677266 0.08470731 0.3105175 FALSE
2 0.3161286 0.9102854 0.9559161 0.14665398 0.1736086  TRUE
3 0.1951060 0.6304466 0.5529309 0.13894793 0.6352741 FALSE
4 0.7696047 0.2728853 0.3892910 0.67016050 0.1315047 FALSE
5 0.4675989 0.1841558 0.9340945 0.22240919 0.5642445 FALSE
6 0.1342969 0.5703942 0.5106183 0.55438823 0.4235319 FALSE
</code>
Comment: Good answer, but I also care about how large/small increase/decrease is compared to the determined set. Any suggestions?
Comment: I' not sure I fully understand what you are trying to do.  Can you explain further?


Integration boundaries in simple ODE

Question: I'm reading the wikipedia article on the integration factor. In the first section, "Use in solving first order linear ODE", they describe how to solve an ODE of the form
$$ y'  + P(x)y = Q(x) $$

Finally, we can move the exponential to the right-hand side to find a general solution to our ODE:
$$ y = e^{-\int_{s_0}^xP(s)d(s)} \int_{t_0}^x Q(t)e^{\int_{s_0}^t P(s)ds}dt  + C e^{-\int_{s_0}^xP(s)d(s)}$$

The article does not mention what $t_0$ and $s_0$ are. I would have thought that there is one initial condition, $x_0$, and both refer to that. But then, why use two different variables for the same thing?
Answer: $s_0$ instead of $x_0$ is probably used to express that the lower boundary is arbitrary. Moreover, you can use any fixed anti-derivative instead of the definite integral, the additive constant cancels in the end.
It is also possible that this is a case of multiple authors using multiple conventions and multiple degrees of explicitness.

Using an initial value $y(x_0)=y_0$ one can specialize the integration and used parameters to
$$
e^{\int_{x_0}^x P(s)\,ds}·y(x)-e^{\int_{x_0}^{x_0}…}·y_0=\int_{x_0}^x e^{\int_{x_0}^t P(s)\,ds}·Q(t)\,dt
$$
and thus
$$
y(x)=y_0·e^{-\int_{x_0}^x P(s)\,ds}+\int_{x_0}^x e^{-\int_{t}^x P(s)\,ds}Q(t)\,dt
$$
Comment: Say I am given an initial value $y(x_0) = y_0$. Then I can use $y_0$ to solve for $C$, but also it will imply that both $s_0 = x_0$, and $t_0 = x_0$, right?
Comment: Yes, using $s_0=t_0=x_0$ would then be the most intuitive choice.
Comment: Two follow-ups: The general expression had $C e^{-\int \cdots}$, but you have $y_0 e^{\int \cdots}$, is that a typo? Second: in the second line, your inner inner integral is from $t$ to $x$ - shouldn't that be $x_0$ to $x$?
Comment: Sorry, I misread the form of the differential equation as $y'=Py+Q$. You are right, with the given form the signs must be opposite. -- No, this is combining both the exponentials before and after the integral sign, that is the difference of the integrals over $[x_0,x]$ and $[x_0,t]$..

Integration boundaries in simple ODE


If $a_{k}=2^{2^k}+2^{-2^k}$ then evaluate $\prod_{k=1}^\infty\left(1-\frac{1}{a_{k}}\right)$

Question: If $$a_{k}=2^{2^k}+2^{-2^k}$$ then evaluate $$\prod_{k=1}^\infty\left(1-\frac{1}{a_{k}}\right)$$
I tried using Sophie-Germaine Identity about factorisation for $x^4+4$ but it did not work
Answer: Note that
$$1 - \frac{1}{a_k} = \frac{1 - 2^{-2^k} + 4^{-2^k}}{1 + 4^{-2^k}} = \frac{1 + 8^{-2^k}}{(1 + 2^{-2^k})(1 + 4^{-2^k})}$$
and for $|x| < 1$, we have
$$\prod_{k=1}^{\infty} (1 + x^{2^k}) = \lim_{n \to \infty} \prod_{k=1}^n (1 + x^{2^k}) = \lim_{n \to \infty} \frac{1 - x^{2^{n+1}}}{1 - x^2} = \frac{1}{1-x^2}$$
which gives
$$\prod_{k=1}^\infty \left(1 - \frac{1}{a_k}\right) = \frac{\prod_{k=1}^\infty (1 + 8^{-2^k})}{\prod_{k=1}^\infty (1 + 2^{-2^k})\prod_{k=1}^\infty (1 + 4^{-2^k})} = \frac{\left(1 - \frac{1}{4}\right)\left(1 - \frac{1}{16}\right)}{1 - \frac{1}{64}} =
 \frac{5}{7}.$$
Answer: Let $2^{2^{-k}}=b, 2^{2^k}=\dfrac1b $
$1-\dfrac1{a_k}=\dfrac{b^2-b+1}{b^2+1}$
$a_{k+1}=(2^{2^k})^2+(2^{2^{-k}})^2=b^2+\dfrac1{b^2}=\dfrac{b^4+1}{b^2}$
$1-\dfrac1{a_{1+k}}=\dfrac{b^4-b^2+1}{b^4+1}$
Observe that $$(b^2-b+1)(b^2+b+1)=(b^2+1)^2-b^2=b^4+b^4+1$$
and $$(1+b^2)(1-b^2)=1-b^4$$
$$\implies\prod_{m=k}^n\left(1-\dfrac1{a_m}\right)=\dfrac{1-b^2}{1+b+b^2}\cdot\dfrac{1-b^{2^n}+b^{2^{n+1}}}{1-b^{2^{n+1}}}$$  as for $1-b^2\ne0$
Observe that $n\to\infty, b^{2^n}=0$
Here $k=1,4b=1$


view infinite scroll: how to exec a js function after loading items ?

Question: I have the module "views infinite scrolling" installed on my site and it works. Now I want to exec a function when all loaded (Via ajax) items are loaded and showed to the user. How can I do this ? Thanks.
Comment: You'll probably need to replace the module's JS behavior with one of your own - currently it doesn't raise any events. Or you could try [`ajaxComplete()`](https://api.jquery.com/ajaxcomplete/)
Answer: You should be able to use Drupal JS Behaviors. Views Infinite Scroll should fire off Drupal behaviors on an AJAX request. You would need to add custom JS to your pages that use infinite scrolling.
Here's an example where someone uses this to add a class to views rows loaded from Views Infinite Scroll.
Drupal.behaviors.myBehaviorName = {
  attach: function (context, settings) {
    // run your code here
  }
};

Comment: And then you can use that to detect the presence of the "load more" button. Views Infinite Scroll will remove it when all items are loaded. Posting code in a separate answer...
Answer: As @romain-ni says, the latest dev version supports raising a trigger when new items are loaded, however there are patches for previous version if for some reason you can't update to the latest version of the views_infinite_scroll package
v8.x-1.6
https://www.drupal.org/project/views_infinite_scroll/issues/3227982
Once this is in place you can listen for that event in your own Javascript:
$(document).on('views_infinite_scroll.new_content', function (evt) {
  // Your code here
});

Answer: This code will show a visually-hidden button after all items have loaded.
Drupal.behaviors.infiniteScrollShowButton= {
  attach: function (context, settings) {
    // If all items have loaded, display the "show all" button
    if ($('.view-taxonomy-term .js-pager__items a').length === 0) {
      $('.view-taxonomy-term .view-footer a.button').removeClass('visually-hidden');
    }
  }
};

Answer: Un patch existe pour l'ajout d'un évènement jQuery au chargement de contenu : https://www.drupal.org/project/views_infinite_scroll/issues/3164903
On y ajoute deux triggers :

"views_infinite_scroll.new_content" : au chargement des éléments
"views_infinite_scroll.new_content.appended" : une fois que les éléments sont présents dans le DOM

Le premier trigger devrait intégrer la prochaine version stable 8.x-1.8, puisqu'il est déjà disponible dans la version 8.x-1.x-dev
Ensuite pour détecter l'évènement :
$(document).on('views_infinite_scroll.new_content', (e) => {...})


How to display cached uploaded image in tmp/uplodas directory using Carrierwave S3 and Sidekiq on Heroku

Question: I am using Carrierwave + carrierwave_backgrounder + Sidekiq + Heroku to upload images. The upload works fine. When the upload form is submitted, I need to display the uploaded image, but background job is still processing it, so the page only displays the file name, I have to wait the background job is done, refresh the page to see it. How can I display a temp uploaded image when the page finish loading?
I know I can config the cache_dir to store a tmp image and will be deleted afterwards, like this:

  def cache_dir
    "#{Rails.root}/tmp/uploads"
  end
Can I render this tmp image? If so, how do I render this in the view? I want to avoid using default_url in the uploader
I am using process_in_background :avatar in the model
Thanks!!
Comment: I doubt there is something like it with that I presume ur best bet (perhaps you know it ) `default_url` also make sure you set `move_to_cache` `move_to_store` could improve ur background processing experience because seem like u r file are quite large
Answer: You should be able to define the default_url method in your uploader class.
Ex:
class MyUploader < CarrierWave::Uploader::Base
  def default_url
    "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  end
end

Comment: Thanks for that, is there a way I can display the cached uploaded image in the tmp/uploads?


What to do when every VIF value is infinity

Question: I know that VIF values have no upper limit, and that anything over 10 is usually bad news if you are trying to avoid multicollinearity especially for regression models such as multiple logistic regression.
However - most of what I have read suggests removing the offending infinity variable. Here in lies the problem.
I'm currently working on a dataset with nearly 2000 variables, and every single one has produced a VIF of infinity.

I've been doing this on python:
<code>vif_info = pd.DataFrame()
vif_info['VIF'] = [variance_inflation_factor(df.values, i) for i in range(dif.shape[1])]
vif_info['Column'] = df.columns
vif_info.sort_values('VIF', ascending=False)
</code>
and I have tried various different methods, which have all produced the same results, so I'm relatively sure I haven't done something wrong there.
I have also tried log transforming the data and I still get the same result.
I'm not sure if it adds up though because when I produce something like a clustermap using a regular correlation matrix (see below) there seems to be clear specific variables that are highly correlated but not all variables seem to be this way.
In terms of statistical analysis I'm not sure how one would proceed with these results (or if theres something obvious that I've done wrong).
Comment: What kind of analysis do you want to do with your variables?
Comment: Ideally I'd do a multiple logistic regression. My response variable is categorical (3 categories) and I'd like to which of the variables are most significantly associated with each category
Answer: It seems that a somevariables are able to create perfect multiple regressions on other variables (which would explain why all the VIF are infinity).
In order to identify them, I would try to do some actual regressions $X_j=X_{\backslash j}\beta+\epsilon$ and check the coefficients in order to try to identify the problematic variables.
Otherwise, maybe this comes from your dataset. I am not familiar with chemistry data at all. According to your experience, is it common to have very high VIF in such a dataset ? Also, what is the size of your dataset ? How big is the number of observations in comparison to your 2000 regressors ?
EDIT:
Based on your comment, it is likely that the issue comes from the fact that you have way more variables than observations ($k=2000 > N = 45$). So all the regressions end up having $R^2=1$, which corresponds to your VIF equal to 1 for all variables.
As a consequence, I suggest you try to find a way to use a small number of regressors for your regressions. A technique like forward stepwise regression could help, but will prevent you from doing inference with your resulting model. This will be fine if you are only interested in predictions.
Comment: I'm honestly not sure how common this is as it's my first project in this domain.

the number of observations is pretty small - only 45.

The dataset is a publicly available one: https://www.metabolomicsworkbench.org/data/DRCCMetadata.php?Mode=Study&StudyID=ST000046
Comment: OK, I get it. I edited my answer.
Answer: If you were going for prediction, I would have suggested some regularization approach.
In a context of Null Hypothesis Significance Testing (NHST), you may want to look at the collinearity diagnostics of Belsley, Kuh and Welsch. In contrast to VIF, they also reveal which groups of predictors are closely associated. This makes deciding how to "thin out" your predictor set much more focused. The disadvantage is that BKW is quite a bit more complicated. And I don't know how well it works with 2000 predictors.
Alternatively, you could use a dimension reduction technique like PCA and run your logistic regression on the first few principal components. The disadvantage here is that you get the p values of the principal components, not of your original data.
Finally, NHST really presupposes you have predefined hypotheses in the context of a planned experiment. If you really want to feed in 2000 predictors and assess whether any coefficient is nonzero, perhaps you should go back to the planning stage and plan your experimental controls more carefully.
Comment: It is possible to use NHST with regularization, see the answer here: https://stats.stackexchange.com/questions/241082/testing-for-coefficients-significance-in-lasso-logistic-regression


Unittesting Callable Orchestrations

Question: Working with BizTalk, I like to use callable orchestrations (without pipelines) as a service for other orchestrations, giving more flexibility in the architecture. But unittesting them is rather devious. Now, I use a seperate application with a wrapper orchestration (just calling the orchestration to test) that I deploy to BizTalk before unittesting.
Does someone have a better way to unittest callable orchestrations? Most preferrably, I would have a unittest where I don't need any extra artifacts to deploy.
Thanks in advance.
Answer: It is hard to answer an open question with NO, but my answer would be that that it is not practically possible.
Orchestrations are really tightly coupled with the BizTalk orchestration engine. If you want to unit test an orchestration, you will need to simulate that orchestration engine. That is not an easy job. There are a lot of specifics there that you have to think about, like dehydration, serialization, scopes, how messaging to and from your orchestration actually works, etc..
I would say that you are taking the right steps by separating out parts of your orchestrations, and not making them direct bound on physical ports. That makes testing possible / easier. Less connections also means less points of error.
I would try to limit the amount of orchestration work that you do. Only use an orchestration when there is no better (or at least more testable) alternative.
If you can test your orchestration quickly and without to much effort, by simply deploying, dropping a message, and watching the results, than you are already doing more testing than a whole suite of BizTalk developers. If you make this process easy, and automate it where you can (deploy, drop file, check expected output) then you will at least make it easier to detect regressions.

The goal is to make testing so easy / cheap and so reliable, that is easier to test than not to test. That way you will prevent managers from saying skip the tests, they take too long. You will want them asking: can you test it first?

Unittesting Callable Orchestrations