Determine $[ \mathbb{Q} (\sqrt{2}, e^{2\pi i/3}) : \mathbb{Q}]$

Question: I want to determine $[ \mathbb{Q} (\sqrt{2}, e^{2\pi i/3}) : \mathbb{Q}]$.  I can see that $[ \mathbb{Q} (\sqrt{2}) : \mathbb{Q}] = 2$ because $2$ is the degree of the polynomial $x^2 -2$, which is used because it has $\sqrt{2}$ as a root.  However, I don't know what to do with determine $e^{2\pi i/3}$.
Answer: You can verify that $e^{2i\pi/3}$ is a cube root of unity, from which we can deduce that $\displaystyle f(x) = \frac{x^3-1}{x-1} = x^2 + x + 1$ is its minimal polynomial.  If $f$ is irreducible over $\mathbb{Q}(\sqrt{2})$—or, equivalently, if $f$ has no roots in this field—then the extension $\mathbb{Q}(\sqrt{2}, e^{2i\pi/3})/\mathbb{Q}(\sqrt{2})$ will be of degree $2$.  To see that roots of $f$ do not exist in $\mathbb{Q}(\sqrt{2})$, note that these roots are complex with nonzero imaginary component (look at its discriminant or expand the cube roots of unity according to Euler's theorem).
To finish up, apply the multiplicativity formula for degrees on the tower $\mathbb{Q} \subset \mathbb{Q}(\sqrt{2}) \subset \mathbb{Q}(\sqrt{2}, e^{2i\pi/3})$.


Nagios RHEL 5.4

Question: I'm moving Nagios 3 over from Ubuntu 8 server to RHEL 5.4. One nice feature Ubuntu had is the ability to tell you where the configuration errors are. For example if I had something incorrect in my commands.cfg file, I was informed where the error was. This does not seem to be the case with RHEL. I just get a generic message.
Running configuration check... CONFIG ERROR! Check your Nagios configuration.

Is there any kind of flag or something you can add to a config file to give more of a verbose error message?
Answer: I think the following is what you want, you may have to change the paths to match your installation of course.
After you have made the change or changes, you can use /etc/init.d/nagios reload.  The following command doesn't always show all of the errors it sees, so after you correct an error, run it again.
sudo /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg
Comment: That was it, I knew it was something simple. Thanks!
Answer: I had to do this so often, I wrote a tiny shell script which lives in my nagios /etc/ directory:
#!/bin/bash
/opt/csw/nagios/bin/nagios -v /opt/csw/nagios/etc/nagios.cfg | egrep -i 'Warning|Error|okay'

...adjust your paths to suit.
Now when I make changes, my fingers know to go
# ./check
Warning: Contact group 'alladmin' is not used in any host/service definitions or host/service escalations!
Total Warnings: 1
Total Errors:   0
Things look okay - No serious problems were detected during the pre-flight check

...and based on that, I can ./reload (or not).
Comment: I got everything working, thanks for the shell script! it's an uphill battle with Nagios ;)

Nagios RHEL 5.4


Sectors which is smaller than corresponding PV size error

Question: OS : CentOS6.8
The initial disk was /dev/vdc with which volume group vg0 was mde. Then, this disk was removed from volme group using vgreduce /dev/vdc vg0 which made the LVM metadata inconsistent, showing the PV with uuid not found. New partition /dev/vdc1 was also created.
To restore the LVM metadata, executed following command.
pvcreate --uuid "40sFOW-dBUz-Jb0l-K8ig-puvo-2qIA-xPfLIP" --restorefile /etc/lvm/archive/vg0_00003-615784639.vg /dev/vdc1

Changed the device name from /dev/vdc to /dev/vdc1.in file vg0_00003-615784639.vg and executed above command.
[root@testpaul ~]# ls -lt /etc/lvm/archive/vg0_00003-615784639.vg /etc/lvm/archive/vg0_00002-1466532506.vg
-rw------- 1 root root 1567 May 20 10:24 /etc/lvm/archive/vg0_00003-615784639.vg
-rw------- 1 root root 1324 May 20 10:13 /etc/lvm/archive/vg0_00002-1466532506.vg
[root@testpaul ~]#
[root@testpaul ~]#
[root@testpaul ~]# grep -i device  /etc/lvm/archive/{vg0_00003-615784639.vg,vg0_00002-1466532506.vg}
/etc/lvm/archive/vg0_00003-615784639.vg:                        device = "/dev/vdc1"    # Hint only
/etc/lvm/archive/vg0_00003-615784639.vg:                        device = "/dev/vdd1"    # Hint only
/etc/lvm/archive/vg0_00002-1466532506.vg:                       device = "/dev/vdc"     # Hint only
[root@testpaul ~]#

How can I correct below error in pvs command.
[root@testpaul ~]# pvs

 Device /dev/vdc1 has size of 20971377 sectors which is smaller than corresponding PV size of 20971520 sectors. Was device resized?
  One or more devices used as PVs in VG vg0 have changed sizes.

  PV         VG   Fmt  Attr PSize  PFree
  /dev/vdc1  vg0  lvm2 a--u 10.00g 1020.00m
  /dev/vdd1  vg0  lvm2 a--u 10.00g   10.00g

[root@testpaul ~]#

Comment: @JeffJose if you use whole with lvm you don't have any reason to use partition.
Comment: The tests I am doing is on test server and on actual production server, there are so many block devices that make up the volume group. Only for one disk,  customer has added disk as raw device initially, then removed disk from volume group and then he created partition and added that to volume group.
Answer: I reduced the PV size lesser, 1MB i lessened.
[root@testpaul ~]# pvresize --setphysicalvolumesize 10239M /dev/vdc1

Device /dev/vdc1 has size of 20971377 sectors which is smaller than corresponding PV size of 20971520 sectors. Was device resized?.....
Physical volume "/dev/vdc1" changed
  1 physical volume(s) resized / 0 physical volume(s) not resized

[root@testpaul ~]# vgcfgrestore vg0

  Restored volume group vg0

[root@testpaul ~]# pvs

PV         VG   Fmt  Attr PSize  PFree

/dev/vdc1  vg0  lvm2 a--u 10.00g 1020.00m

/dev/vdd1  vg0  lvm2 a--u 10.00g   10.00g


If p is an odd prime, then $2^{p-1} \equiv p+1 \bmod 2p $

Question: If $p$ is an odd prime, then $2^{p-1} \equiv p+1 \bmod 2p $.
I can't seem to apply Fermat's Little Theorem with this one. Can anyone give me a hint on how to prove this.
Answer: You can use the Chinese remainder theorem in this case, since $2$ and $p$ are relatively prime.  You clearly have $2^{p-1} \equiv 0$ mod $2$ and $2^{p-1} \equiv 1$ mod $p$, by Fermat's little theorem. Now, using the CRT, you can find the class of $2^{p-1}$ mod $2p$.
Answer: Or from
$$2^{p-1}\equiv 0 \pmod{2} \Rightarrow 2^{p-1}\equiv p+1 \pmod{2}$$
since $p+1$ is even. And
$$2^{p-1}\equiv 1 \pmod{p} \Rightarrow 2^{p-1}\equiv p+1 \pmod{p}$$
Or
$$2 \mid (2^{p-1}-(p+1))$$
$$p \mid (2^{p-1}-(p+1))$$
and $\gcd(2,p)=1$, thus
$$2p \mid (2^{p-1}-(p+1)) \Rightarrow 2^{p-1}\equiv p+1 \pmod{2p}$$


Rigorous Proof of the Principle of Counting

Question: Principle of Counting: If there are m ways of doing a task A and n ways of doing a task B, then there are mn ways of doing tasks A and B.
What would it take to prove this rigorously? All the proofs I have seen rely on our intuitive notion of counting. In the wikipedia article, it says that this principle is just the definition of the cardinality of the cartesian product of two finite sets. Does this mean that, if I wanted to prove this rigorously, I would have to pick a model of ZF, define cardinality, reformulate the statement in terms of my model and then prove it?
Comment: You could probably pull off an induction on $n$.  I think such a proof would be more of an exercise in semantics rather than mathematics.  Personally, I'm happy to take PoC as an axiom. :-)
Comment: Well, induction is part of ZF too...  You can't do anything without using some kind of axioms, and there's nothing wrong with that.  Axioms are pretty just ways of formalizing our intuitive notion of what mathematics is.
Comment: What is the role of tasks in the formulation? They seem to me just to add potential confusion (for instance task B might be a subtask of A...). If you are asking to prove that that if sets $A$, $B$ have finite cardinalities $n$ and $m$ respectively, then $A\times B$ has cardinality $nm$, the product being described by Peano's axioms, then one should not have a hard time giving a formal proof.
Answer: You do need to rely on an intuitive notion somewhere, because "ways of doing a task" is not itself a formal mathematical concept until you explicitly equip it with a formal interpretation. You can then argue formally that the consequences of your interpretation are such-and-such, but the argument that the interpretation accurately captures your notion of "ways of doing a task" is necessarily informal.
Comment: I agree that you need a formal mathematical concept in order to argue formally. I believe the formal concept for the principle of counting is the cartesian product. It makes me wonder though: why have the principle of counting when the cartesian product captures the intuitive notion of "ways of doing a task". It seems silly to me.
Answer: Let's say I want to build something. It can be done in two steps. For step $1$, I have $m$ choices. For step $2$, $n$ choices. Each possible construction then can be represented by an ordeded pair $(x,y)$, where $x\in [1,m]$ and $y\in [1,n]$.
The number of possible constructions is then the number of elements of the set $S$ with pairs $(x,y)$ as defined. I don't know if you want the answer of how the size of $S$ is proven, but I (or somebody else) can show you if you want.
Comment: Regaring your comment "why have the principle of counting when the cartesian product captures the intuitive notion of "ways of doing a task". It seems silly to me."

You can think of the "Principle of counting" as another name for |AXB|=|A|*|B| (what I proved above). It's just that the name is better in the context when you're counting things.
Comment: Yes, I would like to know how the size of $S$ is computed from first principles, i.e. the axioms of ZF.
Comment: By induction. Let A and B be finite sets. We want to prove that

AXB={(a,b) | $a\in A$ and $b\in B$} has size |A|*|B|.

Base case:
|B|=0. It follows AXB is the empty set and |A|*|B|=0 by definition.

Induction step:
|B| has size n+1. Let b an element of B. |B-b|=n. Thus, |AX(B-b)|=a*n.

We also have that AXB=AX(B-b) U AX{b} so |AXB|=|AX(B-b)| + |AX{b}|=a*n+a=a(n+1), as needed.


Averages using integrals

Question: Suppose a 1000 degree liquid is cooling, at the rate of $ C = 22 + 900 e^{-0.3t}$.
So after 50 minutes I'd expect $ C = 22 + 900e^{-15}$ = 22. But what is the average value of the temperature over that 50 minutes? I came up with
$ 1/50 ∫_0^{50}\:22\:+\:900e^{-0.3t}dx = 82$
Is this correct?
Comment: Idea? Yes. Your calculations? Not so much.
Comment: I think you need to specify what is the unit of $t$ in $C$. You assume it is minutes but... is it?
Comment: When is the liquid $1000$ degrees? At $t=0$ you have $C=922.$
Comment: Ok the initial temperature is not of importance, just the process of finding the average value is what I was looking for
Answer: You are very much correct:
$$T_{avg} = {\sum T(t)\over \triangle t}$$
$$=\displaystyle\int_0^{50} 22+e^{-0.3t}dt\over\displaystyle\int_0^{50} dt$$
$$=22 - {(900)(e^{-15}-e^0)\over50\cdot 0.3}$$
Similarly taking $e^{-15}$ to be negligible
$$= 22 + 60$$
$$\boxed{T_{avg} = 82}$$
However as some commenters have mentioned, the units of $\tau = 0.3$ and $t$ are of importance.
Comment: I just find it quite unusual: the capital letters and you pretending to be a dog (I know you can't possibly be one). But if that's your style, go for it!
Comment: Haha thank you dog. Yeah I just wanted to make sure I had the formula correct for use with a different example
Comment: The function is actually $22+900e^{-0.3t}$. Doing this I find that the OP is actually correct.
Comment: Dear me. I have. Apologies for the silly mistake. I'll fix it right at once.
Comment: Also, what is up with that profile of yours?
Comment: Sneaking around, now, are ya? @TobyMak … just kidding. I don't think there is anything wrong with it...

Averages using integrals


How to adjust the prediction probability of a classifier for validation accuracy

Question: Suppose you have a ML binary classifier that outputs the probability $p$ that a particular set of features belong to class $A$ (therefore the probability that the features are from class $B$ is $1-p$). Of course, those predictions don't take into account how well the classifier performed on validation sets, so I'm trying to figure out how to incorporate that information into the final result.
For example, I round the output probability up or down at 50% to make the classification. Suppose my classifier has a True Positive rate of 94% and a False Negative rate of 10% for class $A$ in a validation set. For a new, unseen feature set, it reports a probability of 98% that the features are from class $A$. That number should really go down, since there's a 6% chance it is a False Positive.
Strangely enough, I have yet to be able to find discussions online or in the literature about how to adjust the probability predictions to reflect validation findings. Or maybe I'm just looking in the wrong places...
Comment: Theres an inconsistency in your description.  If your classifier reports a probability, it doen't inherently have a true positive rate or a true negative rate.  So to make sense of the question, you'll have to explain that a bit more.  When a classifier reports a probability for an event, as long as that classifier is well calibrated to the population, then that probability really is its best estimate of $P(y = 1 \mid X)$, there's no need to adjust it.
Comment: I round up or down at 50%.
Comment: When you round up or down like that, you're being very destructive.  You're replacing an estimate of a probability, which gives you lots of information about the classifiers degree of belief, and artificially forcing it to be completely confident.  You shouldn't expect the outcome of such a destructive intervention to have much of anything to do with the quality of the original probabilistic estimates.  I'll soapbox a bit: setting a classification threshold at 50%, and thinking the resulting rule tells you much of anything statistically is misguided....
Comment: ...This is a fundamental misconception about classification.  Models predict probabilities, and they come together with some measure of their uncertainty in the form of probabilities (as long as they are well calibrated).  Hard classifiers do not, class assignment is a non-statistical issue.  It should not be done lightly, and it should always be done in the context of the business or scientific problem you are trying to address.  Every time someone naively thresholds a binary classifier at 50% they are making a serious error.
Comment: Matthew, I understand your points completely. What I had hoped was that by thresholding the probas on the validation results, I could establish a rough TN rate, and use that as a conservative prior to adjust output probabilities for new classifications--where I will report the proba, not a threaholded value. So I'm throwing away that validation info for a specific reason, not because I want to ignore it. Of course I'm happy to hear that this idea of mine is flawed. I've just found classifieds can report a 99% probability but they make sufficient errors that this isn't really believable.
Answer: I found this blog post, which provides a convenient method and code for comparing the output prediction to empirical probability of a binary classifier, provided the validation set is sufficiently large.
http://jmetzen.github.io/2014-08-16/reliability-diagram.html
I fit a low-order polynomial to the result, which provides a reasonable conversion from classifier output to actual probability.


How to create content type programatically

Question: how to create content type programatically and attach field api fields to it? hook_node_info() will not work for me since i want to create my node type and its instance in a single method (for testing purposes), so kindly suggest a solution other than hook_node_info().
Thanks
Answer: To create a node type, call node_type_save(). Have a look at the documentation of the Fields API for information on how to attach fields to the node type.


Monitorando a última row de uma tabela

Question: Estou tentando monitorar a última row de um banco MySQL e quando esta for alterada eu vou exibir uma mensagem, porem estou com dúvidas em como monitorar com código C#.
Já consegui requisitar a última row de tempo em tempo, porém gostaria de exibi-lá somente se for diferente da anterior.
Esta primeira parte inicia meu contador juntamente com o Load do Form:
private void AnteSala_Load(object sender, EventArgs e)
{
    var timer = new System.Timers.Timer
    {
        Interval = 2 * 60 * 1000,
        SynchronizingObject = this
    };
    timer.Elapsed += delegate
    {
        //MessageBox.Show(@"tentou update check 1");
        ReadInformationFromeMessage();
        //MessageBox.Show(@"passou 1");
    };
    timer.Start();
}

Esta segunda parte pega minha última row mensagem do banco:
private void ReadInformationFromeMessage()
{
    try
    {
        const string mySelectQuery =
            "select * from send_eMessages order by id desc limit 1";
        var myCommand = new MySqlCommand(mySelectQuery, ConexaoBancoMySql.GetConexao());
        var reader = myCommand.ExecuteReader();

        while (reader.Read())
        {
            var eMessage = (reader.GetString("eMessage"));

            Invoke((MethodInvoker)delegate
            {

               var pop = new PopupNotifier
               {
                   //escopo de mensagem
                   TitleText = "*  Informativo de Segurança  *",
                   ContentText = "" + eMessage,
                   //fim do escopo de mensagem
                   TitleFont = new Font("Tahoma", 12),
                   //cor do titulo do form
                   TitleColor = Color.White,
                   BodyColor = System.Drawing.Color.FromArgb(0, 75, 0),
                   //contorno do form
                   BorderColor = System.Drawing.Color.FromArgb(0, 255, 0),
                   //cor da fonte do aviso
                   ContentColor = System.Drawing.Color.FromArgb(255, 255, 255),
                   //tamanho da fonte
                   ContentFont = new System.Drawing.Font("Tahoma", 12F),
                   //cor da fonte do aviso quando mouse em cima
                   ContentHoverColor = System.Drawing.Color.FromArgb(255, 255, 255),
                   //centralizacao da mensagem no form
                   ImagePadding = new Padding(0),
                   ContentPadding = new Padding(10),
                   Delay = 15000,
                   GradientPower = 150,
                   //tamanho da borda superior
                   HeaderHeight = 1,
                   Scroll = true,
                   ShowCloseButton = true,
                   ShowGrip = true,
                   ShowOptionsButton = false,
               };
                pop.Popup();
           });
        }
    }
    catch (MySqlException ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
        ConexaoBancoMySql.FecharConexao();
    }
}

Answer: A pergunta não ficou clara pra mim, mas não tenho pontuação para comentar. Então vou responder baseado em que eu entendi.
Neste caso eu faria uma DataTable de cache histórico, onde toda vez que você que fizesse a consulta salvasse os dados nesta tabela de cache, e depois, compararia o retorno de dados da consulta atual com os dados do cache.
public void sample(){

    DataTable cache = /* sua tabela de cache */;
    DataTable consultaAtual = /* retorno da sua consulta atual */;

    foreach(DataRow rowCache in cache.Rows){
        foreach(DataRow rowConsultaAtual in consultaAtual.Rows){
            /* abaixo você vai comparar todas as colunas da linha da consulta atual com as colunas da linha do cache */
            if(rowCache["column1"].toString().Equals(rowConsultaAtual["column1"])){
                /* os valores das colunas da consulta atual e do cache estão iguais, então não houve modificação */
            }
        }
    }
}

Não sei se era isso que você queria, caso não seja excluo a resposta. Sou iniciante e estou tentando aprender ajudando, espero que te ajude :)
Comment: Tudo bem @caio porem ja obtive respostas no overflow , mesmo assim obrigado

Monitorando a última row de uma tabela


Recover files on a Windows 7 host from a user who has been deleted from active directory?

Question: Is there a way to recover data (Files, Programs, etc...) on a Windows 7 machine assigned to a specific Active directory user, that has since been deleted from Active Directory? For some reason the previous IT Manager deleted the user without archiving any data from the machine before hand and my higher ups are asking if I can retrieve said data.
Answer: Log onto the computer. Find the user profile for the user. Copy the data to where ever you need.
Comment: I looked in C:\users\ already. There was no information there. The Documents file that is hosted on our server was empty as well. So either she didn't use the shared folder for storage purposes or the information just seems to be gone...


Como verificar se arquivo existe no diretório da aplicação no armazenamento interno?

Question: Estou tentando verificar se um arquivo existe no diretório da aplicação no armazenamento interno com o código abaixo
String path = Environment.getExternalStorageDirectory().getPath()+"/meu_diretorio/arquivo";
    boolean exists = (new File(path)).exists();
    if (!exists) {
        Toast.makeText(getActivity(), "O arquivo não existe!", Toast.LENGTH_SHORT).show();
    }else{
        Toast.makeText(getActivity(), "O arquivo existe!", Toast.LENGTH_SHORT).show();
    }

Estou utilizando as permissões:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

No entanto não está funcionando. Como devo proceder com essa verificação?
Comment: o `meu_diretório` tem acento mesmo ou só exemplo?
Comment: Era só um exemplo.
Comment: Está dando algum erro na aplicação?! Você concedeu permissão de leitura ou escrita?
Comment: Estou utilizando as permissões que incluí na pergunta. Não está dando nenhum erro.
Comment: Em vez de `getPath()` você tentou usar `getAbsolutePath()`?
Comment: Não deu certo também!
Comment: Deixa eu entender! Existe o arquivo, mas sua aplicação não reconhece certo?! Você chegou a debugar e ver se está pegando o caminho corretamente?!
Comment: O caminho que é mostrado no path é `storage/emulated/0/` mas o correto deveria ser o `data/br.com.minhaaplicacao/meu_diretorio/arquivo` ou eu estou confundindo tudo?
Answer: O código que está a usar é para aceder ao armazenamento externo.
Se quer obter o caminho para a raiz do armazenamento interno deve usar File getFilesDir().
Para obter o caminho completo para um arquivo name, guardado no armazenamento interno, use File getFileStreamPath(String name)
Notas:

Os métodos indicados são da classe Context(Activity é um Context).
Não são necessárias quaisquer permissões para ler/escrever no directório/arquivo.
Os arquivos deverão ter sidos escritos recorrendo a um FileOutputStream obtido pelo método FileOutputStream openFileOutput(String name, int mode).
Veja Como usar armazenamento interno.
Comment: Obrigado, consegui resolver o problema apresentado no tópico.


Creating muliple nodes from one page

Question: I want to create multiple nodes from one page where I input one or two values into each entity, where each of the entities has a reference.
Example:
If I had three kids, I would measure their height each week, entity types "kid" and "height". Height references to kid and instead of click add "height" three times and select which kid then input height, I would like to have a page with the names (or ID) of the kids, then one input field for each, so that when I save, three entities of height are created with the values specified.
Comment: Hello and welcome. Please remember that simply providing specification is not enough, unless what you want seems to be something widely and universally useful. In specific cases like this, please do your search and research (see Help Center, Asking section for details) and ask when you will hit specific problem with implementation.
Comment: Thanks Molot. I have done my search and research as best as I can, but I am still unable to find the solutions. I would assume there was a modue for this particular prblem, and I'm quite certain I stumbled upon a way to solve it long tme ago.
Answer: There are a couple of modules to create entities (nodes etc) inline i.e in the parent form, when it's being created itself.
When you save the form, it creates the entity AND the entities that are referencing it, but it's up to you to create the entity structure and references to achieve what you want.
I can vouch for References Dialog
However, I think you are making it too complex and you only really want one node type (kids) with an unlimited field (height), if that is your real scenario.
For example you easily create a custom form with three (or loop for x) fields and when it saves it adds the result to existing nodes, eg :
<code>// Get and render the form somewhere.
$form = drupal_get_form('kids_height_form');
print render($form);

/**
 * Form constructor.
 */
function kids_height_form() {
  $kids = array(2210, 2043, 2038);
  $entities = entity_load('node', $kids);
  // dpm($entities);
  foreach ($entities as $kid) {
    $id = $kid->nid;
    $form["height_$id"] = array(
      '#title' => 'Height this week for $id',
      '#type'  => 'textfield',
    );
  }
  $form['submit'] = array(
    '#type'  => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

/**
 * Form submit handler for kids_height_form().
 */
function kids_height_form_submit($form, &$form_state) {
  $kids = array(1, 2, 3);
  $entities = entity_load('node', $kids);
  foreach ($entities as $kid) {
    $id     = $kid->entity_id;
    $height = $form_state['values']["height_$id"];
    $count  = count($kid->field_height[LANGUAGE_NONE]);
    $kid->field_height[LANGUAGE_NONE][$count + 1] = array('value' => $height);
    entity_save('node', $kid);
  }
}
</code>
The top bit prints the form, the form constructor simply create as many text fields as there are node ids in the array and the submit handler does the same loop except also adds the result to a new delta for the height field and saves the entity.
You can also achieve this with EntityMetaWrappers and may be a bit neater but the process is very similar. (this is untested by the way and will need work to suit your needs);

Creating muliple nodes from one page


Postfix "mail-to-script" pipe only delivers empty messages

Question: i have a problem here.
I want that a incoming email is piped to a php script in the system through postfix.
My System is running with ispconfig 3, postfix and dovecot (< virtual mailbox users are saved in mysql).
I looked already into this one: How to configure postfix to pipe all incoming email to a script?
... the script is executed, but no "message" is delivered to the script. My setup so far:
In ISPConfig 3 i have set up the following email route:
Active      Server          Domain              Transport   Sort by
Yes         example.com     pipe.example.com    piper:      5

excerpt from my postfix master.cf:
piper   unix  -       n       n       -       -       pipe
    user=piper:piper directory=/home/piper argv=php -q /home/piper/mail.php

so far it is working great (mail sent to email@example.com) (mail.log):
Jun 21 16:07:11 example postfix/pipe[10948]: 235CF7613E2: to=<firstname.lastname@example.com>, relay=piper, delay=0.04, delays=0.01/0.01/0/0.02, dsn=2.0.0, status=sent (delivered via piper service)

... and no errors in mail.err
the mail.php is sucessfully executed (its chmod 777 and chown'ed to piper), but creates a empty .txt file (normally it should contain the email message):
-rw------- 1 piper piper    0 Jun 21 16:07 mailtext_1340287631.txt

the mail.php script ive used, is the one from http://www.email2php.com/HowItWorks
if i use their (commercial) service to pipe an email to the mail.php (in a apache2 environment) through a provided "pipe-email", the message is saved sucessfully and complete. But as you can see, i dont want to use external services.
-rw-r--r--  1 web2 client0  1959 Jun 21 16:19 mailtext_1340288377.txt

So, whats wrong here? I think it has something to do with the "delivering configuration" in my system...
Answer: That is because your PHP-Script is crap. It doesn't save STDIN to the file. It instead saves a non-initialized (empty) variable to a file. This is why it is empty.
You should learn PHP to solve the problem.
Comment: And why it is working when i use the http://www.email2php.com/ Service (Destination set to the mail.php, like http://example.com/mail.php)? This doesnt make sense to me.
Comment: So, i wrote a short bash script to save stdin to a file.

the command

`echo testing | /home/piper/stdin.sh`

sucessfully creates a stdin.txt with the content "testing", but execute this one via master.cf piper: transport, it creates again a empty stdin.txt file.
Comment: Another update... this one works: http://www.daniweb.com/web-development/php/threads/318306/pipe-email-to-php


Are studies in epidemiology all observational?

Question: Are studies in epidemiology all observational and not controlled? My impression comes from Wikipedia, which lists:

Case Series
Case Control Studies
Cohort Studies
Outbreak Investigations

and no others.
Comment: sometimes they infect the population just to see what happens...
Answer: First, observational studies can have control. Like prospective cohort studies (people choosing to smoke versus people choosing not to) or case-control studies (people with outcome versus people without outcome.) A more proper contrast for observational studies is probably "intervention studies" or "experimental studies", in which researchers get to assign exposures.
Back to your question. Most epidemiology journals do publish intervention studies such as clinical randomized controlled trials (RCTs; ex1, ex2, ex3, ex4), although it's true that they are rarer than observational designs. Most epidemiology courses and texts also include intervention study designs like clinical randomized controlled trials.
Answer: "All", "always", etc. are dangerous words.
Most epidemiology studies are observational - as a field epidemiology tends to concern itself with study questions that are not amenable to randomization and controlled trials. The dominant form of studies one would encounter while doing graduate work in epidemiology or working in a public health department, or reading epidemiology journals will be observational in nature - cross-sectional prevalence studies, cohorts, case-control studies, etc.
There are however caveats to this:
"all observational and not controlled": One of these things is not like the other. A study can be observational and controlled - if we just mean "people who didn't have the exposure/treatment/whatever" than the bulk of most cohort studies are controls. Case-control studies have "controls", but this means non-cases. In a study I've run, "control" meant "This hospital didn't have a particular policy in place". There isn't the deliberate assigning of people as controls as there is in a randomized trial, but depending on what one intends to convey by "control" it's possible for an observational study to have them. Equally, you can have a non-observational experimental study with no controls. That's probably not a good idea, but its certainly possible.
There are studies in epidemiology that are arguably not observational. The most obvious example of this would be mathematical modeling studies, which aren't really observational or randomized, but are definitively part of epidemiology. They also happen to be what I do.
Comment: +1 - but I just want to pinpoint that the "controls" in "case-control studies" are not the controls that the OP is referring to. It's not a coincidence that many people think that "case-noncase studies" would be a better name for those kind of studies. On a different note, from what I've been reading here on CV, it seems to me that your epidemiological research is really interesting, @EpiGrad
Answer: Epidemiologists use experiments and nonexperiments to learn about health and disease. Experiments provide a useful conceptual framework for learning about health and disease (see Hernan and Robins text Causal Inference, 2015).
Comment: I found you are stephen cole.
Answer: Of course not. Epidemiology is a vast field, including many smaller fields such as public health, educational sciences, etc. For example, many high-quality journals in public health accept and publish many clinical trials.
Comment: I'd argue that Epidemiology is a subset of Public Health, not the other way around.


Getting rid of password_confirm labels in module

Question: In a module, the following generates unwanted labels for 'Password' and 'Password confirm':
$form['password'] = array(
  '#type' => 'password_confirm',
  '#maxlength' => 20,
  '#size' => 10,
);

It produces the following HTML:

  Password
  <input class="password-field form-text" type="password" id="edit-password-pass1" name="password[pass1]" size="10" maxlength="128" />

  Confirm password
  <input class="password-confirm form-text" type="password" id="edit-password-pass2" name="password[pass2]" size="10" maxlength="128" />

The object is to get rid of the text labels and replace them with images.  I have tried toggling '#title', '#title_display' and '#label_display' but nothing works.
Any ideas?
Answer: I agree with @Clive that it is not a good idea to remove those labels, but there is a way to make them invisible, without to remove them. Drupal 7 has a CSS class for that purpose: element-invisible.
The code I would write is similar to the following one.
function mymodule_form($form, &$form_state) {
  $form['password'] = array(
    '#type' => 'password_confirm',
    '#maxlength' => 20,
    '#size' => 10,
    '#process' => array('form_process_password_confirm', 'code_testing_process_password', 'user_form_process_password_confirm'),
  );

  return $form;
}

function mymodule_process_password($element) {
  $element['pass1']['#title'] =  '' . t('Password') . '';
  $element['pass2']['#title'] =  '' . t('Confirm password') . '';

  return $element;
}

The process functions I am using are the same used from the "password_confirm" form field, except the second one, which is my custom process function I use to make the label invisible.
You could also replace the reference to form_process_password_confirm() if you want to radically change the output for the form fields. The last process function I am using is the one that adds the JavaScript code which checks when the password entered in the two form fields is the same, among other things.
Comment: I was looking for something like this and would have used it but was too far along with the CSS method by the time it was posted.  It's good to know though.  Thanks!
Answer: Replacing a label with an image isn't a good idea, mainly for accessibility reasons (an input without a label is a sure way to fail a WAI compliance test).
One simple option would be to set the dimensions and background image of the labels in CSS, and indent the text so it's not visible.
Something like
.form-item-password-pass1 label {
  display: block;
  width: 50px;
  height: 50px;
  background: url(/images/50x50.png) left top no-repeat;
  text-indent: -9999em;
}

That way you don't actually need to change the markup, and everyone gets the best of both worlds.
Comment: Thanks Clive, I was looking for a PHP module solution and don't like the text-indent trick but wound up using this solution.


Upgrade from Ubuntu Server 9.10 to 10.04

Question: Is there a best practice, meaning a particular script or procedure, that should be used to update from one version of Ubuntu Server to another? This would have to be without overwriting files/Apache sites living on the server. Is this something that could be done through Aptitude?
Answer: First thing: Make a backup. Then follow this documentation, which took me less than a minute to find.
Comment: Thanks, I realize Ubuntu has great documentation, was just asking for some feedback on best practices in case  there were recommendations outside the community docs. This content has led me astray in the past, albeit on more convoluted issues, but either way, thanks for pointing me in that direction.


pure virtual function and abstract class

Question: I have the following classes, Base and Derived and when I compile the compiler complains that it cannot create an instance of DLog because it is abstract.
Can someone tell me how I can fix this error?
I'm guessing it's because not both pure virtual functions are not implemented in the Derived.
class Logger
{
public:

    virtual void log(int debugLevel, char* fmt, ...) = 0;
    virtual void log(string logText, int debugLevel, string threadName = "") = 0;

    static Logger* defaultLogger() {return m_defaultLogger;}
    static void setDefaultLogger(Logger& logger) {m_defaultLogger = &logger;}

protected:

    static Logger* m_defaultLogger;
};

class DLog : public Logger
{
public:
    DLog();
    ~DLog();

    static DLog *Instance();
    static void Destroy();

    void SetLogFilename(std::string filename);
    void SetOutputDebug(bool enable);
    std::string getKeyTypeName(long lKeyType);
    std::string getScopeTypeName(long lScopeType);
    std::string getMethodName(long lMethod);

    virtual void log(string logText, int debugLevel)
    {
        Log(const_cast<char*>(logText.c_str()));
    }

    void Log(char* fmt, ...);

private:

    static DLog *m_instance;

    std::string m_filename;
    bool m_bOutputDebug;
};

// DLog instantion as a singleton
DLog *DLog::Instance()
{
    if (!m_instance)
        m_instance = new DLog();
    return m_instance;
}

Comment: You need to implement the PVFs in the derived class, obviously.
Comment: But there are two overloads of the `log` method, one with an ellipsis. Use Boost.Format or a similar technique instead.
Comment: Please please please, don't overload functions with an ellipsis. Will save you hours of hair-pulling and late night debugging.
Comment: @Alex:  Not an overload... its with a capital L the Log function.  the others are lower case...
Answer: virtual void log(string logText, int debugLevel, string threadName = "") = 0;

has not been implemented in class DLog. You have to implement it because it's pure virtual in the base class.
You probably meant this in your first overload of log in DLog:
virtual void log(string logText, int debugLevel, string /*threadname*/)
{
    Log(const_cast<char*>(logText.c_str()));
}

EDIT: You also have not implemented the overload of
virtual void log(int debugLevel, char* fmt, ...) = 0;

Note here though that using the const_cast is a very bad idea and is undefined behavior. You can get well defined behavior by doing something like this instead:
virtual void log(string logText, int debugLevel, string /*threadname*/)
{
    logText.push_back('\0'); // Add null terminator
    Log(&logText[0]); // Send non-const string to function
    logText.pop_back(); // Remove null terminator
}

Better yet though, just make "Log" const-correct in the first place.
Comment: @Tony: Some `std::string` implementations will have a null terminator there but they are not required to have one, unless you call the `c_str` member. However, you cannot modify the buffer returned by `c_str` and have well defined behavior.
Comment: I thought string was null terminated??  Or is it just a char* thats null terminated?
Answer: By deriving your DLog class from Logger you are assuring that you will provide the implementation for all (assuming you don't want DLog as an abstract class) pure virtual methods declared in the base class. Here you have not provided implementation to pure virtual functions hence class DLog becomes an abstract class. In C++ you can not create an instance of an abstract class hence you get the compiler error. BTW, your base class is missing the virtual destructor.


How do I increase windows service startup timeout

Question: I have migrated software to a very slow sever. Some software services refuses to startup because of system timeout. How do I increase timeout from default 30 sec.(?) to several minutes?
Thank you in advance!
Answer: You can modify the timeout value in the registry.

1. Click Start, click Run, type regedit, and then click OK.
2. Locate and then click the following registry subkey:
 - HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
3. In the right pane, locate the ServicesPipeTimeout entry.

**Note**: If the ServicesPipeTimeout entry does not exist, you must create it. To do this, follow these steps:

 - On the Edit menu, point to New, and then click DWORD Value.
 - Type ServicesPipeTimeout, and then press ENTER.
4. Right-click ServicesPipeTimeout, and then click Modify.
5. Click Decimal, type 60000, and then click OK.
 - This value represents the time in milliseconds before a service times out.
6. Restart the computer.

Comment: user149591 please mark this as the answer.
Comment: @Dominique 2 to the 32nd power, minus 1.  Not that a value that high will do you any good.  That's just how long Windows will wait... if a process is taking that long to start, it sounds to me like it's having trouble starting, and it might not be the Windows service timeout that's causing your pain.
Comment: For more discussion on how to control this timeout in other situations (Windows restart, etc) see this SO answer: https://stackoverflow.com/a/29928342/434413
Comment: @NickDeMayo Seeing as how he hasn't been back since August 19th, that seems unlikely to happen.
Comment: @HopelessN00b Can't mods mark stuff as answered on behalf of the users? :)
Comment: Does anybody know the maximum value for this registry entry? I've just tried putting 10 minutes (on Windows 10) and I have the impression my service already stops at 5 minutes.
Comment: I'm finding this works for `net stop` just fine as my batch files wait very long for big services to stop (MySQL8) but `net start` still times out and fails in my batch files soon after attempting to start.  Are there separate values for start/stop timeout?
Answer: Here is a quick one-liner, which can be executed from an elevated PowerShell prompt, that sets the pending service timeout to 3 minutes:
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control" -Name ServicesPipeTimeout -Value 180000 -Type DWord
Comment: Brilliant! Can't stand sludging through regedit.
Answer: Please find a visualized answer by appuals.com
Comment: Hi, and welcome! Thanks for your answer, but please follow the [guidelines](https://serverfault.com/help/how-to-answer). So: please answer with text and not just a picture (so it's easier to find and read), and add context to the link.


Create sorted HashMap from Stream Java 8

Question: I am converting a HashMap<String, Double> into a HashMap<String, Double> where the content is sorted by value. When I print out the following:
Stream<Map.Entry<String, Double>> sorted = map.entrySet().stream()
    .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).forEach(System.out::println);

the data is printed out in the correct order, sorted by value. However, I don't need to print out the data, I want to collapse the content of this stream into a new HashMap with the new sorted order. I tried a few options, but I seem to be getting back my original, unsorted HashMap when I do this:
return map.entrySet()
    .stream()
    .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
    .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()));

How can I modify the stream so that I send back the sorted HashMap?
Comment: does the first line of code even work?
Answer: The collector you used produces a HashMap by default, and HashMap doesn't have ordering.
You can use a different collector that would produce a LinkedHashMap, which preserves insertion order:
return map.entrySet()
    .stream()
    .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
    .collect(Collectors.toMap(entry -> entry.getKey(),
                              entry -> entry.getValue(),
                              (a,b)->a,
                              LinkedHashMap::new));

Comment: Yes, of course. I got so caught up in the higher-order functions that I forgot about the HashMap issue. Thank you!


Decreasing function made up of cubes, squares and floor function

Question: Let $t$ and $r$ be two integers with $r\geq 1, t\geq \frac{r}{2}$. Put
$$
f(r,t)=\lfloor 2(t^2+r)^{\frac{3}{2}}-(2t^3+3rt) \rfloor
$$
(here $\lfloor x \rfloor$ denotes the floor of $x$, i.e. the largest integer below $x$). Thus
$f(1,.)$ is identically zero, the first two values of $f(2,.)$ are $2$ and $1$, followed by zeroes.
It is easy to see that $f(r,t)=0$ whenever $t\geq \frac{3}{4}r^2$.
   Is it true that $f(r,.)$ is decreasing (as a function of $t$) for every
$r \geq 1$ ?
Comment: (Just an idea:) One way to get ahold ofthis problem is to fix $r$, and let $g(t) = 2(t^2+r)^{3/2} - (2t^3 + 3rt)$.  Compute $g'(t)$ to see that _eventually_ $g'(t) \leq 0$ for $t$ sufficiently large.
Answer: Assume that $t\ge 0$ and $r>0$, and set $g(r,t):=2(t^2+r)^{3/2}-(2t^3+3rt)$.  Then $\partial g/\partial t=6t\sqrt{t^2+r}-(6t^2+3r)$.  Now if we multiply by the conjugate
$$
(6t\sqrt{t^2+r}+6t^2+3r)(\partial g/\partial t)=-9r^2< 0,
$$
so we also have $\partial g/\partial t< 0$.  Therefore, $g(r,t)$ is nonincreasing in $t$, so $f(r,t)=\lfloor g(r,t) \rfloor$ must be as well.
Comment: More simply: Fix $r \geq 1$ and let $t > 0$.  As you say, it suffices to show that $g(t) = 2(t^2 + r)^{3/2} - (2t^3 + 3rt)$ is nonincreasing in $t$.  Compute

$$\begin{align}
&g'(t) = 6t(t^2 + r)^{1/2} - (6t^2 + 3r) \leq 0
\\
\iff &(t^2 + r)^{1/2} \leq t +\frac{r}{2t}
\\
\iff &t^2 + r \leq t^2 + r + \frac{r^2}{4t^2}
\\
\iff &\frac{r^2}{4t^2}  \geq 0
\end{align}$$
with the last statement being clearly always true.  Therefore $g(t)$ is decreasing in $t$ as desired.
Comment: @David: By the way, it took me a long time to correctly read your post.  I believe what you are saying is that if $h(t) = 6t(t^2 +r)^{1/2} + 6t^2 +3r$, then since $h(t) \geq 0$ for all $r,t$ and $\frac{\partial g}{\partial t} \cdot h(t) < 0$, it must be that $\frac{\partial g}{\partial t} < 0$ for all $r,t$.  Is that correct?
Comment: Re the comment by @JavaMan immediately above, that's correct.


parsing a line of text to get a specific number

Question: I have a line of text in the form "    some spaces  variable =         7     =    '0x07'  some more data"
I want to parse it and get the number 7 from "some variable = 7".  How can this be done in python?
Answer: I would use a simpler solution, avoiding regular expressions.
Split on '=' and get the value at the position you expect
text = 'some spaces variable = 7 = ...'
if '=' in text:
    chunks = text.split('=')
    assignedval = chunks[1]#second value, 7
    print 'assigned value is', assignedval
else:
    print 'no assignment in line'

Comment: While there's nothing wrong(?) with learning regex, and they can be useful, I am terribly fond of this quote: You have a matching problem, so you think "Aha! I'll use a regex!" Now you have two problems.
Answer: Use a regular expression.
Essentially, you create an expression that goes something like "variable = (\d+)", do a match, and then take the first group, which will give you the string 7. You can then convert it to an int.
Read the tutorial in the link above.
Answer: Basic regex code snippet to find numbers in a string.
>>> import re
>>> input = " some spaces variable = 7 = '0x07' some more data"
>>> nums = re.findall("[0-9]*", input)
>>> nums = [i for i in nums if i]  # remove empty strings
>>> nums
['7', '0', '07']

Check out the documentation and How-To on python.org.


Selenium with headless chromedriver not able to scrape web data?

Question: I wrote a simple program to scrape data from https://stats.nba.com. My code here works absolutely fine, as it is able to get the data from the website perfectly:
chrome_options = webdriver.ChromeOptions()
d = webdriver.Chrome(ChromeDriverManager().install(),options=chrome_options)
d.get('https://stats.nba.com/teams/advanced/?sort=W&dir=-1')
scrape = BeautifulSoup(d.page_source, 'html.parser').find('table')

for row in scrape.find_all('tr'):
    for col in row.find_all('td'):
    #...more parsing code here

However, as soon as I add
chrome_options.add_argument('--headless'), the entire code fails and I get AttributeError: 'NoneType' object has no attribute 'find_all'.
Why does this happen? I've looked everywhere and cannot find a solution. Thanks!
Edit: the problems seems to be that d.page_source gives different results for headless and non-headless. Does anyone know why there is a discrepancy?
Comment: Looks like you should check the contents of d.page_source and see what the problem is.
Comment: @Chris I just checked, and strangely, the headless output of d.page_source does not have the table I want; however, the non-headless output of d.page_source contains the table. Why would this discrepancy exist?
Comment: If there is no recaptcha or something similar it could be that the page renders differently for different viewports.
Comment: @borisdonchev How would I get around this?
Comment: Try adding something to change it like this for example: `chrome_options.add_argument("--start-maximized")`
Comment: @borisdonchev Already tried that, no luck. I think I may have to use a different webdriver or maybe even a different website for the data.
Answer: Edit:
I think I've found the solution. It appears that they have a system that checks the user-agent of the browser and they don't allow headless chrome
so try to add this to your code:
# ...
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
chrome_options.add_argument(f'user-agent={user_agent}')
# ...

This is the output that I receive from that:
scrape = BeautifulSoup(d.page_source, 'html.parser').find('table')
for row in scrape.find_all('tr'):
    print(row)

#

#
#
TEAM
# GP
# W
# L

Comment: Thank you so much for this solution. I've been stuck with this problem for an awkwardly long time and was on the verge of going insane.
Comment: @blueblast I edited the answer. You can check if it works now (:
Comment: Fantastic! I've been stuck on this for days and finally found this soulution. Thank you so much :)
Comment: Can you save the HTML content of the page and inspect it? There is a possibility that the content that you are receiving doesn't look like you expect it.
Comment: Yes, the HTML outputs are different for some reason when I run headless. I do not understand why


Erdos conjecture about Fat sequences?

Question: Some while ago i sat with my professor Adrian Stern of the Ben-Gurion University for a little more than half an hour, we talked about a lot of open question and cutting edge methods in math to tackle these problems.
So he told me about "Erdos Fat sequences conjecture" to be found in Wikipedia Erdős conjecture on arithmetic progressions
The conjecture simply says that if $A$ is a set of integers (sequence) and $A$ is fat meaning $\sum \limits_{n \in A} \frac{1}{n}  = +\infty$ then $A$ have a.p. of any length.
Since then i thought about many sequences that "disproof" the conjecture, i am not trying to solve the conjecture or anything, i am just baffled, that these sequences i came up with seems to falsify the conjecture.
For instance let $a_n = \lfloor 16 n \ln (16 n) \ln \ln (16 n) \rfloor$ starting with $A =\{45,137,251,379,517,665,819,980,1147,1319,\cdots \}$
The set $A$ obviously is fat since $\sum \limits_{n=1}^{\infty} \frac{1}{\lfloor 16 n \ln (16 n) \ln \ln (16 n) \rfloor}$ diverges.
Also the set $A$ have no a.p. of length $3$ or more.
So where did i get wrong, what mistakes have i done ?!
Any help is more appreciated.
Last thing, because in Israel we are in (Islamic,Jew) holidays, i could not ask my professor about the thing that baffled me, and the vacations in Israel continues till 26.10.2017, so its very long time to wait.
Comment: @Ahmad: that't for the case of length $3$.
Comment: How do you know it has no a.p. of length $>3$ ?
Comment: @Ahmad: the theorem doesn't say *contiguous* a.p.
Comment: How do you prove, that this has no a.p. of arbitrary length? Seems like for large enough n, the ln terms should "not change" (modulo rounding). This gives a a.p.
Comment: Proof of no arithmetic progression of length 3?
Comment: i think but not sure because $a_{n+1}-a_{n} > a_{n}-a_{n-1}$.
Comment: @YvesDaoust i know, but when every next term bigger then the current more than the current is bigger than the previous it seems there will never be a.p. of length $3$ or more ! (once again not sure), its more intuitive to me than a solid proof.
Comment: This reasoning makes no sense if you are allowed to skip elements.
Comment: so to make sure it does not have a.p. of length $3$ or more one have to prove that $a_{x}-a_{y}= a_{y}-a_{z}$ for some integer $x,y,z$ ?
Comment: A quick search (without careful rounding controls) gave $(a_{108},a_{109},a_{110})=(25877,25877+288,25877+2\times 288)$  But the real point here is that the theorem does not require consecutive entries.
Answer: To summarize the comments:
The key point is that the conjecture does not require the fat sequence to have consecutive terms in progression.
As it happens, this sequence has progressions of length $3$, even if you require consecutive terms.  For example, $$(a_{92},a_{93},a_{94})=(21336,21336+280,21336+2\times 280)$$
It is, however, easy to find fat sequences which do not have consecutive $3-$term progressions.  For example $$A=(1,2,11,12,21,22,\cdots)$$
Thus $A$ consists of $n\in \mathbb N$ such that $a\equiv 0,1\pmod {10}$.  Of course this sequence contains infinitely long progressions, but the terms are not consecutive.
Comment: Oh, this stuff is highly non-intuitive.  Kind of explains the basis for making the conjecture though...the obvious ways to block progressions is to put in increasing gaps, but that method more or less guarantees convergence of the sum.  Very hard to get a handle on the problem.
Comment: also to name few that are not consecutive entries $(9,18,26),(6,19,30),(7,26,42) , \cdots$ , oh boy, some times intuitive thinking could mislead you big time, i don't know how i did not see these obvious facts before.

Erdos conjecture about Fat sequences?


How to get add term form of taxonomy inside node type form?

Question: I'm trying to render taxonomy add term form inside content type ('article') add form. (node/add/article)
In hook_form_alter, I called this callback function on abutton.
public function _cvv_ajax_callback(VocabularyInterface $taxonomy_vocabulary) {
    $taxonomy_vocabulary = 'cvv';
    $term = \Drupal::entityManager()->getStorage('taxonomy_term')->create(['vid' => $taxonomy_vocabulary->id()]);
    return \Drupal::entityFormBuilder()->getForm($term);
  }

But this is not return form in my node/add page, rather giving me error:

error   php   Drupal\Core\Entity\EntityStorageException: Missing
  bundle for entity type taxonomy_term in
  Drupal\Core\Entity\ContentEntityStorageBase->doCreate()

I tried
if ($vocabulary = taxonomy_vocabulary_machine_name_load('jenis_dokumen')) {
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');
  $edit = array();
  $taxonomy_form = drupal_get_form('taxonomy_form_term', $edit ,$vocabulary);
  return drupal_render($taxonomy_form);
}

but this is also not working in Drupal 8.
Also tried:
 $form = \Drupal::formBuilder()->getForm('\Drupal\taxonomy\Controller\TaxonomyController::addForm','plan_features');

didn't worked :'(
Lastly I tried Inline Entity Form , the problem with module is, when a add term form get rendered inside node type form and if you do
kint($form_id); inside hook_form_alter, you won't get any form id for this inline form. Hence if you want to add custom validations for the term title, it won't be achievable even by hooks this module provides.
Please  suggest a way to do this.
Comment: What was the error message of the second one?
Answer: Have you tried this module? It's pretty much what you could need:
Inline Entity Form
Comment: This is a good solution, Inline Entity Form is on by default on D8 Lightning distribution.
Comment: But altering inline entity form is also a big trouble. Because this module provides 3 hooks. So I want to add custom validation on term name, it is not achievable through these hooks.
Comment: Also, there's no way even to get the form id of the form rendered by "Inline Entity form."
Answer: Your first solution should work. Use the name of the vocabulary instead of the id ..
$term = \Drupal::entityManager()->getStorage('taxonomy_term')->create(['vid' => $taxonomy_vocabulary->label()]);


Are there hidden technical difficulties for vocalists when they transpose?

Question: I am not a vocalist, but an instrumentalist.
When I want to transpose something up or down a half step, this takes considerable work: different hand/chord shapes on the piano, completely different fingerings on a brass or woodwind instrument, etc.
I have always assumed that transposition for vocalists is a relatively simple exercise, and that the only consideration that comes into play is range: transposing something up or down could make the higher or lower notes more difficult, but that's pretty much it.
Am I correct here, or are there other hidden difficulties for vocalists when they transpose?
Answer: Depending on how the vocalist initially learned their song, remembering the transposed version can be surprisingly nightmarish. If the vocalist learned the song by ear from a single recording, they can no longer pitch-match to any version in their head when singing a transposed version. If the vocalist learned the song from sheet music, they just might be trying to transpose the song on the fly by transposing every individual note on the sheet music by the same amount instead of transposing the first note and using intervals between sung notes from there.
Comment: +1, a lot of musicians have better (partial) pitch memory than they are aware of, and they often encounter difficulty while transposing without quite realizing why. Also, professional singers are very aware of their "money notes" and register shifts, and transposing by a whole tone definitely interferes with this.
Answer: Apart from your observations about each end of the range - both that of the vocalist and that of the song - I haven't found any technical difficulties. Certain sounds are more difficult to song well, particularly at the top end, when tansposed higher.
It's strange, but I don't even consider what happens when I sing a particular song in a different key. Not even consciously thinking in intervals. Very slightly similar to playing something on guitar or bass, merely by shifting everything up or down. There's the obvious more stretch there when playing in a lower key, more squash in a higher key, but that's the instrument. But everything basically the same.
So, no technical difficulties or challenges such as are found on most instruments - which often need complete changes of fingering, embouchure, etc. An interesting one would be to give a good sight-singer some dots, but an incorrect start note/key. Without absolute pitch, I doubt it would come out 'wrong'.


Laravel, aumentar os campos padrão da autenticação User, já pronta no laravel via composer

Question: Olá queria aumentar o número de campos do formulário de autenticação para inserir novos campos.

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('users');
}
}

Eu queria colocar mais campos para inserir via formulário, tanto a validação como no insert.

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('senha');
        $table->string('endereco');
        $table->string('cidade');
        $table->string('telefone');
        $table->string('razao_social');
        $table->string('cnpj')->unique();
        $table->rememberToken();
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('users');
}
}

Alguém pode me ajudar a me informar aonde fica estes campos?
Comment: Ai tem um porém, antes ou depois de rodar o primeiro migration de `users` tem diferenças nos comandos!
Comment: relacionada: http://pt.stackoverflow.com/a/165058/54880
Answer: Para adicionar campos extras no usuário padrão do laravel, faça as seguintes alterações:
database/migrations/xxxx_xx_xx_xxxxxx_create_users_table.php
Schema::create('users', function (Blueprint $table) {
    ...

    $table->string('phone')->nullable();

    ...
}

Agora, atualize seu modelo para acompanhar as mudanças da migration, adicione dentro da propriedade fillable os novos atributos.:
app\User.php
class User extends Authenticatable
{
    ...

    protected $fillable = [
        'phone',
    ];

    ...
}

Agora você deve alterar o validador dentro do controller padrão de autenticação, vamos adicionar uma validação simples para a nova propriedade dentro do método validator. Veja como ficou:
app\Http\Controllers\Auth\AuthController.php
protected function validator(array $data)
{
    ...

    return Validator::make($data, [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6|confirmed',
        'phone' => 'string|min:8|max:13',
    ]);

    ...
}

Adicione também a propriedade dentro do método create no mesmo arquivo:
protected function create(array $data)
{
    ...

    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'phone' => $data['phone'],
    ]);

    ...
}

Por último, você deve adicionar o novo campo dentro do seu código html da forma que desejar, mas, com o mesmo nome que você adicionou no método create do controller. Os formulários padrões de login e registro, normalmente se localizam em resources/views/auth/login.blade.php e resources/views/auth/register.blade.php.
O melhor a se fazer, é ler a página de autenticação na documentação oficial do Laravel, é bem simples e detalhado.


Question regarding Bayes rule

Question: I know that Bayes rule states
$P(X|Y) = P(X  and  Y)/ P(Y)$
What happens if P(X|X>=Y)?
Will I divide by marginal probability of Y or P(X>=Y). For instance how would I approach problem given following PMF
<code>X/Y          1            4
1            0.018        0.153
2            0.045        0.18
5            0.235        0.369
</code>
Comment: What you cite as "the Bayes rule" is instead actually the definition of conditional probability (a closely related formula, to be sure).  One can appy that "PMF" (probability mass function) data for the joint distribution of $X$ and $Y$ to evaluate any well-formulated conditional probability.  But if $X$ is a random variable, so that typically an outcome is a real number (about which one might ask whether $X\gt Y$), one does not say "What is $P(X)$?", the probability of $X$.  You are perhaps asking about expected values of random variables (conditioned on $X\gt Y$)?
Comment: As written this doesn't make sense.  To have the notation $P(X|Y)$ be meaningful, you need $X$ and $Y$ to be events, but to have $X > Y$ you need $X$ and $Y$ to be random variables.  Do you have a particular problem you're interested in?
Comment: Yes, I am talking about random variables here.
Comment: $P(X>Y)$ can be expressed as $1-P(X<Y)$, which is $1-F(x)$ where $ F$ is cdf of $Y$.
Comment: @DavidS So how would the entire formula look like ?
Comment: @MichaelLugo I have added the problem
Comment: @hardmath yes!!
Answer: In the formula
$$ P(A | B) = \frac{P(A \cap B)}{P(B)}$$
$A$ and $B$ are, to start with, events (of which $B$ must have non-zero probability).  By a slight abuse of notation, we write the same when $X,Y$ are random variables.
$$ P(Y | X) = \frac{P(X\cap Y)}{P(X)}$$
but here the events are to be understood as the particular values that each variable can take . That is, by $P(X)$ we mean $P(X=x)$, and so on. This can also be generalized to continuous variables, using densities. All this is explained in the Wikipedia.
The expression $P(X|X \ge Y)$ has no problem, you just need to remember that the condition is an event. If you feel unsure, write it more explicitly:
$$P(X=x|X \ge Y)=\frac{P(X=x \cap X \ge Y)}{P(X \ge Y)}$$
From your table, the numerator and denominator should be easily computable, by summing the corresponding terms.
This should also make you clear that $P(X|Y)$ depends on two variables (in your example, you should compute $6$ values, while $P(X|X \ge Y)$ depends only on $X$ (you must compute $3$ values)
Comment: Thanks a bunch!
Comment: Please answer one last question. I am just confirming here. P(X=1 | X=1 >= Y) = (0.171 * 0.018)/ 0.018. Given that P(x=1) = 0.171. Is this correct? Repeating the same process for every x and then adding it up
Comment: No, that's wrong. Remeber, The denominator (the condition) is a plain event, it does not depend on the value of $x$!.
Comment: $P(X=1 \cap X \ge Y) = 0.018$ , $P(X\ge Y)=0.018+0.045+0.235+0.369$
Comment: Makes sense. Thanks again!
Comment: @hardmath Fixed. thanks.

Question regarding Bayes rule


On h:commandLink Ajax Success/Failure open Modal Dialog

Question: I have implemented an action bar with different command links firing ajax calls. My backing bean handles those actions.
<a4j:commandLink value="Save" action="#{actionHandler.perform('save')}" execute="@form"
oncomplete="" onerror="">
</a4j:commandLink>

OR
<h:commandLink value="Save">
  <f:ajax execute="@form" actionListener="#{actionHandler.perform('save')}"
</h:commandLink>

What i want to achieve is that for every commandlink in my action bar when ajax call has success/failure then show a modal dialog alongth with current performed action specific information like header, message, redirect URL etc. In other request/response based framework we normally return a JSON respone and act accordingly. But i dont know how can we achieve this here. I looked at Richfaces(the framework in use) rich:popupPanel but could not find any way to pass parameters to popup. Any suggesstion?
Answer: You can use a4j:commandLink (or a4j:commandButton). Example (from RichFaces 4.3 project):
<a4j:commandLink action="#{bean.setupTransactionDetails}"
    event="onclick" render="transactionDetails"
    oncomplete="#{rich:component('transactionDetails')}.show()"
    styleClass="richLink">
    <h:outputText value="#{res.transactionType}" />
    <f:setPropertyActionListener value="#{res.transactionId}"
        target="#{bean.transactionId}" />
</a4j:commandLink>

Where #res.transactionId is parameter, transactionDetails is name of popup.


what to be carefull when rebuilding primary AD domain controller?

Question: I just did some search such as this one and this to avoid asking a question which already has answer.
However, I'm not sure whether the information fully match my question or not.
The situation is, I'm currently maintaining a test environment under a business domain. There are two windows 2016 AD domain controllers acting as primary DC and second DC respectively, and are apparently linked together to provide domain services.
These two domain controllers only have basic roles running: domain services and dns, and all the nodes/clients in this domain are managed by them.
Now, the primary DC encountered unexplainable issues and I have no choice but to delete the whole machine and rebuild a new primary DC to replace it.
I have no experience on "rebuilding" the "primary" domain controller, does anyone know what to be aware of when doing such thing? Or maybe I can just delete the primary DC and recreate it without making any changes on second domain controller?
thanks in advance.
Answer: Notice that while you designate one of your controllers as "primary", there is no such concept in the Active Directory technology. The NT4 "PDC" functionality was essentially split a "primariness" into several Flexible Single Master Operation (FSMO) roles, which can be assigned to different DCs, and then there will be no signle controller which can be designated "primary" at all. That was done 22 years ago, and yet many people still use ancient and irrelevant NT4 terminology!
So, the general DC "rebuilding" strategy applies. After each step you should check your replication is consistently working, and group policies on the SYSVOL share are available. You begin by fixing replication issues (if any), then move all assigned FSMO roles away from the controller you are about to demote, and then you demote it, updating DNS. After reinstalling and promoting a new DC you may reassing some FSMO roles to it or leave them where they are — it doesn't matter much.


Suppose $f$ is differentiable on $\mathbb{R}$ and $f'(0)$ is positive

Question: (a) Must there be an interval around $0$ on which the derivative remains positive?
(b) Is there an open interval around $0$ on which $f$ is increasing?
For (a) I believe the answer is yes because $f$ is differentiable and the derivative $f'(0)$ exists.
Since $f'(x) = lim_{x \rightarrow 0} \dfrac{f(x)-0}{x-0}>0$,
then
$lim_{x \rightarrow 0-} \dfrac{f(x)-0}{x-0}>0$ and $lim_{x \rightarrow 0+} \dfrac{f(x)-0}{x-0}>0$
Am I on the right track here?
As far as (b) is concerned, I thought I would use the Mean Value Theorem and define the interval around $c>0$, but I know I can't start with point $c$ and from there find an interval $(a,b)$, so maybe there's another way, like Darboux's Theorem?
Thanks in advance!
Comment: For (a), take the function in http://math.stackexchange.com/questions/292275/discontinuous-derivative and add $x$. This gives a counterexample.
Comment: No to both questions. Answers will be yes if $f'$ is continuous at $0$. Hence one must construct a counter-example example where $f'$ is discontinuous at $0$.
Answer: The counter-example from user detnvvp's answer shows that the answer to both your queries is NO. I want to address some concerns over your approach in this answer.
You start off with $$f'(x) = \lim_{x \to 0}\frac{f(x) - f(0)}{x - 0} > 0$$ I think there is a typo and the correct equation is $$f'(0) = \lim_{x \to 0}\frac{f(x) - f(0)}{x - 0} > 0$$ And then you show that the corresponding one sided limits are also positive. From that you get two things (which you should have tried to work out):
1) There is an $h > 0$ such that $f(x) > f(0)$ for all $x \in (0, h)$.
2) There is a $k > 0$ such that $f(x) < f(0)$ for all $x \in (-k, 0)$.
Such a behavior is expressed by saying that $f$ is strictly increasing at point $0$. But note that this is not the same as saying that $f$ is increasing in some interval containing $0$. Precisely we can't combine 1), 2) above to say that $f$ is strictly increasing in $(-k, h)$.
Thus you should not expect the answer of $(b)$ to be affirmative.
Regarding $(a)$ note that continuous functions have sign preserving property i.e. if $f$ is continuous at $a$ and $f(a) \neq 0$ then $f$ has same sign as that of $f(a)$ in some interval containing $a$.
So the answer to $(a)$ is affirmative if $f'$ is continuous at $0$. But we are not given this so we should not expect an affirmative answer for $(a)$.
Answer: (b) is wrong: to see that, consider the function $$f(x)=\left\{\begin{array}{c l}x^2\sin\frac{1}{x}+\frac{1}{2}x, & x\neq 0 \\ 0, & x=0\end{array}\right..$$ Then $f'(0)=\frac{1}{2}>0$, but $f$ is not increasing on a neighborhood of $0$. To see that, consider the derivative at any $x>0$: $$f'(x)=2x\sin\frac{1}{x}-\cos\frac{1}{x}+\frac{1}{2},$$ which changes sign infinitely often as $x\to 0^+$.
Comment: The same example shows that $(a) $ is also false.
Comment: This is actually a direct proof of (a), although for (b) we only need note that $f'(x) \ge 0$ and $f(x)$ increasing are equivalent for a differentiable function on an open interval


Executar outra ação durante um await Task.Delay

Question: Estou fazendo uma aplicação onde chega uma determinada parte do código em que preciso colocar um:
 await Task.Delay(tempo);

Porem, ao mesmo tempo em que tenho que esperar esse tempo eu preciso executar uma ação de 10 em 10 minutos.

Já quebrei a cabeça pensando em como posso fazer isso e nada veio em mente.
Gostaria de saber se é possível fazer isto e como.
Comment: Chama outro thread com alguma atividade para ser executada em paralelo.
Answer: Bom dia,
Pelo que você informou você necessita de uma nova thread para realizar a ação de 10 minutos. Neste caso você tem duas possibilidades simples de utilizar:

Task: você cria uma nova Task da biblioteca System.Threading.Tasks com um while e um await Task.Delay(tempo); assim a task será executada constantemente, no caso da task ele executa a ação e depois de completamente executada a ação vai chegar no delay e esperar o tempo determinado;
Task _task_execucao_leitura;
void main(){
    _task_execucao_leitura = tf.StartNew(this.metodo_desejado);
}

async void metodo_desejado(){
    while (true)
    {
        await Task.Delay(_tempo_ler_dados);
        ação desejada
    }
}

Timer: uma outra opção utilizar um Timer da biblioteca do System.Threading esta ação executa uma ação em um intervalo determinado, no fim do intervalo a ação é executada novamente, tendo ela sido finalizada na primeira execução ou não;
Timer timerLeitura;
void main(){
 timerLeitura = new Timer(new TimerCallback(leituraMetodo), null, tempoInicio, tempoLeitura);

}

void leituraMetodo(object obj)
{
    ação desejada
}

Answer: Você pode fazer desta forma também:
void DoWorkPollingTask()
{
    Task.Run(async () =>
    {
        while (true)
        {
            // Faça alguma coisa...
            await Task.Delay(time_to_sleep);
        }
    });
}

Desta forma você irá rodar o método de forma assíncrona e em paralelo com outras atividades.


Using a Eigen type inside boost graph

Question: I've got some Eigen alignment issues when adding a vertex to the following graph:
<code>#include <boost/graph/adjacency_list.hpp>
#include <Eigen/Eigen>

struct Vertex
{
   EIGEN_MAKE_ALIGNED_OPERATOR_NEW
   Eigen::Affine3d T; // Here is the Fixed-size vectorizable Eigen object
};

struct aligned_listS { };

namespace boost
{
  template <class ValueType>
  struct container_gen<aligned_listS, ValueType>
  {
    typedef std::list<ValueType, Eigen::aligned_allocator<ValueType> > type;
  };
}

typedef boost::adjacency_list< boost::listS, aligned_listS, boost::directedS, Vertex> MyGraph;

int main(int, char*[])
{
   Vertex v;

   MyGraph g;
   boost::add_vertex(v, g);

   return 0;
}
</code>
At run time,I have the following error message:
<code> /usr/local/include/eigen3/Eigen/src/Core/DenseStorage.h:56: Eigen::internal::plain_array<T, Size, MatrixOrArrayOptions, 16>::plain_array() [with T = double, int Size = 16, int MatrixOrArrayOptions = 0]: Assertion `(reinterpret_cast<size_t>(array) & 0xf) == 0 && "this assertion is explained here: " "http://eigen.tuxfamily.org/dox-devel/TopicUnalignedArrayAssert.html" " **** READ THIS WEB PAGE !!! ****"' failed.
</code>
It seems that either the aligned_listS template argument is not set at the good place or my aligned allocator is not well defined.
So I'm looking for some hints on how making this aligned allocator works properly.
Here is the full gdb backtrace if it can help:
<code>#0  0xb7fdf1b2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
#1  0xb7d401df in __GI_raise (sig=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
#2  0xb7d43825 in __GI_abort () at abort.c:91
#3  0xb7d39085 in __assert_fail_base (fmt=0xb7e76c38 "%s%s%s:%u: %s%sAssertion `%s' failed.\n%n",
    assertion=0x804b324 "(reinterpret_cast<size_t>(array) & 0xf) == 0 && \"this assertion is explained here: \" \"http://eigen.tuxfamily.org/dox-devel/TopicUnalignedArrayAssert.html\" \" **** READ THIS WEB PAGE !!! ****\"", file=0x804b2ec "/usr/local/include/eigen3/Eigen/src/Core/DenseStorage.h",
    line=56,
    function=0x804b5e0 "Eigen::internal::plain_array<T, Size, MatrixOrArrayOptions, 16>::plain_array() [with T = double, int Size = 16, int MatrixOrArrayOptions = 0]") at assert.c:94
#4  0xb7d39137 in __GI___assert_fail (
    assertion=0x804b324 "(reinterpret_cast<size_t>(array) & 0xf) == 0 && \"this assertion is explained here: \" \"http://eigen.tuxfamily.org/dox-devel/TopicUnalignedArrayAssert.html\" \" **** READ THIS WEB PAGE !!! ****\"", file=0x804b2ec "/usr/local/include/eigen3/Eigen/src/Core/DenseStorage.h",
    line=56,
    function=0x804b5e0 "Eigen::internal::plain_array<T, Size, MatrixOrArrayOptions, 16>::plain_array() [with T = double, int Size = 16, int MatrixOrArrayOptions = 0]") at assert.c:103
#5  0x08049f1c in Eigen::internal::plain_array<double, 16, 0, 16>::plain_array() ()
#6  0x080499f1 in Eigen::DenseStorage<double, 16, 4, 4, 0>::DenseStorage() ()
#7  0x0804935a in Eigen::PlainObjectBase<Eigen::Matrix<double, 4, 4, 0, 4, 4> >::PlainObjectBase() ()
#8  0x08048ec7 in Eigen::Matrix<double, 4, 4, 0, 4, 4>::Matrix() ()
#9  0x08049d71 in Eigen::Transform<double, 3, 2, 0>::Transform(Eigen::Transform<double, 3, 2, 0> const&) ()
#10 0x080496c0 in Vertex::Vertex(Vertex const&) ()
#11 0x080496e9 in boost::detail::adj_list_gen<boost::adjacency_list<boost::listS, aligned_listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>, aligned_listS, boost::listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>::config::seq_stored_vertex::seq_stored_vertex(Vertex const&) ()
#12 0x080491cc in boost::detail::adj_list_gen<boost::adjacency_list<boost::listS, aligned_listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>, aligned_listS, boost::listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>::config::stored_vertex::stored_vertex(Vertex const&) ()
#13 0x08048df3 in boost::detail::adj_list_gen<boost::adjacency_list<boost::listS, aligned_listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>, aligned_listS, boost::listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>::config::vertex_descriptor boost::add_vertex<boost::adjacency_list<boost::listS, aligned_listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>, boost::detail::adj_list_gen<boost::adjacency_list<boost::listS, aligned_listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>, aligned_listS, boost::listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>::config, boost::directed_graph_helper<boost::detail::adj_list_gen<boost::adjacency_list<boost::listS, aligned_listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>, aligned_listS, boost::listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>::config> >(boost::detail::adj_list_gen<boost::adjacency_list<boost::listS, aligned_listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>, aligned_listS, boost::listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>::config::vertex_property_type const&, boost::adj_list_impl<boost::adjacency_list<boost::listS, aligned_listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>, boost::detail::adj_list_gen<boost::adjacency_list<boost::listS, aligned_listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>, aligned_listS, boost::listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>::config, boost::directed_graph_helper<boost::detail::adj_list_gen<boost::adjacency_list<boost::listS, aligned_listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>, aligned_listS, boost::listS, boost::directedS, Vertex, boost::no_property, boost::no_property, boost::listS>::config> >&) ()
#14 0x080489be in main ()
</code>
Comment: I don't get this error. What compiler version and Eigen version are you using?
Comment: I'm running Ubuntu 12.04 and using g++ (4.6.3), with Eigen 3.1.3 and boost 1.52.0. To compile, I used the command "g++ graph.cpp -I/usr/local/include/eigen3", and no other flags.
Comment: EDIT: class Vertex -> struct Vertex, as EIGEN_MAKE_ALIGNED_OPERATOR_NEW must be public.
Answer: A way to go around is to have the following graph definition :
<code>typedef boost::adjacency_list< boost::listS, boost::listS, boost::directedS, boost::shared_ptr<Vertex> > MyGraph;
</code>
And in this case, this code does not generate the assert.
<code>   boost::shared_ptr<Vertex> ptr(new Vertex(v));
   boost::add_vertex(ptr, g);
</code>
In this case, the Eigen macro seems to make the job. However, I still don't understand why the first code is not running. Using a pointer is more a patch than the solution...

Using a Eigen type inside boost graph


Find an equation in spherical coordinates for the surface represented by the rectangular equation

Question: The rectangular equation is
$$x^2+y^2-8z^2=0$$
$$x^2+y^2=8z^2$$
Know in the relationship between rectangular and spherical coords. we can manipulate our given to fit the form:
$$x^2+y^2+z^2=9z^2$$
$$\rho=x^2+y^2+z^2, \space z=\rho\cos(\phi)$$
$$\rho^2=9\rho^2\cos^2(\phi)$$
$$1=9\cos(\phi)$$
$$\frac{1}{3}=\cos(\phi)$$
$$\arccos(\frac{1}{3})=1.23 \space rads$$
And so the equation in spherical coords. is $\phi=1.23$
I know my math is correct but I have the wrong answer so I'm not sure where I went wrong.
Comment: It seems to me that you took only the conical surface for positive $z$. You can also have $\cos\phi=-\frac 13$
Comment: What is supposed to be the right answer?
Answer: Your calculation is almost right indeed the surface is a cone with equation in spherical coordinates $$\phi=\arctan (2\sqrt 2)=\arccos \left(\frac 13\right)$$
$$\phi=\pi-\arctan (2\sqrt 2)=\pi-\arccos \left(\frac 13\right)$$
assuming $\phi \in[0,\pi]$.
Following your steps, from here
$$1=9\cos^2(\phi)$$
we obtain indeed
$$\cos (\phi)=\pm \frac13 \implies \phi=\arccos \left(\frac 13\right),\,\phi=\pi-\arccos \left(\frac 13\right)$$


How to add Colorbox to a field in a twig template?

Question: I have a site with various products on it. So I created node--product.html.twig. I then removed this from my twig template:
{{content}}

Because I want to display fields myself in a custom format, without relying on Drupal's built-in display. So for the most part this was easy, as I could do this:

This works perfectly. But my problem is that I want the user to be able to click on this image and see it in a modal view, but USING the Colorbox module.
Is there another way to output this field in the twig template so that it automatically loads colorbox and everything that is needed?
Answer: You really would want to use:
{{ content.field_product_image }}
The field display setting will pass the image style to it, and I assume colorbox has a field formatter or tie in here as well. Supply a field Twig template to strip extraneous markup divs.
Comment: But how does this work for fields that have multiple values?
Comment: This is a good question.
Comment: Shouldn't that be the responsibility of the field formatter?


Understanding a part in a solution.

Question: I was reading this question Showing this to $1 \leq p < \infty$ ,  here on this site.
But I did not understand this part (in the third solution mentioned there given by @mechanodroid):
" Now notice that for large enough $t_0 \ge 1$ we have $t \ge t_0 \implies \ln t \le \sqrt[2p]{t}$ so the above integral can be bounded by
$$\int_1^{t_0}\frac{(\ln t)^p}{t^2}\,dt + \int_{t_0}^{+\infty}\frac{dt}{t^{3/2}} < +\infty$$
which is finite since $\frac{(\ln t)^p}{t^2}$ is bounded on $[1,t_0]$ and $t \mapsto \frac1{t^{3/2}}$ is integrable on $[1, +\infty)$."
Could anyone clarify this part for me, please?
2- Also for the second solution given by @Awegan, I can see a typo in $p$ and $q$, the powers of $L$, am I correct?
3- Also, is there an alternative proof (detailed) for the question given in the link I mentioned above?
Answer: $$\int_1^{t_0}\frac{(\ln t)^p}{t^2}\,dt + \int_{t_0}^{+\infty}\frac{dt}{t^{3/2}} < +\infty$$
Since the integrand of the left hand integral is bounded, then
$$\int_1^{t_0}\frac{(\ln t)^p}{t^2}dt\leq M(t_0-1),$$
where $M$ is the bound (see here). Clearly this is finite.
For the right hand integral, just evaluate it, e.g.
$$\int_{t_0}^\infty\frac{dt}{t^{3/2}}dt=\left[-\frac{2}{\sqrt{t}}\right]_{t_0}^{+\infty}=\frac{2}{\sqrt{t_0}},$$
which is also finite.
The sum of two finite numbers gives a finite number, so by definition of $L^p$ spaces $f\in L^p(0,1]$.

In answer to your comment, here's a plot of $\log t$ (in blue) and $t^{1/(2p)}$ for $p=1.4$, for example. As you can see, $t_0\approx 35$ in this case, after which the inequality holds true for $t\geq t_0$. This always happens for some $t_0$ value.
Comment: @Mathstupid yes, check out https://math.stackexchange.com/questions/1663818/does-the-logarithm-function-grow-slower-than-any-polynomial
Comment: @Mathstupid pretty much, yes. I mean $t>1$ so $\ln t$ behaves nicely, so that you get a continuous function $(\ln t)^p/t^2$, so since we consider integrating over $(1,t_0)$ then there must be some maximum $M$ of that function in $(1,t_0)$.
Comment: What about the rest of my questions?
Comment: @Mathstupid re (2) I think you may be right, there is a typo, check out this for comparison: https://math.stackexchange.com/questions/390227/proving-that-lp-subset-lq-when-1-le-q-le-p
Comment: And why we are assuming "for large enough $t_0 \ge 1$" ?
Comment: Why "$\ln t \le \sqrt[2p]{t}$"?
Comment: Is there any mathematical proof for my last question other than the drawing?
Comment: why the integrand of the left hand integral is bounded?
Comment: Is this because it is a continuous function (as it is a rational function of a continuous ln function in the numerator and a polynomial (continuous) in the denominator) on a closed interval  ?

Understanding a part in a solution.


Existence of non-trivial bounded linear functionals with a quasi-norm

Question: Is it well known, and easy to prove, that if we define the norm of $L^p$ with $p<1$ in the usual way, $ \| \cdot \|_{L^p} $ is not actually a norm because it does not satisfy subadditivity. At the same time, if there is a linear functional $l$ that satisfies $$|l(f)| \le M \|f\|_{L^p} $$ for all $f \in L^p$ and some $M > 0$, then $l=0$.
I wonder whether it is generally true that with a quasi-norm $\mathcal{N}$, which violates subadditivity, the only bounded linear functionals is trivial (if we pretend $\mathcal{N}$ is a norm).
In particular, I have the following example in mind (from Exercise 15 in Chapter 2 of Stein and Shakarchi's Functional Analysis).

Consider the weak-type space, consisting of all functions $f$ for which $m(\{ x : |f(x)| > \alpha \}) \leq \frac{A}{\alpha}$ for some $A$ and all $\alpha > 0$. One might hope to define a norm on this space by taking the "norm" of $f$ to be the least $A$ for which the above inequality holds. Denote this quantity by $\mathcal{N}(f)$.

We can show that $\mathcal{N}(f)$ is not a genuine norm because it does not satisfy subadditivity through the following example.

The function $f(x) = 1/ | x |$ has $\mathcal{N}(f) = 2$. But if $f_N = \frac{1}{N} [f(x + 1) + f(x + 2) + \cdots + f(x + N)]$, then $\mathcal{N}(f_N) \ge c \log N$.

The textbook also claims that this space has no non-trivial bounded linear functionals.
Comment: L_p with $0<p<1$ is metrizable and the metric $d(f,g)=\|f-g\|^p_p$ I makes the space a complete metric spca. The bounded sets are similar to the case $p\geq1$
Comment: @Oliver Díaz, I knew. That's why I wrote "if ..." The point is not that we can find a well-behaved norm, but rather that if we treat a non-norm as if it were a norm, we would have trouble finding non-trivial bounded linear functionals.
Comment: That is why I also added a description of the bounded sets which is all you need to determine whether an operator is bounded or not…
Comment: [This](https://math.stackexchange.com/q/4556006/121671) may be of interest to you
Comment: For functional s on L_p with $0<p<1$ this [posting](https://math.stackexchange.com/q/4413489/121671) may also be of interest
Comment: Thank you @OliverDíaz. I've corrected a few minor errors in [this](https://math.stackexchange.com/q/4556006/121671). (Submitted. Not sure if they are visible to you.)
Comment: (+1) Thanks for the edit. Do the postings I referred to you answer you question? Or there is something else I am missing.
Comment: @OliverDíaz In the weak-type example that I have posted, the relevant quasi-norm is $L^{\infty,1}$. I don't see how to use either the information in your postings, or $d(f,g) = \|f-g\|_p^p$ for $L^p$, to prove the non-existence of a non-trivial bounded linear functional with $L^{\infty,1}$.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/140599/discussion-between-petra-axolotl-and-oliver-diaz).
Comment: Are you still interested in this problem?
Comment: Yes. I tried to prove that $L^{\infty,0}$ is not locally convex without success. So I decided to take a break and come back to the problem later. Ideally I would want a proof as simple as Proposition 1 in [your post](https://math.stackexchange.com/a/4418268/291842).
Answer: The answer to the OP is no, it is not true in general. The key issue is local convexity.
In the context of the OP's posting, a quasi-metric space $X$ is a non empty set $X$ along with a function $\rho:X\times X\rightarrow[0,\infty)$ such that

$\rho(x,y)=0$ iff $x=y$,
$\rho(x,y)=\rho(y,x)$ for all $x,y\in X$,
there is $K\geq1$ with $\rho(x,y)\leq K(\rho(x,z)+\rho(z,y))$ for all $x,y,z\in X$.
When $X$ is a vector space with a quasi-metric $\rho$ that is translation invariant ($\rho(x_z,y+z)=\rho(x,y)$ for all $x,y,x\in X$), and homogenous ($\rho(cx,cy)=|c|\rho(x,y)$ for all $x,y\in X$ and $c\in\mathbb{F}$) quasi metric, then $\rho$ is a quasi-norm and $(X,\rho)$ a quasi-normed space.

The quasi-metric $\rho$ induces a topology $\tau(\rho)$ on $X$ which can be construct by uniformities: The sets $U_r=\{(x,y): \rho(x,y)<r\}$ form a basis for a uniformity; in fact the collection $U_{1/n}$, $n\in\mathbb{N}$, is a countable basis for the uniformity, and so $(X,\tau(\rho))$ is metrizable (see, Kelly, J. General Topology, Springer-Verlag, chapter 6).
A more direct result by Macías-Segovia and  later by Aimar, Jaffei and Nitti (see Paluszynski, M and Stempak, P., On quasi-metric and metric spaces, Proceedings of the AMS, Vol 137, 12, 2009, pp. 4307-4312)  states that

Proposition: If $(X,\rho)$ is a quasi-metric (resp. quais-normed) space, then
there is $0<p\leq1$ ($p=\tfrac{\log(2)}{\log(2K)}$) and a metric (resp. norm) $d_p$ on $X$ such that
$\tilde{\rho}:=d^{1/p}$ is a quai-metric (resp. quasi-norm) on $X$ equivalent to $\rho$ (i.e., $c\rho\leq\tilde{\rho}\leq d\rho$ for constants $c,d>0$);
furthermore,
$$\tilde{\rho}(x,y)\leq \Big(\tilde{\rho}^p(x,z)+\tilde{\rho}^p(z,y)\Big)^{1/p},\qquad x,y,z\in X$$

It is clear that the topology induced by the quasi-metric $\rho$ and the metric $d_p$  are the same.
If $X$ is a quasi-normed vector space, ans  $d_p$ is complete, the $(X,d_p)$ is an $F$-space. Examples of this situation are already mentioned by the OP: $L_p(X,\mathscr{F},\mu)$ for $0<p<1$ with $\rho(x)=\|x\|_p$ and $L^{\infty,p}(\mathbb{R},\mathscr{B}(\mathbb{R}),m)$ ($m$ Lebeusge measure on the line with $\rho(x)=\sup_{t>0}\{t m^{1/p}(|x|>t))$ with $0<p\leq 1$. These spaces are not normable (there is no norm equivalent to $d_p$) since  $L_p$ ($0<p<1$ ) is not (in general) locally convex, and neither is $L^{\infty,1}(\mathbb{R})$. Hence their dual spaces are trivial.
This is in contrast to $L_p(\mu)$ with $p\geq1$ or $L^{\infty,p}(\mu)$ with $p>1$. The former is already a complete normed space; the later has a norm $\newcommand\vertiii[1]{{\left\vert\kern-0.25ex\left\vert\kern-0.25ex\left\vert #1
    \right\vert\kern-0.25ex\right\vert\kern-0.25ex\right\vert}}
\vertiii{\;}_p$ that is equivalent to the quasi-norm $[\;]_p$ (see this posting for example).
Comment: @PetraAxolotl: To show that the space is not locally convex is enough to consider one neighborhood of the form $B(0;r)$ and show that there are elements in that neighborhood say, $f_1,\ldots,f_m$ such that a (not every, but just some) convex combination $f:=\alpha_1 f_1+\ldots + \alpha_m f_m$ ($0<\alpha_j<1$, $\sum^m_{j=1}\alpha_j=1$) is not in $B(0;r)$.
Comment: I completely get it that if a quasi-norm is not locally convex, the dual space must be trivial. What I think is still missing is that $L^{\infty,1}(R)$ is not locally convex. (I have not studied topology. In fact, local convexity is so far not even mentioned in the textbook I am using. So an elementary proof would be much appreciated!)
Comment: The example $f_N$ shows that $L^{\inty,1}$ is not, for $f_N$ is a convex combination of functions in the *ball*  $B(0;2)$.
Comment: I understand. My question is whether the existence of such $f_N$ necessarily means that *every* other function $f$ is also a convex combination of functions in a neighbourhood the origin. In the other proof of yours about $L^p, p<1$, it was explicitly shown to be valid for all $f$.
Comment: I see. Thanks a lot!
Answer: There are examples of such spaces which do have non trivial linear functionals.  For example the discrete version of $L^p$, i.e. $\ell^p$.  Point evaluations do the trick.  (If you want a silly example, take a finite dimensional space and put a suitable quai-norm on it).