Insert value to field programmatically and remove cache from field

Question: I have content type feature and i have field hit_count in this c.type, also i have db table - hit_count - example:
nid   hit_count

1     434
2     233
3     512

I want to output hit_count inside my field - hit_count on current node(also should appear on node edit). So for example if node id is 1, field hit_count = 434, and if admin want to edit this field i want to update field value to my table hit_count with current nid and field value hit_count.
To save value into my database table i will use hook_node_update and just get fields nid and hit_count values and update my table.
But i don't know what hook should i use or how to insert this value from database to my field. There are lots of nodes with content type feature.
UPDATE

My first thought is - why do you use a separate db table for this rather than simply using an integer field in the content type?

Hit count module was created long time ago, client wanted to disable/enable statistics for every content type, so default statistics module does not fit our needs. And now client want to manage this hit counts for certain nodes etc...
Also i managed to insert value to edit form on hook_exit updated custom hit count module.
function hit_count_exit($destination = NULL) {
    if ($node = menu_get_object()) {
        $selected_types = array_filter(variable_get('hit_count_content_types', array()));
        if (!empty($selected_types)) {
            if (in_array($node->type, $selected_types)) {
                db_update('node_hit_counter')
                        ->expression('totalcount', 'totalcount + 1')
                        ->condition('nid', $node->nid)
                        ->execute();
                if($node->type == 'feature') {
                    $val = db_query("SELECT * FROM {node_hit_counter} WHERE nid='$node->nid'")->fetchAll();
                      db_merge('field_data_field_hit_count_node')
                        ->key(array('entity_id' => $node->nid))
                        ->fields(array(
                                'entity_type' => 'node',
                                'bundle' => 'feature',
                                'deleted' => 0,
                                'entity_id' => $node->nid,
                                'revision_id' => $node->nid,
                                'language' => 'und',
                                'delta' => 0,
                                'field_hit_count_node_value' => $val[0]->totalcount,
                        ))
                        ->execute();
                }

            }
        }
    }
}

But right now i see next problem. I need to get rid of Drupal field cache, cuz i see cached value every time i reload page, and if i clear all caches i get current value of hit_count.
Comment: My first thought is - why do you use a separate db table for this rather than simply using an integer field in the content type?
Comment: To update a field on your edit form, you can use hook_form_alter() http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7
Comment: updated my question, i solved one problem but got another) with `drupal field cache` i need to get rid of it
Answer: I also think you could use an integer field on the node for this - but keeping that aside, the  problem you are facing (the inserted value not being refreshed by the cache) is caused by the fact that you are trying to write in the database table field_data_field_hit_count_node directly. This is definitely discouraged, and you should be using the proper API instead.
Instead of db_merge('field_data_field_hit_count_node')->...->execute() you would want to do something like:
$node->field_hit_count_node[LANGUAGE_NONE][0]['value'] = $val[0]->totalcount;
$node->save();

Doing it this way ensures that the saving is done by Drupal, the caches are cleared as required, hooks as called as necessary, etc.
In addition if you don't mind using the entity module, then you can do this with Entity Metadata Wrappers in a simpler way:
$nw = entity_metadata_wrapper('node', $node);
$nw->field_hit_count_node = $val[0]->totalcount;
$nw->save();

Comment: gonna look at `entity_metadata_wrappers`


Homology of a space obtained from $S^n$ by attaching a cell $e^{n+1}$ by a map of degree $m$

Question: I am trying to understand how to use cellular homology on this simple example: let $X$ be a space obtained from $S^n$ by attaching a cell $e^{n+1}$ by a map of degree $m$. I understand that the generators of the group $H_k(X^{(k)},X^{(k-1)})$ are in one-to-one correspondence with the $k$-cells of $X$, and I am supposing the CW structure of $S^n$ with 2 cells in each dimension. But how do I calculate the $Ker(d_k)$ and $Im(d_k)$, where $d_k$ are the boundary maps in the cellular chain complex? I know about the cellular boundary map formula, but I understand how it works on this example.
Answer: Chain complex for an easier CW structure.
Well, first it is easier to compute the homology if you use the CW structure on $S^n$ having one $n$-cell and one $0$-cell. The cellular chain complex just looks like $$\mathbb{Z}\to0\to\cdots\to0\to\mathbb{Z}$$ or if $n=1$, then $\mathbb{Z} \overset{0}\to\mathbb{Z}$.
Then if you adjoin one more cell via a degree $m$ map, by definition this gives you a cellular chain complex $$\mathbb{Z} \overset{m}\to\mathbb{Z}\to0\cdots\to0\to\mathbb{Z}.$$ Following the instructions for the cellular boundary formula, as on page 140 of Hatcher, there is really no work to do here since in this case the complement of our cell in dimension $n$ is already just a point.
Chain complex for the CW structure having two cells in each dimension.
If you are really set on using the CW structure with two cells in each dimension, it takes a little more work to find the cellular chain complex for $S^n$. Also there is some amibiguity here in that there is more than one CW structure with two cells in each dimension that produces $S^n$. Of course the chain complexes will all be quasi-isomorphic, but if you do it in an organized way then you will get $$\mathbb{Z}^2 \overset{d_n}\longrightarrow \mathbb{Z}^2 \overset{d_{n-1}}\longrightarrow \cdots \overset{d_1}\longrightarrow\mathbb{Z}^2$$
where each of the $d_i$ are just given by the matrix $\begin{pmatrix}1&-1\\1&-1\end{pmatrix}$. I will describe how to do this below. Once you see this, then attaching the $n+1$ cell via a degree $m$ map should give you
$$\mathbb{Z} \overset{\begin{pmatrix}m\\ m\end{pmatrix}}\longrightarrow\mathbb{Z}^2 \overset{d_n}\longrightarrow \mathbb{Z}^2 \overset{d_{n-1}}\longrightarrow \cdots \overset{d_1}\longrightarrow\mathbb{Z}^2.$$
Computing $d_{n+1}$ with the cellular boundary formula.
To compute that $d_{n+1}$ is as above using the cellular boundary formula, consider the two $n$-cells in $S^n$, one for each hemisphere. The coefficient of $d_{n+1}(e^{n+1})$ on the top hemisphere is obtained by crushing the lower hemisphere and checking the degree of the map $$\partial D^{n+1} \to S^n \overset{\text{crush}}\longrightarrow S^n.$$ By the local degree theorem, this only depends on the size of the preimage at a suitable point - but this is the same as for the original map since all we did was crush the lower hemisphere. So the degree of this map is still $m$. The same logic applies to the coefficient on the cell for the lower hemisphere.
Seeing that $d_i = \begin{pmatrix}1&-1\\1&-1\end{pmatrix}$.
Label the cells in dimension $k$ by $e^k$ and $f^k$, which will be the correct ordered basis for the matrices above. Here is how to define attaching maps so that all chain maps are given by the matrix above.
Consider the $k$-skeleton $S^k$ inside of the plane $\mathbb{R}^{k+1}$ in $\mathbb{R}^{k+2}$ (you should probably take $k=1$ for visualization purposes).
Above $S^k$ in $\mathbb{R}^{k+2}$ is the top hemisphere of $S^{k+1}$ which is isomorphic to $D^{k+1}$ via the projection map. The attaching map is the identity, so as above we have that $d_{k+1}(e_{k+1}) = e_k + f_k$. The lower hemisphere of $S^{k+1}$ is isomorphic to $D^{k+1}$ as well, but the orientation of the boundary is the opposite, relative to $S^k$. To see this, note that the attaching map is the same identifying $e^k$ with the upper hemisphere, reflecting through $\mathbb{R}^{k+1}$, then attaching along the identity map. So, the cellular boundary formula tells you $d_{k+1}(f_{k+1}) = -e_k - f_k$.


Depicting complex numbers

Question: Sorry for a stupid question but how would you depict
$0\leq arg(z)\leq \frac{7\pi}{3}$ on the complex plane?
Is this a circle or is it going to be the the same as when you depict $0\leq arg(z)\leq \frac{\pi}{3}$?
(Suppose $|z|=1$)
Answer: Firstly, as a geometrical angle, it is clear that whole circle rotations do not change the point, so angles differing by an integer multiple of $2\pi$ radians (a complete circle) are the same, as reflected by the figure below. Similarly, from the periodicity of $\sin (x)$ and $\cos (x)$, the definition
$$
z=r\left( \cos \varphi +i \sin \varphi \right)=re^{i \varphi}$$
also has this property. The argument of zero is usually left undefined.
Answer: It will be a circle, since all points with argument in the interval $[0,2 \pi)$ satisfy the inequality.

Depicting complex numbers


Formatar resultado em JSON com os dados retornados a cada 30 minutos

Question: Há pouco tempo atrás, fiz esta pergunta: Recuperar parâmetro para filtro em SQL: data e hora a cada minutos
Agora preciso que o resultado seja no formato igual JSON ao abaixo:
<code>{label:'00:00', y:92 , indexLabel:'92'},
{label:'00:00', y:92 , indexLabel:'92'},
{label:'01:00', y:92 , indexLabel:'92'}
</code>
Como fazer?
Comment: E qual o problema? O que você fez e qual erro ocorreu?
Comment: Poderia detalhar melhor sua resposta?
Comment: Agora o sentido da pergunta mudou completamente, deixou de ser um problema de javascript para ser um problema no back-end PHP.
Answer: Você pode tentar o seguinte código:
<code>for($hora= 0; $hora < 24; $hora++){
    $hoje = new DateTime();
    for($minuto = 0; $minuto <= 30; $minuto += 30){
        $data_hora = $hoje->format('Y-m-d') . ' '  // dia mes e ano de hoje
            . str_pad($hora, 2,'0', STR_PAD_LEFT)   // hora do primeiro loop (formatado com zero à esquerda)
            . ':' . str_pad($minuto, 2,'0', STR_PAD_LEFT) . ':00'; // minutos do segundo loop (formatado com zero à esquerda)

        // nota: os segundos estão fixos em 00 (linha acima)

        $resultado[] = processa_query($data_hora ); // chama a função que irá processar o sql
    }
}

// monta o resultado em $JSON e exibe o mesmo, o implode junta a array em uma string
echo $JSON = '{ "dados":[' .  implode(', ', $resultado) . ']}';

function processa_query($data_hora){

    $sql = "SELECT valor FROM valores where data_hora < '$data_hora' order by id desc limit 1  ";
    $consulta = $pdo->query($sql);
    $resultado = $consulta->fetchAll(3);

    $valor_equipamento = $resultado[0][0];

    // através do explode, separo a data da hora (separados pelo espaço)
    $hora_minuto = explode(' ' ,$data_hora);
    // removo os segundos
    $hora_minuto = substr($hora_minuto[1], 0,5);
    // monto um item o JSON concatenando:
    // label: recebe a variável $hora_minuto
    // y: recebe o $valor_equipamento (sem aspas)
    // indexLabel: recebe o $valor_equipamento (com aspas)
    return "{label:'$hora_minuto', y:$valor_equipamento , indexLabel:'$valor_equipamento'}";
}
</code>
Comment: Duplicou de http://pt.stackoverflow.com/a/148798/3635, se já existia resposta então não duplique por favor.
Comment: @GuilhermeNascimento: O correto seria ele editar a pergunta anterior para alterar o resultado de saída? Que antes eram apenas data e hora e agora seria JSON?
Comment: A pergunta foi marcada como duplicata, se você acha que não é então deve votar por reabrir. O que pode ser bem correto já que aqui fala do JSON.
Comment: @GuilhermeNascimento, não estou questionando não... só quero entender o que seria melhor para a comunidade... ele deveria alterar a primeira pergunta que desejava saber como retornar as horas... e já tinha sido respondida e abrir outra para formatar a saída com JSON, ou seria melhor ele editar a pergunta?
Comment: Eu entendi, acho que você deveria manter ambas respostas, mas explicar esta aqui melhor e modificar esta pergunta e votar para reabrir, já que aqui é outro problema. O problema que o AP é quem não soube perguntar, pois ele já tinha a resposta, só faltava a parte do JSON, mas ele preferiu repetir o problema. Então para melhor proveito é editar a pergunta mesmo. Claro que isso é opinião minha :)
Comment: @GuilhermeNascimento, muito obrigado pela explicação. Para mim que tinha falado com o autor da pergunta pelo chat estava claro, mas realmente a pergunta estava confusa e parecia duplicada. Já fiz a edição... porém ainda não sei ou não tenho privilégio suficiente para votar para fechar ou reabrir. Muito obrigado pela atenção.
Comment: só recomendo que explique o código atual, pois tem a explicação de como fez o 24horas, mas não tem a explicação da concatenação e do implode, só uma dica para enriquecer a resposta ;) ... PS: votei por reabrir.
Comment: Reabri, mas acho que é bom o autor da pergunta ficar mais atento para explicar melhor as próximas duvidas, pois me parece falta de esclarecimento na anterior. (na verdade se já é o que está respondido, não precisava nem reabrir, mas enfim...)
Comment: @Bacco, agradeço ... foi falha minha, pois como falei com ele no chat e ele é um usuário de baixa pontuação, eu deveria ter orientado ele melhor.  Serve de experiência para as próximas.
Comment: @GuilhermeNascimento, explicações adicionadas!
Comment: Adicionei um pequeno detalhe


two different edge color map on the same graph?

Question: I have done the following code to plot colors of nodes and edges color map from files :
## NODES COLORS##
Active={}
with open('NWWE/node'+str('{:03d}'.format(i))+'.txt', 'r') as f:
    for j in f:
        a,b=j.split(',')
        Active[a]=b[0]
for node in G.nodes():
        G.node[node]['category'] = Active[node]
color_map = {'0':'b', '1':'r'}

##EDGES COLOR MAP##
with open('NWWE/edges'+str('{:03d}'.format(i))+'.txt', 'r') as f:
    for k in f:
        a,b,c=k.split(',')
        G[a][b]['weight']=float(c)

edges,weights = zip(*nx.get_edge_attributes(G,'weight').items())

##DRAW GRAPH##
nx.draw(G, pos, edgelist=edges, edge_color=weights, width=5.0, edge_cmap=plt.cm.Blues, node_color=[color_map[G.node[node]['category']] for node in G])

But I have two kind of possible connection between nodes, with for each kind different possible weights, so I would like to plot my graph using two different color maps for edges. Is there any issue ?
Thanks a lot !
Answer: I found solution thanks to nx.draw_networkx_edges :
#one group with one color map :
edges = tuple(list_edgesG1)
weights = tuple([G[e][f]['weight'] for e,f in edges])
nx.draw_networkx_edges(G, pos, edgelist=edges, edge_color=weights, width=3.0, edge_cmap=plt.cm.Reds)

#the other group with different color map :
edges2 = tuple(list_edgesG2)
weights2 = tuple([G[e][f]['weight'] for e,f in edges2])
nx.draw_networkx_edges(G , pos, edgelist=edges2, edge_color=weights2, width=3.0, edge_cmap=plt.cm.Blues)


Display PDF file in modal window using PartialView

Question: In my Asp.Net Core (MVC, core 2.2) I use a sort of a generic modal pop-up throughout the website.
In the Layout page I have the basic code for the modal:

function showGenericModal(event) {
    var src = event.target || event.srcElement;

    // find the parent that contains proper decorations
    var url = $(src).closest("*[data-url]").data('url');

    // trigger an HTTP GET
    $.get(url, function (data) {
        // fill content and show modal
        $('#modalGeneric').html(data);
        $('#modalGeneric').modal('show');
    });
}

and I can then call it (open) with a link like this:

That calls an action from the controller and opens the required PartialView that has the rest of the modal code. And it works.
Following the examples from this post: How to display .pdf file in modal window? I want to show a PDF in my modal pop-up.
So, I added this two Actions to my Controller:
public IActionResult PdfPartial(int id)
{
    ViewBag.Id = id;
    return PartialView("_PartialDocumentPreview");
}

public async Task<IActionResult> ShowModalDocument(int id)
{
    var file = _docs.GetDocument(id);

    file.Contents = await _docs.Download(doc);

    var contentDisposition = new System.Net.Mime.ContentDisposition
    {
        FileName = file.Title,
        Inline = true
    };

    Response.Headers.Add("Content-Disposition", contentDisposition.ToString());

    var memory = new MemoryStream(file.Contents);
    return File(memory.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf);
}

and the PartialView ("_PartialDocumentPreview"):

            <embed  src="@Url.Action("ShowModalDocument", "ZavarovalnePolice",
            new { id = @ViewBag.Id })" type="application/pdf"
            style="width:100%; height:100%"/>

        <button type="button" class="btn btn-outline-warning"
            data-dismiss="modal">Close</button>

The PDF opens, but not in a modal pop-up, rather as a new page (with a url like: https://localhost:123/ZavarovalnePolice/PdfPartial/1.
What I'm doing wrong that it doesn't open as a pop-up?
EDIT (as per @Rena suggestion in the answer below) -
I just changed the href to data-url and it works:

Comment: Could you share more details about your controller and entire view code?About what is your `_docs` and  `item.id`.
Comment: `_docs` is a repository with methods that return document (attachment) data from the DB and `item.id` is the ID of the document from the view model. I'll try your workaround from below answer
Answer:
What I'm doing wrong that it doesn't open as a pop-up?

That is because you add href in your  link,it would get into the PdfPartial action by default,no need to add it if you use jQuery.
Here is a simple workaround like below:
1.View:

show the pdf
@section Scripts{

}

2.Controller:
public IActionResult PdfPartial(int id)
{
    ViewBag.Id = id;
    return PartialView("_PartialDocumentPreview");
}

public async Task<IActionResult> ShowModalDocument(int id)
{
    string filePath = "~/file/test.pdf";
    var contentDisposition = new System.Net.Mime.ContentDisposition
    {
        FileName = "test.pdf",
        Inline = true
    };
    Response.Headers.Add("Content-Disposition", contentDisposition.ToString());
    return File(filePath, System.Net.Mime.MediaTypeNames.Application.Pdf);
}

3.pdf would pop-up so small by using default css style,you could add css style like below in your main view not partial view:


How can I parse an XML file stored in blobstore on Google App Engine?

Question: I need to parse an XML file stored in the blobstore. How do I do that?
This is  what I have done till now:
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.getBlobFile(new BlobKey(key));

I cannot parse the XML file using javax.xml package or can I? The classes in that package if put into action requires a reference of a java.io.File object. But I do not have that.
This is what I have been doing till now : (not on the server but locally)
         File blobKeys = new File("/home/non-admin/NetBeansProjects/Personal Site_Testers/web/xml/xml_1.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(blobKeys);
        Element root = doc.getDocumentElement();

        Element firstName = doc.createElement("first-name");
        firstName.setTextContent(name);

        root.appendChild(firstName);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("/home/non-admin/NetBeansProjects/Personal Site_Testers/web/xml/xml_1.xml"));
        transformer.transform(source, result);

Note : There are 3 xml files uploaded to the blobstore. Those xml files just have a root tag . I want to get the xml reference and parse them to append child node several times depending upon the request made.
Comment: Maybe this can help you: http://code.google.com/p/gaevfs/
Comment: @WimDeblauwe How will **that** help me ?
Comment: It was just something I found that might be useful in getting an actual File object. But I think the suggestion from @zsxwing is much better. You should use the FileService as he says.
Answer: If you want to parse *.xml, I think jdom2 may be is more convenient which I use in the app engine and it works.
However, you can read the FileService API document and there is an example with how to read and write the file. If you can get a InputStream or Reader, then you can use javax.xml to parse the xml  content in the InputStream or Reader.
    FileService fileService = FileServiceFactory.getFileService();
    AppEngineFile readableFile = new AppEngineFile("your_file_name");
    FileReadChannel readChannel = fileService.openReadChannel(readableFile,
            false);
    InputStream input = Channels.newInputStream(readChannel);

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(input);

    Element root = doc.getDocumentElement();

    Element firstName = doc.createElement("first-name");
    firstName.setTextContent("content");

    root.appendChild(firstName);
    // Now write
    GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
            .setBucket("mybucket").setKey("myfile")
            .setMimeType("text/html").setAcl("public_read")
            .addUserMetadata("myfield1", "my field value"); // change as
                                                            // your need
    AppEngineFile writableFile = fileService.createNewGSFile(optionsBuilder
            .build());
    FileWriteChannel writeChannel = fileService.openWriteChannel(
            writableFile, false);
    OutputStream output = Channels.newOutputStream(writeChannel);

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    DOMSource source = new DOMSource(doc);
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StreamResult result = new StreamResult(output);
    transformer.transform(source, result);

Comment: I want to parse xml with high layer of abstraction that javax.xml offers when computing locally
Comment: Do you create the XML yourself as well? You might want to try [XStream](http://xstream.codehaus.org/) if you just want to serialize and deserialize objects to/from XML in a high level way
Comment: There are 3 xml files uploaded to the blobstore. Those xml files just have a root tag . Now I want to get the xml reference and parse them to append a child node. This is all I want to do.
Comment: Do you mean that you want to parse the xml file and append something to some nodes? What's the problem when you try to do it?
Comment: First, you can get a Reader of the xml file. Then, you use javax.xml APIs to parse the Reader. I think it's OK. What's error when you try to do like this?
Comment: I try to show a demo that how to use the FileService and javax.xml APIs.
Comment: Maybe you just need new FileInputStream(file)?
Comment: **Nothing gets written to the `xml` file in the blobstore when I try the above code.I check the blobstore and it same as before with the just a root tag.**
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/16067/discussion-between-suhail-gupta-and-zsxwing)
Comment: I have posted some code there. Unable to identify what is going wrong. There are no error logs but the xml doesn't get written
Comment: can you please help me find what is wrong in the code posted @ http://chat.stackoverflow.com/rooms/16067/discussion-between-suhail-gupta-and-zsxwing


How to derive the density of Gaussian Copula?

Question: I have a question regarding Gaussian copulas:
The multivariate Gaussian copula is defined as,
$$
C(u_1,\dots,u_n;\Sigma) = \Phi_{\Sigma}(\Phi^{-1}(u_1),\dots,\Phi^{-1}(u_n)),
$$
where $\Phi_{\Sigma}$ is a multivariate $n$-dimensional normal distribution with correlation matrix $\Sigma$ and $\Phi$ is the standard univariate cumulative distribution function. How can we show that the corresponding density
is:
\begin{align}
  c(u_1,\dots,u_n;\Sigma) &= \frac{1}{\sqrt{\mbox{det} \Sigma}}\exp
        \begin{pmatrix} - \displaystyle{\frac{1}{2}}
          \begin{bmatrix}
           \Phi^{-1}(u_1) \\
           \vdots \\
           \Phi^{-1}(u_n)
          \end{bmatrix}^{T} [\Sigma^{-1} - I ]
          \begin{bmatrix}
           \Phi^{-1}(u_1) \\
           \vdots \\
           \Phi^{-1}(u_n)
         \end{bmatrix}
    \end{pmatrix},
\end{align}
where $I$ is the identity matrix?
Comment: which source is that multivariate formula from?
Answer: Let $x=[\Phi^{-1}(u_1),\ldots,\Phi^{-1}(u_n)]^{\top}$. Then
\begin{align}
c(u_1,\ldots,u_n;\Sigma)&=\frac{\partial^nC(u_1,.\ldots,u_n;\Sigma)}{\partial u_1\cdots\partial u_n}=\frac{\Phi(x;0,\Sigma)}{\prod_{i=1}^n \phi(x_i)} \\
&=(2\pi)^{-\frac{n}{2}}|\Sigma|^{-\frac{1}{2}}\exp\!\left(-\frac{1}{2}x^{\top}\Sigma^{-1}x\right)\times\prod_{i=1}^n (2\pi)^{-\frac{1}{2}}\exp\!\left(\frac{1}{2}x_i^2\right) \\
&=|\Sigma|^{-\frac{1}{2}}\exp\!\left(-\frac{1}{2}x^{\top}\Sigma^{-1}x+\frac{1}{2}x^{\top}x\right) \\
&=|\Sigma|^{-\frac{1}{2}}\exp\!\left(-\frac{1}{2}x^{\top}(\Sigma^{-1}-I)x\right).
\end{align}
Comment: which source is that formula  for the density of the multivariate copula from?


Prevent webpage dialog from spawning new browser window?

Question: I have an open web page dialog.  From there, what I'd like to do is when the user clicks on a link, refresh the contents of the dialog with modified query string parameters.  The problem I am running into is that rather than refresh the same web page with new parameters, a new browser window pops up.
Here is the page used to open the dialog:
<!DOCTYPE html>

<title></title>

    Click For Modal

and this is the code within the webpage dialog that attempts to refresh the webpage with changed query string parameters:
<!DOCTYPE html>

<title></title>

Please Click Me

I've also tried using window.open as well as setting window.location.  And I've also tried setting window.location.href but the result was the same.
the new browser window displays exactly what I expect.  It's just not in the same window.
Thoughts?
Answer: Since posting this question, I came up with two possible solutions.  In case anyone comes after me and wants to know what I ended up doing, here you go!
The first was just to make the popup non-modal.  Removing the modal piece gave me the behavior exactly like I expected it.  This didn't work in my situation however for a different reason...  It seems that the session cookie was not carried over which in this web app, would cause the log-in page to be displayed before then displaying the correct page.  This struck me as odd, but ran out of time to investigate why that was happening.
Second (and this is the solution i ended up going with) was to use an iframe, and display what i needed within the iframe.  Definitely not my favorite, but it works!


Configurar o JDK no Android Studio

Question: Preciso configurar o caminho do JDK no Android Studio via terminal sem acesso root para um script. O computador tem o JDK/JRE 7, tentei alterar o valor de algumas variáveis: PATH, JAVA_HOME, JDK_HOME, STUDIO_JDK, ... .
No terminal o jdk 8 funciona alterando o valor do PATH, mas quando abro o Android Studio ele só reconhece o JRE.

Graficamente via Project Structure eu consigo mudar o JDK, mas preciso que seja via CLI.

Alguém sabe?
Comment: Ate onde sei quando altera o PATH pelo terminal, normalmente é temporário, o PATH é alterado somente para aquela janela/instancia do terminal, por isso não efeta o Android Studio. Para ser permanente acho meio dificil sem root.
Comment: O PATH alterado dessa forma é temporário, mas isso não tem relação na influência com o Android Studio, pois o que conta é como está na hora e a ideia do script é sempre alterar antes de abrir.
Answer: O Android Studio usa a varíavel JAVA_HOME para obter a versão do Java. Você precisa utilizar o comando abaixo informando o seu respectivo local do Java:
export set JAVA_HOME=/usr/lib/jvm/java-8-oracle/

Esse caminho do default-java não contém o Java 8, você vai precisar instalá-lo. Para a instalação, siga o manual.
Comment: Eu havia alterado essa variável, mas isso só faz o Android Studio reconhecer o jre, o JDK não.
Comment: Mas você colocou com o caminho do JDK? Se colocar com aquele default vai apontar pra um JRE mesmo.
Comment: Coloquei, tanto que quando coloco o valor da variável JAVA_HOME no campo JDK Location da GUI funciona.

Configurar o JDK no Android Studio


Very high condition number

Question: I am solving a linear system of equations with a condition number of 10^18 with matlab with double precision. As I know  as a rule of thumb every power of 10 in condition number reduces one significant digit of the answer and hence with double precision I have no significant digit remained. However, the solution seems correct, since it is the answer to an elasticity Finite element problem which I know its answer. How is it possible? does matlab "A\b" uses special preconditioners?
Comment: From wikipedia: "[...] the condition number does not give the exact value of the maximum inaccuracy that may occur in the algorithm. It generally just bounds it with an estimate (whose computed value depends on the choice of the norm to measure the inaccuracy)." Hence, a large condition number is no guarantee for a bad solution. You can use the spparms('spumoni',2) command to get more information about what algorithm backslash invokes for your particular matrix.
Comment: Have you looked at the spectrum of singular values of your matrix?  Is it simply rank deficient (a reasonable range of singular values with a sudden drop-off to effectively 0 singular values) or is there exponential decay in the singular values?  Have you checked the discrete Picard condition?
Answer: The standard condition number can be arbitrarly bad estimator of sensivity of solution to numerical errors, especially if matrices $A$ or $A^{-1}$ are badly scaled.
The standard condition number should not be used to test accuracy of solution to linear equations using the LU method (as in Matlab). Lapack does not use this, but uses much more accurate (and fast) componentwise error estimator similar to the Skeel condition number:
$$cond(A,x) = \frac{\||A^{-1}||A||x|\|_{\infty}}{\|x\|_{\infty}}$$
where $x$ is the true solution to $Ax = b$.
Problems with this condition number are well explained in Higham, Nicholas J. Accuracy and stability of numerical algorithms. Siam, 2002. This books also provides good alternatives, unfortunately unavailable in Matlab standard library.

Very high condition number


Comparing two groups of incidence rates

Question: Thank you for your time with this question.
I'm trying to answer whether an exposure is correlated to incidence of disease. I have a group of 100 counties in California,  and I have the incidence of disease among exposed people in those counties as well as incidence of disease among nonexposed people in each county.
For example, the data looks like, County A, exposed 5.6 , nonexposed 6.8, County B,  exposed 3.3, nonexposed 3.2, etc. etc. up to 100 counties in California.
I also have various sociodemographic variables for each those 100 counties. Some of these variables can be separated by exposed and non-exposed.  For example, I have median income of exposed and nonexposed, average household value of exposed and nonexposed, and percentage of exposed and nonexposed on private insurance. I also have other variables that are strictly by county, meaning there is no breakdown of exposed or nonexposed (these include things like average age of the county, % of each race and/or ethnic background, % male/female).
I am curious as to what would be the best way to actually see if there are differences in incidence rates between exposed and unexposed in California, and whether those differences are truly attributable to the exposure.
I was doing some reading, and came across propensity score matching, but notice that that's mostly used for treatment and outcome type data, instead of exposure and  incidence type data. Would something like a logistic regression to find significant covariates and then controlling for those do the trick?
Would greatly appreciate any advice here.
Thank you
Answer: If you want to compute a causal effect you need to control for confounders. The problem is, that you really need to find all confounders, otherwise your results are not reliable, and in the worst case nasty things like Simpson's paradox could happen.
Now, you mentioned covariates like age, race, and sex, for which you only have data averaged over exposed and nonexposed. That means you cannot control for them. And while I don't know the details of your scenario, I think that those covariates could easily be confounders.
In general, if you knew all the confounders and had always the data separated for exposed and nonexposed, you could use propensity score matching or regression or a mixture of both using MatchIt. Exposure can be understood as some type of treatment and incidences are valid outcomes.

Comparing two groups of incidence rates


Sort Part Numbers by First Character in Excel

Question: I have an excel document with about 12,000 lines of part numbers with pricing information. I think the most intuitive way to sort them would be as follows:
1, 12, 15, 100, 10003, 2, 2002, 20005000, 3, 30, 333, 4, 5, 6, 700000, 800000.
All the numbers that begin with 1 are in the same spot, same with all 2 prefixes, etc. My problem is, excel's default sorting method sorts it like THIS:
1, 20, 30, 40, 100, 150, 200, 250, 500, 1000, 1500, 2000, 10000.
So it sorts them in regular ascending order, which I think makes it more difficult to find your part number, especially as they get super long as some of them do.
I don't have a lot of resources outside of excel at my workspace, so I would like to stick to using that. My knowledge of excel also isn't too impressive, so please treat me like an idiot!
Answer: To make thing easier to describe, let's assume that your list of part numbers is in column A, and that you have a blank column B.
In cell B2 enter this formula:
=TEXT(A1,"#")

Copy that down as far as your list goes.
Now, selecting both columns, Custom Sort by column B.
That's it.
Comment: Thank you very much for your help! I got it working now :)
Answer: With data in column A like:

In B1 enter:
=CHAR(1) & A1

and copy down.  Then sort cols A & B by B to get:

Is this "alphabetic-style" sort closer to what you need??
Comment: Thank you very much for your help! I got it working now :)
Comment: @Mikee  Thanks for the feedback!
Answer: Create a new column called SortOrder with the following formula:
=VALUE(LEFT(A2,1))

Then go to Home tab > Sort & Filter > Custom Sort.... Sort first by SortOrder, then by Value:
Comment: Thank you very much for your help! I got it working now :)


Specifiying range for log-normal distribution in Python

Question: I am generating a random log-normal distribution using the inbuilt function. Is it possible to specify a range for a given mean and sigma? For instance, I want a random distribution between 0 and 0.5 with mean=0.2, sigma=0.5?
import numpy as np

r=np.random.lognormal(mean=0.2, sigma=0.5, size=(3,3))
print([r])

Comment: Does this answer your question? [Restricting numpy.random.lognormal to a given range, Python](https://stackoverflow.com/questions/51995490/restricting-numpy-random-lognormal-to-a-given-range-python)
Comment: AFAIK, lognormal distribution does not have a bounded range of definition like normal distribution. You certainly need a truncated lognormal distribution but this one is not provided by Numpy. That being said, if the range is reasonable, I think you can repeat the operation to obtain a truncated lognormal distribution.
Answer: Not directly, but you can generate more points and filter those that are outside your parameters. With the values you provided, however, there will be very few such points:
np.random.seed(0)
z = np.random.lognormal(mean=0.2, sigma=0.5, size=10_000)

>>> np.sum(z < 0.5) / len(z)
0.0346

As a side note, please know that the parameters mean and sigma of np.random.lognormal() refer to the underlying normal distribution, not to the mean and std of the log-normal points:
np.random.seed(0)
z = np.random.lognormal(mean=0.2, sigma=0.5, size=1000)
y = np.log(y)

>>> np.mean(z), np.std(z)
(1.3886515119063163, 0.7414709414626542)

>>> np.mean(y), np.std(y)
(0.2018986489272414, 0.5034218384643446)

All that said, if you really want what you asked for, you could do:
shape = 3, 3
zmin, zmax = 0, 0.5

n = np.prod(shape)
zc = np.array([])
while True:
    z = np.random.lognormal(mean=0.2, sigma=0.5, size=n * 100)
    z = z[(zmin <= z) & (z < zmax)]
    zc = np.r_[zc, z]
    if len(zc) >= n:
        break
r = zc[:n].reshape(shape)

>>> r
array([[0.34078793, 0.45366409, 0.40183988],
       [0.43387773, 0.46387512, 0.30535007],
       [0.44248787, 0.32316698, 0.48600577]])

Note, however, that the loop above (which in this case is done on average just once), may run forever if your bounds specify an empty space.
Edit
For efficiency, we can use instead scipy.stats.truncnorm. However, there seems to be an issue when loc, scale != 0, 1, so here we roll out our own adjustment:
# convert X ~ N(0, 1) to Y ~ N(u, s):
# Y = X * s + u
# want Y in [a, b]:
# so X in [(a - u)/s, (b - u)/s]
#
# We want Z ~ logN(u, s) in [zmin, zmax]
# Z = exp(Y) and
# a, b = np.log((zmin, zmax))

def lognormal(a, b, loc=1, scale=1, size=1):
    a, b = np.log((a, b))
    ca, cb = (np.array((a, b)) - loc) / scale
    rv = truncnorm(a=ca, b=cb)
    z = np.exp(rv.rvs(size=size) * scale + loc)
    return z

Example:
zmin, zmax = 0, 0.5
z = lognormal(zmin, zmax, 0.2, 0.5, 10_000)

Or, to capture the rather noisy warning from np.log(0):
import warnings

with warnings.catch_warnings():
    warnings.filterwarnings('ignore', category=RuntimeWarning, message='divide by zero encountered in log')
    z = lognormal(zmin, zmax, 0.2, 0.5, 10_000)

Either way, we now have:
np.min(z), np.max(z)
(0.10787873738453256, 0.4999993445360746)

And the same distribution than one would get with the above (r) with shape = 10_000:
def lognormal_naive(a, b, loc=1, scale=1, size=1):
    zc = np.array([])
    while True:
        z = np.random.lognormal(mean=loc, sigma=scale, size=n * 100)
        z = z[(a <= z) & (z = size:
            break
    return zc[:size]

r = lognormal_naive(zmin, zmax, 0.2, 0.5, 10_000)

fig, ax = plt.subplots(ncols=2, figsize=(7, 2))
ax[0].hist(z, bins=100)
ax[1].hist(r, bins=100);

However, the timing is much better:
%timeit lognormal_naive(zmin, zmax, 0.2, 0.5, 10_000)
64.2 ms ± 60.3 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit lognormal(zmin, zmax, 0.2, 0.5, 10_000)
2.06 ms ± 3.61 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Comment: This approach is generally very inefficient if the array is relatively big (or/and the range small) as it regenerate all the value if only few value are outside the range. The probability of having such an event should very close to one for big arrays. The `n*100` mitigate the problem for this case but this generate 100x time more values than required in the worst case... In pathological cases it can be many orders of magnitude slower than actually required.
Comment: In fact, this is getting *exponentially slower* with the size in pathological cases. For example a 10x10 matrix with `zmin, zmax = 0, 0.35` takes several minutes while a basic (naive) code finding the values one by one takes 0.0005 second on my machine. This is >200_000 times slower!
Comment: Indeed, as noted in the answer. Clipping a log-normal distribution is simply not a good idea to start with. For degenerate cases, you'd probably build something ad-hoc to draw from the tail of the normal distribution and then take the log. See. e.g. [here](https://stackoverflow.com/a/28868550/758174).
Comment: See updated answer using `scipy.stats.truncnorm`.
Comment: Indeed, much better (especially in pathological cases). For the warning, I think it is better to use a zmin set to a very small value like 1e-15 so to avoid a `log(0)` instead of hiding the problem.


Migration bringing in duplicate taxonomy terms

Question: I have a very simple taxonomy term migration (migrate module, that lets in duplicate terms for no reason I can figure out.  I have tried explicitly setting allow_duplicates to False, even though that should be the default behavior, but nothing changes.  The base migration that this migration inherits from just sets up a db connection object, sets up team description variables, and sets some configuration variables.  It also sets up a few helper methods that are not used in this migration.
Here is the migration class:
class EnviroscopeKeywordMigration extends BaseEnviroscopeMigration
{
    public function __construct($arguments)
    {
        parent::__construct($arguments);

        $this->description = t('import Keyword data');
        $query = $this->getConnection()
            ->select('doc_keyword', 'k')
            ->fields('k', array('ID', 'NAME'));

        $this->dependencies = array("GeoArea");

        $this->source = new MigrateSourceSQL($query, array(), NULL, array('map_joinable' => FALSE));

        $this->destination = new MigrateDestinationTerm('keywords');
        $this->map = new MigrateSQLMap($this->machineName,
            array(
                'ID' => array(
                    'type' => 'int',
                    'length' => 11,
                    'not null' => TRUE,
                    'description' => 'Keyword ID',
                ),
            ),
            MigrateDestinationTerm::getKeySchema()
        );

        $this->addFieldMapping('name', 'NAME');

        $this->addUnmigratedDestinations(array(
            'description',
            'parent',
            'parent_name',
            'format',
            'weight',
            'path',
            'pathauto',
        ));
    }

}

Can somebody, PLEASE help me debug why this might be bringing in duplicate terms like this:
Comment: The file that you're migrating has these duplicates?
Comment: I'm migrating from another MySQL database, it has duplicates in it. They should all be combined into one term per phrase/word and the the migration map all the source Ids should map to that single destination.
Comment: Too many for manual deletion? Is this other db a Drupal db?
Comment: The other db is not a Drupal db, too many for manual deletion, and other migrations depend on those source Ids being mapped properly so the other data gets associated with the right terms.
Answer: I ended up biting the bullet and writing it myself.  I still don't know what was causing it to not work in the first place, but I replicated the desired behavior with this helper method in the migration class:
public function check_for_existing_term($taxonomy, $term) {
    $query = db_select('taxonomy_vocabulary', 'v')
        ->condition('machine_name', $taxonomy);
    $query->innerJoin('taxonomy_term_data', 'td', 'v.vid=td.vid');
    $new_tid = $query->fields('td', array('tid'))
        ->condition('td.name', $term)
        ->execute()
        ->fetchField();
    return ($new_tid) ? $new_tid : False;
}

In the constructor of the migration class I set $this->taxonomy = 'keywords'; and I used that in $this->destination = new MigrateDestinationTerm($this->taxonomy);, then I added the following prepareRow:
    public function prepareRow($row)
    {
        $new_tid = $this->check_for_existing_term($this->taxonomy, $row->NAME);
        if ($new_tid) {
            $this->map->saveIDMapping($row, array($new_tid),
                MigrateMap::STATUS_IGNORED, MigrateMap::ROLLBACK_DELETE);
            $this->rollbackAction = MigrateMap::ROLLBACK_DELETE;
            return FALSE;
        } else {
            return TRUE;
        }
    }

This tries to find a matching term in the database for each row.  If it finds it, it adds an entry in the map table and then returns FALSE so the migration won't do anything further for that row.  If it is a new term it returns True, and the migration continue happily, adding in the new term.
Comment: That's essentially what I was saying.
Comment: Except that your solution would have returned without writing anything into the migration map for duplicate terms. Later when I ran the migration of nodes that need keywords associated with them The first instance of each would be the only one that got a term mapped.
Answer: One way I used to do this was use the built in prepareRow method. I would query and check for term exists by name for the vocabulary I am importing to. If I got a result, I would return false, which prevents that record from being migrated. Taxonomy terms are tricky.
In this case it does not sound like you have unique terms in the source database, so I'm not sure how you can flatten multiples down to just one term while preserving relational data on content that used those terms (who's ID has changed in Drupal).
Comment: That is no good because all the source Ids need to be mapped to the right destination terms so that the migrations that depend on this one will be associated with the right terms. I may end up having to write a method to manually do the duplication check and mapping that migrate's documentation and behavior in other migrations suggest it should be doing by default.
Comment: The source terms have unique Ids, just not unique terms so what needs to happen is for the migration map to be written one row per source but many source Ids mapping to the same destination tid
Answer: There are two ways to eliminate duplicates.
First the select-statement should have the "DISTINCT" qualification.
Second there is a dedupe method for the proces. Online documentation will help you further, i.e. http://blog.studio.gd/node/5. But you must use the database-wrapper supplied by Drupal. Also adjust settings.php with a $databases 'migrate', 'default' declaration.
Comment: Neither of those do what I want.  dedupe ensures that each term comes in as unique, which is the behavior I am trying to avoid.  Select distinct will mean that there is only a migrate map mapping for one of the instances of the term.  What needs to happen is for there to be a row in the migrate map for every source, but for all identical sources to map to the same destination.  This enables future node migrations to properly map terms onto the nodes.
Comment: High UltraBob, seems you have to apply the first rule of migration. Ensure that your source data is correct. So first dedub your source and make sure there is only one occurrence per term is present. Then do the migration. Otherwise you have to do all sorts of acrobatic during your migration.
Comment: My source data is correct for the system I'm migrating from, but is in a state that needs to be improved since it currently provides no utility. The answer I wrote here addresses that.
Answer: Just in case someone else would have the same problem on a drupal 9, I developed a small module containing a migrate process for that: https://www.drupal.org/project/migrate_merge_duplicated_terms


Start vino-server (VNC) before login on Linux CentOS

Question: I'm using the default vino-server package to access my CentOS 6 workstation via VNC.
It works ok, but only AFTER I locally login on the workstation. I need to have vino-server start BEFORE the login, right at the Gnome login screen where I choose username and password.
Due to personal reasons, I need to use Vino and not vnc-server or any other packages.
I already tried to insert /usr/libexec/vino-server & in /etc/gdm/Init/Default but this didn't solve the issue.
Comment: What are you actually trying to accomplish?
Comment: I answered the question on [Super User](http://superuser.com/a/766306/2357).
Comment: Have a look at the [NX server using FreeNX](http://wiki.centos.org/HowTos/FreeNX) howto. If it doesn't help you, I suggest reasking on [Super User](http://superuser.com/) or [Unix & Linux SE](http://unix.stackexchange.com/).
Comment: I don't agree with this choice, but I reasked on SU.
Comment: Remotely displaying a screen has little to do with servers. It's a more generic topic. Also *"personal reasons"* don't sound too professional to me, unless it's an unfortunate choice of words.
Answer: look for init script (/etc/init.d) for vino-server
Update :  i hacked an existing startup script, try placing it in /etc/init.d/ and run updaterc.d vnc-server defaults , i have not tried it myself but this is it i have used as skeleton for most of my startup scripts.
### BEGIN INIT INFO
# Provides:          vino-server
# Required-Start:    networking
# Required-Stop:     networking
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: vino-server test script
# Description:       This is a test daemon
#                    This provides example about how to
#                    write a Init script.
### END INIT INFO

# Using the lsb functions to perform the operations.
. /lib/lsb/init-functions
# Process name ( For display )
NAME=vino-server
# Daemon name, where is the actual executable
DAEMON=/usr/libexec/vino-server
# pid file for the daemon
PIDFILE=/var/run/vino-server.pid

# If the daemon is not there, then exit.
test -x $DAEMON || exit 5

case $1 in
 start)
  # Checked the PID file exists and check the actual status of process
  if [ -e $PIDFILE ]; then
   status_of_proc -p $PIDFILE $DAEMON "$NAME process" && status="0" || status="$?"
   # If the status is SUCCESS then don't need to start again.
   if [ $status = "0" ]; then
    exit # Exit
   fi
  fi
  # Start the daemon.
  log_daemon_msg "Starting the process" "$NAME"
  # Start the daemon with the help of start-stop-daemon
  # Log the message appropriately
  if start-stop-daemon --start --quiet --oknodo --pidfile $PIDFILE --exec $DAEMON ; then
   log_end_msg 0
  else
   log_end_msg 1
  fi
  ;;
 stop)
  # Stop the daemon.
  if [ -e $PIDFILE ]; then
   status_of_proc -p $PIDFILE $DAEMON "Stoppping the $NAME process" && status="0" || status="$?"
   if [ "$status" = 0 ]; then
    start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
    /bin/rm -rf $PIDFILE
   fi
  else
   log_daemon_msg "$NAME process is not running"
   log_end_msg 0
  fi
  ;;
 restart)
  # Restart the daemon.
  $0 stop && sleep 2 && $0 start
  ;;
 status)
  # Check the status of the process.
  if [ -e $PIDFILE ]; then
   status_of_proc -p $PIDFILE $DAEMON "$NAME process" && exit 0 || exit $?
  else
   log_daemon_msg "$NAME Process is not running"
   log_end_msg 0
  fi
  ;;
 reload)
  # Reload the process. Basically sending some signal to a daemon to reload
  # it configurations.
  if [ -e $PIDFILE ]; then
   start-stop-daemon --stop --signal USR1 --quiet --pidfile $PIDFILE --name $NAME
   log_success_msg "$NAME process reloaded successfully"
  else
   log_failure_msg "$PIDFILE does not exists"
  fi
  ;;
 *)
  # For invalid arguments, print the usage message.
  echo "Usage: $0 {start|stop|restart|reload|status}"
  exit 2
  ;;
esac
# Example captured from :http://www.thegeekstuff.com/2012/03/lsbinit-script/

& Add it to chkconfig

sudo /sbin/chkconfig --add  vnc-server
sudo /sbin/chkconfig --list vnc-server
sudo /sbin/chkconfig vnc-server on
Comment: Nice try but there is no init script for vino. [See for yourself](http://s29.postimg.org/qrlgofl3r/z_Screen_Shot27.png)
Comment: @akash, have you tested this script?
Comment: like is said in the beginning, i used my skeleton script and updated it to suit requirement, it would still need someone to run and test. i intended to get @Dr.GianluigiZaneZanettini going.


Do musicians who never learned to read music but play a transposing instrument learn the standard fingering names?

Question: If a trumpeter or saxophonist, for example, learned to play music by ear and not by sheet music or formal training, is it more likely that s/he learned the standard fingering names or the concert pitch? (I.e. an alto saxophonist would, from the start, call the fundamental/native-key an Eb and not C).
My guess is that most of these players play with concert pitch instruments such as a jazz band and would just learn the name of the actual pitches their playing. Why bother transposing in your head if you're never looking at sheet music and are always given the key in concert pitch?
But then what do they do when they switch (if ever?) to another instrument in the same family (alto to tenor sax, for example). Do they know memorize both notes for the same fingering, like a recorder player?
Comment: This is why it is important to be able to read. Each music skill you add will only do you good. I still have friends who play guitar who won't put in the effort to read or learn theory.... it hinders their ability on all affronts. They are limited in many aspects.
Answer: My guess is that they probably don't even know the names of the notes either way. It would be mainly of academic interest, and no help for the stage they're at. On occasions, I play, separately, with a guitarist, flautist and sax player (alto and tenor), who don't read, and aren't needing the key a song is in. They just play, and it works. They seem to have a second sense as to where the notes are, and if they knew what those were called, either concert or written, it wouldn't help.
Those are only three examples, I'm sure other ideas will emerge, but what I'm not sure of is that knowing note names would help those individuals. They just have the propensity to play right, and they're not the only players I've worked with who are like that.
Not saying whether it's good or bad, generally, however, it works for them.
Answer: It's a good question. Since I read music I have no definite answer to that one, but my viewpoint comes from having "perfect" pitch (which I call "pitch recognition," meaning if you play me a pitch I can tell you the name it would have on a piano. Concert pitch.) I play a number of instruments, many of them transposing. Horn (french) plays many transpositions, but I read not by fingering but by concert pitch. So for horn in F the note on the second line from the bottom is middle C. Horn in Eb, I read concert pitch bass clef up an octave and add three flats mentally. And so forth....And I also play Bb transposing instruments, and read yet another clef in concert pitch for those. Etc....the advantage to that is I can take, for example, clarinet music and play it on the viola, since I read by pitch. People think I must be a marvelous transposer when what I actually do is read a whole lot of clefs. I think that may be what goes on with people who play by ear...doesn't matter what the transposition is if they can hear what pitches to play. Same thing, different presentation.


Progressive Upload and Encryption with CryptoJS

Question: The goal here is to upload a file, encrypt it at the client side, and send the file and its attributes via AJAX to myphpscript.php.  To allow larger files, I want to upload in slices using the FileReader slice method and progressively encrypt the slices using the methods described on the CryptoJS site (https://code.google.com/p/crypto-js/).  My code below runs, but only ends up storing a a small portion of the intended entire encrypted file.  Can I progressively upload and encrypt in the way I am describing?

Comment: If you want to upload the data in several chunks, then I'd expect to see you making requests in some kind of loop … but I don't see that happening?
Comment: Right now the way I am doing this, correct me if I am wrong, is in the section with the comment "LOOP THROUGH BYTES AND PROGRESSIVELY ENCRYPT".  In that while loop, I run the function readBlob which reads a particular slice.
Comment: But you are _sending_ the data to your server outside of that loop, afterwards …
Comment: I see your point; to clarify, I don't necessarily want to upload the data in chunks, I want to progressively encrypt its slices from FileReader and then upload all at once.  Maybe uploading all at once defeats the purpose of the progressive slicing and encrypting, and if so, an alternative would be helpful :)
Answer: So your problem is the line var encrypted = aesEncryptor.finalize();
This is not the encrypted file, but the final 'chunk' produced by the CryptoJS.AES finalizer.
you need to append that to the end of the window.bits buffer to yield the fully encrypted file.
Also, you shouldn't be using window.bits.push, you should keep hold of a reference to each chunk like this (psuedocode):
var prog;
//then in the loop, if chunk is null assign to chunk or else concat:
loop:
    if(!prog)
        prog = cipher.process()
    else
        prog.concat(cipher.process())

//then finalize
prog.concat(cipher.finalize())

//now you're free to do whatever with the encrypted file:
var ciphertext = prog.toString()

Answer: One important thing to keep in mind is that the chunks may arrive to the encryptor out of order so you either have to keep track of the order that chunks went into aesEncryptor.process so that you can decrypt in the proper order later or queue the chunks and encrypt them in the proper order to begin with.
Comment: Yep, i detail how to do this [here](http://craig-bruce.com/progressive-decryption/)


Music theory - secondary dominants

Question: Do i still have to use 1st inversion when using secondary diminished triads or sevenths?
I've been watching some videos but it didn't go over this.
Answer: In common-practice music, diminished triads are basically always in first inversion. This means that any time you write a vii°—whether it's a regular vii° or a secondary diminished triad (like vii°/V)—it really needs to be in first inversion.
For fully diminished seventh chords, however, they can be in any inversion. Since this harmony is symmetrical (it's basically built of stacked minor thirds), all inversions technically sound exactly the same in twelve-tone equal temperament; the only difference is how they are spelled.
So in short, yes: any vii° triad needs to be in first inversion. But this rule does not apply to diminished seventh chords.

Music theory - secondary dominants


Avoid duplicate values in comma delimited sql query

Question: hello I have here a comma delimited query:
<code>select [Product_Name]
,(select  h2.Location_name + ', '  from (select distinct * from [dbo].[Product_list]) h2 where h1.Product_Name = h2.Product_Name
    order by h2.Product_Name for xml path  ('')) as Location_name
,(select   h2.[Store name] + ', ' from [dbo].[Product_list] h2 where h1.Product_Name = h2.Product_Name
    order by h2.Product_Name for xml path  ('')) as store_name, sum(Quantity) as Total_Quantity from [dbo].[Product_list] h1
group by [Product_Name]
</code>
but this query shows duplicated data in comma delimited form, my problem is how will I only show the distinct values of the column in comma delimited form? can anyone please help me?
Answer: Well, if you don't SELECT DISTINCT * FROM dbo.Product_list and instead SELECT DISTINCT location_name FROM dbo.Product_list, which is anyway the only column you need, it will return only distinct values.

T-SQL supports the use of the asterisk, or "star" character (*) to
  substitute for an explicit column list. This will retrieve all columns
  from the source table. While the asterisk is suitable for a quick
  test, avoid using it in production work, as changes made to the table
  will cause the query to retrieve all current columns in the table's
  current defined order. This could cause bugs or other failures in
  reports or applications expecting a known number of columns returned
  in a defined order. Furthermore, returning data that is not needed can
  slow down your queries and cause performance issues if the source
  table contains a large number of rows. By using an explicit column
  list in your SELECT clause, you will always achieve the desired
  results, providing the columns exist in the table. If a column is
  dropped, you will receive an error that will help identify the problem
  and fix your query.
Using SELECT DISTINCT will filter out duplicates in the result set.
  SELECT DISTINCT specifies that the result set must contain only unique
  rows. However, it is important to understand that the DISTINCT option
  operates only on the set of columns returned by the SELECT clause. It
  does not take into account any other unique columns in the source
  table. DISTINCT also operates on all the columns in the SELECT list,
  not just the first one.

From Querying Microsoft SQL Server 2012 MCT Manual.


Quais são as fases de padronização de uma propriedade CSS?

Question: Às vezes pesquiso no site Can I Use a compatibilidade entre navegadores de algumas propriedades CSS e me deparo com algumas siglas, tal como: LS, WD, ED, CR etc., como por exemplo, a propriedade clip-path me mostra a sigla CR:

Fiz uma pesquisa e vi que CR significa Candidate Recommendation. Ao que me pareceu, a propriedade ainda não foi padronizada, seria uma candidata para tal. Sei que uma propriedade é padronizada quando possui a sigla LS (Living Standard).
Quais as etapas que uma propriedade tem que passar até chegar ao LS? E porquê ela pode, fatalmente, não chegar nem ao LS?
Comment: Quem seria o Maujor?
Comment: O assunto é interessante, e um mais profundo do que parece... Vamos ver se o Maujor aparece para responder essa :)
Comment: @hugocsl Eu tô fazendo umas pesquisas... se eu conseguir algo, eu mesmo vou postar uma resposta rs
Comment: Se vc é o Tio, e o Leo o Vovô, o Maujor é o Dinossauro  do CSS! Aqui está o site dele https://www.maujor.com/ ele tem uma história de vida bem interessante tem, vários livros publicados, da palestras etc..., inclusive vc pode ver no Youtube alguns vídeos sobre esse mito do mundo dev. https://pt.stackoverflow.com/users/13752/maujor
Comment: @hugocsl achei que vc podia me quebrar essa. Acho meio confuso essa siglas. Bom, mas se o Maujor puder me esclarecer essa questão vou ficar mt agradecido.
Comment: Sam eu até separei um material, mas estou sem tempo para fazer uma resposta no nível que eu gostaria, e tem algumas coisas que tb não consegui identificar, como por ex. "quando ocorre a mudança de status", acho que isso é uma decisão particular do comitê dependendo da disponibilidade dos membros avaliarem... não consegui infos quanto a isso... Se vc achar que uma reposta um pouco mais simplificada pode ter algum valor posso contribuir com o que tenho em mãos aqui
Answer: Vou tentar não me alongar na resposta. E vou citar todos os links com informações complementares e detalhadas. Inclusive sobre o status geral do CSS
Essa lista indica a maturidade das especificações dos códigos na W3C. Indo da menos estável até a mais estável.
Fonte: https://www.w3.org/Style/CSS/current-work

Uma propriedade pode passar por várias revisões dentro de uma mesma "categoria" antes que mude para um status mais estável.
Esse é o histórico de revisões do código Media Query. Repare que por muito tempo eme foi um CR antes de realmente virar um REC.
Fonte: https://www.w3.org/standards/history/css3-mediaqueries

Acredito que a demora nas atualizações dos padrões antigamente se davam principalmente pq o Comitê W3C se comunicava por uma lista de e-mail. Acredite se quiser, eles não tinha um repositório e era tudo acordado e discutido por uma lista de e-mail!
Aqui tem um exemplo de como eram essas conversar.
Lista com histórico: https://www.w3.org/Style/2012/MediaQueriesDisposalOfComments.html
Um exemplo de como eram as conversas: http://lists.w3.org/Archives/Public/www-style/2012Mar/0409.html
Então o comum era que para cada "nova propriedade" fosse criada uma lista de e-mail, e que quisesse contribuir com o Comitê entrava na lista e participava da criação das especificações etc... Aqui tem uma lista de como é organizados os padrões CSS estabelecidos pela W3C, e inclusive vc consegue ver o histórico de cada specs.
Veja: https://www.w3.org/Style/CSS/specs.en.html

E como é o CSS hoje? E o CSS4?
Bom, hoje as coisas evoluíram um pouco, e os projetos da W3C estão no GitHub, isso facilita para acompanhar o desenvolvimento das coisas e para os entusiastas que querem contribuir de alguma forma.
Esse é o GitHub da W3C https://github.com/w3c/ e esse é o projeto do Working Group dos Drafs do CSS https://github.com/w3c/csswg-drafts
Aqui é uma opinião minha: É muito provável que o CSS4 nunca vá existir... Na verdade o CSS ao meu ver é um eterno Beta. Algumas propriedade vão evoluindo enquanto outras serão "deprecadas". Além disso, os módulos de propriedades do CSS estão em níveis diferentes, uns mais avançados e outros menos, e mesmo no que se diz "CSS 3" existem módulos que ainda são 1 e outros que já são 4...
Por exemplos:

Grid Layout ainda especificado como CR Level 1

Mas o Grid Layout Level 2 já está como WD

Já o Medias Query por sua vez estão no Level 4 CR

Isso me leva a crer que nunca será lançado um CSS 4... O que vai ocorrer é apenas um evolução constante e gradual (evergreen). Como a Adobe faz por exemplo com o Photoshop, onde atualmente não tem mais a versão 9 ou 10, agora é apenas a "versão atual" :)
Aqui tem um artigo bem interessante quanto ao futuro e o CSS4: https://www.silocreativo.com/en/css4-the-new-version-of-css-that-will-never-exist/
Esse é o status atual de todas as propriedades https://www.w3.org/standards/techs/css#w3c_all

Importante
É preciso ter em mente que ninguém, nem nenhum Browser, é de fato "obrigado" a seguir o que determina a W3C. Por isso é comum vermos até hoje propriedades como os Vendor Prefix, como -moz- e -webkit-, normalmente essas são propriedades não "oficiais", não são especificadas pela W3C e podem funcionar exclusivamente em um browser ou outro, ou mesmo nem existir em outros browsers. Além disso, cada browser tem certa liberdade para tratar a estilização de certos campos, como os <button> ou <select>, que normalmente têm estilos de user-agent diferentes de browser para browser.
Aqui por exemplo está a lista das especificações e de como elas estão no browser da Mozilla FireFox
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS3


Variable from parameter in Function

Question: Maybe I'm missing something so sorry if that's the case but does anyone know if it's possible in jQuery to use the parameter from a function in a variable. For example:
function number(x){
  variable_number_x++;
}

And in that code replace x with the function parameter. So for example number(2) would output that it adds 1 to the variable_number_2 variable. Any idea's? Thanks in advance!
Answer: window["variable_number_"+x]++; is probably what you need.
I am assuming here that variable_number_2 is a global, but you can replace window with whatever object variable_number_2 is a property of. Alternatively, you can specify an optional parameter that takes the object that the variable is a property of:
var obj = {variable_number_2: 5};
function number(x,obj){
  if(typeof(obj)=="undefined"){
      obj = window;
  }
  return ++obj["variable_number_"+x];
}
console.log(number(2,obj));                 //logs 6
console.log(obj.variable_number_2); //logs 6

Variable from parameter in Function


Filtering Live Messenger traffic by contacts

Question: I am looking for a filtering solution to be able to filter Live Messenger traffic according "with who" they are chatting.
We use Messenger for work, but some of collegues gets a lot of "out of work" messages during work time.
I would like to restrict the messenger traffic according to the contacts email, or UID.
I have found a possible solution, but I couldn't even start it, and seems a bit outdated.
msnpr.exe from http://3proxy.ru/download/
Best regards
Answer: If you can't find an app to handle it, you'll have to get messy with the messenger protocols to be able to pull the contact's information out before delivery. The protocols seem to be updated frequently to continuously cripple unofficial clients, so it's probably impractical.
MS offers a corporate alternative to live messenger which was forked from Windows Messenger, MS Office Communicator. This is the non-hacky way to restrict your messenger use to business purposes.
Alternatively, you could deploy a Jabber server or something similar if you're on a budget.
Lastly, don't forget the maxim "You shouldn't attempt to solve people problems with technology alone"
Answer: Couple of options...
Smoothwall (bias alert: I work for Smoothwall) produce UTM devices that can monitor/block IM. The IM "half proxy" we use is called imspector (bias alert: I have a tiny bit of code in there, and the dev is a colleague and friend), which if you want to implement it on its own might offer more flexibility at a cost of having to set it all up yourself.
Another option is to use an openfire server. We use this to bridge our internal SIP messaging to MSN. Getting it to talk MSN is a bit of a bind IIRC, needing a hard to track down 3rd party plugin, I think this kraken business was involved.


ReactNative: Component inline and for navigation

Question: I am beginning with ReactNative and try to get a component I can navigate to as well as use inline.
MyComp is the component. In Home I try to navigate to MyComp by a button as well as have it inline with .
App.js
import React from 'react';
import { StyleSheet, Text, View, Button, Alert, Image} from 'react-native';
import {createStackNavigator, createAppContainer} from 'react-navigation';
import Home from "./Home";
import MyComp from "./MyComp";

const navi = createStackNavigator({
    Home: {screen: Home},
    MyComp: {screen: MyComp}
});

const App = createAppContainer (navi);
export default App;

Home.js
import React from 'react';
import {StyleSheet, Text, View, Button, Alert} from 'react-native';
import {navigate} from 'react-navigation';
import {MyComp} from "./MyComp";

export default class Home extends React.Component
{
    static navigationOptions = {title: 'At Home'};

    render()
    {
        return (
            <View style={{ alignItems: 'center', justifyContent: 'center', flex: 1}}>
            <Button
                title={"Goto MyComp"}
                onPress={() => this.props.navigation.navigate('MyComp')}/>

            <MyComp/>   {/* Compiler Error */}

            </View>
        );
  }
}

MyComp.js
import React from 'react';
import {Text, View, Button} from 'react-native';

export default class MyComp extends React.Component
{
    render()
    {
        return (
            <View>
            <Text>Here I am</Text>
            </View>
    );
  }
}

But the inline produces an error.

Invariant Violation: Invariant Violation: Element type is invalid:
  expected a string (for built-in components) or a class/function (for
  composite components) but got: undefined. You likely forgot to export
  your component from the file it's defined in, or you might have mixed
  up default and named imports.
Check the render method of Home.

I am not sure whats the problem here. Is it not possible to use a component in both ways?
Answer: remove brackets when u import component in home screen
change
 import {MyComp} from "./MyComp";
to
 import MyComp from "./MyComp";
Comment: Thanks! Whats the reason for that?
Comment: You are exporting the class as default. That's the syntax for importing default exports. Like the error message says, "you have mixed up default and named imports."


AngularJs: How to watch multiple collection using watchcollection

Question: In AngularJS I have 6 to 7 watchcollection that watches foo1,2,3...7 and all of them call the same method methodA().Is there any way in AngularJS to group all these watchers so that I dont have to write multiple separate watchcollection blocks.
<code>$scope.$watchCollection(
                        "foo1",
                        function( newValue, oldValue ) {
                            methodA();
                        }
                );

$scope.$watchCollection(
                        "foo2",
                        function( newValue, oldValue ) {
                            methodA();
                        }
                );
</code>
............and similarly till foo7
Answer: Yes. watchGroup.
<code>$scope.$watchGroup(['foo1', 'foo2', ..., 'foo7'],
    function(newValues, oldValues, scope) {
        methodA();
    }
});
</code>
Answer: Please do as shown below.
Here is nice video about $watchCollection
<code>$scope.$watchCollection('[foo1,foo2]', function () {
        methodA();
     });
</code>
Answer: Yes it is possible, your code should look like this:
<code>$scope.$watch('[foo1, foo2, foo3, foo4, foo5, foo6, foo7]', function() {
    methodA();
}, true);
</code>
Hope this helped.


Why $\hat{\mathbb{C}}\setminus K$ connected $\implies {\mathbb{C}}\setminus K$ connected? ($K $ compact)

Question: Let $\hat{\mathbb{C}}=\mathbb{C}\cup \{\infty\}$ denote the extended complex plane, with the usual topology.That is $U$ such that $U$ is open in $\mathbb{C}$ and the neighbourhoods of $\{\infty\}$  $U_{\infty}=\mathbb{C} \setminus K \cup \{\infty\}$ with $K$ a compact subset of the complex plane.
We need to show that if $K$ is a compact subset of $\mathbb{C}$ then $\hat{\mathbb{C}}\setminus K$ connected $\implies {\mathbb{C}}\setminus K$ connected
I tried to prove it assuming a clopen non-trivial subset of  $ {\mathbb{C}}\setminus K$ . Showing that this set is open is easy but how can i show that is also closed in $\hat{\mathbb{C}}\setminus K$?
Comment: Can you reedit the question in a more clear form?
Comment: For instance, please define the terms you use(C, C-hat, K)
Comment: Sorry, I hope it's clear now. I should write my questions carefully.
Answer: Since $K$ is compact, it is closed and bounded. There is thus a ball $B$ of some radius $r<\infty$ covering $K$. Since $\Bbb C\setminus B$ is connected, $\Bbb C\setminus K$ has exactly one unbounded component.
Let $U$ be a clopen subset of $\Bbb C\setminus K$ containing the unbounded component. Then $U$ is open in $\Bbb C$ and $\Bbb C\setminus U$ is compact, hence $U\cup\{\infty\}$ is open in $\hat{\Bbb C}$. But it's also closed in $\hat{\Bbb C}\setminus K$ since $(\hat{\Bbb C}\setminus K)\setminus(U\cup\{\infty\}) = {\Bbb C}\setminus (K\cup U)$ is open.
Comment: it is always the case that   $U$ contains  the unbounded component?
Comment: @Abellan: If some point in the unbounded component of $\Bbb C\setminus K$ is contained in a clopen subset $U$ of $\Bbb C\setminus K$ (there's always at least one such clopen subset), then $U$ must contain the entire unbounded component because it is connected.
Answer: Suppose WLOG that $0 \in K$, and apply the homeomorphism $z \mapsto \frac{1}{z}$ of $\hat{\Bbb{C}}$. Then $\hat{\Bbb{C}} \setminus K$ is mapped into some bounded open set $D \subset \Bbb{C}$ containing $0$. $D$ is path connected because it is connected. Can you show that $D \setminus \{0 \}$ is path connected as well (paths do not need to pass through $0$, because $D$ is open, so "there is enough space" to go around $0$ and avoid it)? Then conclude.
Comment: I did like this argument a lot. However, it is necessary to choose the homeomorphism such that  $D$ is bounded? Thanks!
Comment: I used the simplest homemorphism I had in mind to get rid of the infinity point. What comes out is a bounded open set, because it is an open set of $\hat{\Bbb{C}}$ far from $\infty$. Actually boundedness of $D$ is not so relevant: what is relevant is path connectedness.
Comment: Yeah. I was thinking that you can get also path connectedness with an unbounded $D$.


Linear regression: R-squared and predicted response

Question: On a business task, I perform simple linear regression with an independent variable $X$ and a dependent variable $Y$. The result is a linear function with slope $β_1$. If $R^2$ (coefficient of determination) = 1, I conclude that an increase of 1 in $X$ will result in an increase of $β_1$ in $Y$. If $R^2$ = 0, I conclude that an increase of 1 in $X$ will on average result in an increase of 0 in $Y$.

Are my conclusions correct?
If $R^2 = 0.5$, can I conclude that an increase of 1 in $X$ will on average result in an increase of $0.5β_1$ in $Y$?
If 2. is incorrect, is there a way to infer such a relationship from a linear regression model («an increase of 1 in $X$ will on average result in an increase of ... in $Y$»)?
Answer: Firstly lets remember $R^2$==1-$SS_{reg}$/$SS_{tot}$. Where $SS_{reg}$ is the sum of squared errors from your model:
$Y=\beta_{1}X+\epsilon$  (Where $\epsilon$ is the error in your prediction)
And $SS_{tot}$ is the sum of squared errors when you assume $Y$ = $\bar{Y}$. This is the same as the linear model $Y=\beta_{0}+\epsilon$, otherwise known as the NULL model.
1.Your first conclusions are correct. Because $R^2$ shows how well movements in $Y$ are explained by your model $\beta_{1}X+\epsilon$. An $R^2$ of 1 means your model perfectly explains movements of $Y$ that is $SS_{reg}$=0 i.e. $\epsilon=0$. So you can conclude an increase in $X$ by 1 will definitely result in $Y$ increasing by $\beta_{1}$. Likewise an $R^2$ of 0 means your model $\beta_{1}X+\epsilon$ does no better in explaining movements in $Y$ than just assuming $Y$ will be the average $\bar{Y}$. (That is $SS_{reg}$=$SS_{tot}$). i.e. $X$ has no bearing on $Y$.
2.If $R^2$=0.5 it means your model explains 50% of the movement in $Y$ when compared to simply stating $Y$ = $\bar{Y}$. The unexplained movement in $Y$ is captured by your error term $\epsilon$, which is white noise. This means when $X$ increases by 1 $Y$ on average will increase by $\beta_{1}$ but due to the unexplained white noise you might not see this in in the data i.e. in every instance of $Y_{i}$.
3.Even where $R^2$<1 your interpretation of $\beta_{1}$ is still the average increase in $Y$ when $X$ increases by 1. It just means there is noise that has been unaccounted for in the model. Adding other predictors into the model may well change the value of $\beta_{1}$, but given the model $\beta_{1}X+\epsilon$, $\beta_{1}$ should be interpreted as the average increase in $Y$ when $X$ increases by 1. The only time this is inappropriate is when $R^2$==0 because in that case $X$ has no relationship with $Y$.
Comment: In this business case, the individual results are not important, only the long-term average. Does this mean that I from a business point-of-view can ignore $R^2$ as long as I can show with a significance test that $R^2$ > 0 ?
Comment: $R^2$ is useful in telling you whether your model $\hat{\beta}_{1}X_{1}$ is a good predictor of $Y$ or not so I wouldn't ignore it but it doesn't change the interpretation of $\beta_{1}$, assuming $\hat{\beta}_{1}$ is statistically significant. You may want to add other predictors to your model that way you can say when holding for $X_{2}$, $X_{3}$, etc $Y$ increases on average by $\beta_{1}$ when $X_{1}$ increases by 1. At the moment your model isn't holding for any other predictors so $\hat{\beta}_{1}$ may not be a good estimation of the population $\beta_{1}$
Comment: To be clear I've used $\hat{\beta}_{1}$ in the above comment to differentiate between your estimated coefficient and the actual population coefficient $\beta_{1}$ you're trying to discover. In my answer any reference to $\beta_{1}$ is a reference to the estimated relationship between $X$ and $Y$. In reality because your not holding for other variables $\hat{\beta}_{1}$ may be a biased estimator of the population $\beta_{1}$


Proof of Cauchy Integral Formula for annulus

Question: Suppose that $f$ is holomorphic in a neighborhood of $A_{r,R}=\{z\in \mathbb C: r<|z|<R\}$, then $f(z) = \frac{1}{2\pi i}\oint_{c_{R}}\frac{f(w)}{z-w}dw-\frac{1}{2\pi i}\oint_{c_{r}}\frac{f(w)}{z-w}dw$. This is the CIT formula for annulus.
I was told to prove it like this:
Fix $z \in A_{r,R}$, using the CIT for star shaped region for the function $g(w)=\frac{f(w)-f(Z)}{w-z}$ if $w \neq z$ and $g(w) = f'(w)$ if $w=z$, I can argue that $\frac{1}{2\pi i}\oint_{c_{R}}\frac{f(w)-z}{z-w}dw-\frac{1}{2\pi i}\oint_{c_{r}}\frac{f(w)-z}{z-w}dw =0$ as pictured below
But then $2\pi if(z)$ will be cancelled, what is wrong with this argument?
Answer: Try to relate your corridor contour with the usual  proof :

If $g(z)$ is holomorphic on $U = \{r-\epsilon < |z| < R+\epsilon\}$ then $$\int_{|z| = R} g(z)dz = \int_{|z| = r} g(z)dz$$
This a special case of the Cauchy integral theorem (if $g(z)$ is holomorphic on $U$ and a closed contour $\gamma$ is homotopically equivalent to $\gamma'$ on $U$, then $\int_\gamma g(z)dz = \int_{\gamma'} g(z)dz $)
Apply it to $g(z)  =\frac{f(z)-f(a)}{z-a}$ where $a \in U$ (*) so that $\int_{|z| = R} \frac{f(z)-f(a)}{z-a}dz -\int_{|z| = r} \frac{f(z)-f(a)}{z-a}dz = 0$
Finally, show that $$\int_{|z| = R} \frac{1}{z-a}dz -\int_{|z| = r} \frac{1}{z-a}dz = \int_{|z| = R} \frac{1}{z-a}dz = 2i \pi$$
So that

$$\int_{|z| = R} \frac{f(z)}{z-a}dz - \int_{|z| = r} \frac{f(z)}{z-a}dz$$
$$ = \int_{|z| = R} \frac{f(z)-f(a)}{z-a}dz - \int_{|z| = r} \frac{f(z)-f(a)}{z-a}dz+f(a) \left(\int_{|z| = R} \frac{1}{z-a}dz - \int_{|z| = r} \frac{1}{z-a}dz\right)$$
$$ = 2i \pi f(a)$$
(*) $g(z)$ is holomorphic around $z= a$ because $f(z)$ is analytic, but if you didn't prove that holomorphic $\implies$ analytic yet, use the Cauchy integral theorem to show  that $\int_{|z| = R} \frac{f(z)-f(a)}{z-a}dz -\int_{|z| = r} \frac{f(z)-f(a)}{z-a}dz = \lim_{\epsilon \to 0} \int_{|z-a|=\epsilon} \frac{f(z)-f(a)}{z-a}dz =  0$
Answer: The integral around the drawn curve vanishes. You may then let the vertical segments approach and they will cancel. The integral then becomes (with $\gamma$ being the boundary of the annulus, oriented in the opposite direction of your drawing):
$$ 0= \oint_\gamma \frac{f(w)-f(z)}{w-z} \frac{dw}{2\pi i} = \oint_\gamma \frac{f(w)}{w-z} \frac{dw}{2\pi i} - f(z)$$
Comment: I am a little bit lost, If I estimate the integral of $g(w)$ as defined above on the small circle, then by ML bound it would vanish(since I can make this circle arbitrarily small and $g(w)$ is continuous). So I am only left with the integral of $g(w)$ on the outer circle minus the inner circle, right?
Comment: In the proposed approach you get indeed only the integral of $g$ along the two circles. Now, when you evaluate the term coming from integrating $f(z)/(z-w)$ with respect to $dw/2\pi i$ (with the given orientation) you simply get $-f(z)$.


IOError: [Errno socket error] [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

Question: Olá, estou executando um simples código python (2.7.3) para lançar uma mensagem por webhook no Discord e estou encontrando o seguinte erro:
  urlopen(url).read()

  File "C:\Python27\lib\urllib.py", line 86, in urlopen
    return opener.open(url)
  File "C:\Python27\lib\urllib.py", line 207, in open
    return getattr(self, name)(url)
  File "C:\Python27\lib\urllib.py", line 436, in open_https
    h.endheaders(data)
  File "C:\Python27\lib\httplib.py", line 954, in endheaders
    self._send_output(message_body)
  File "C:\Python27\lib\httplib.py", line 814, in _send_output
    self.send(msg)
  File "C:\Python27\lib\httplib.py", line 776, in send
    self.connect()
  File "C:\Python27\lib\httplib.py", line 1161, in connect
    self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
  File "C:\Python27\lib\ssl.py", line 381, in wrap_socket
    ciphers=ciphers)
  File "C:\Python27\lib\ssl.py", line 143, in __init__
    self.do_handshake()
  File "C:\Python27\lib\ssl.py", line 305, in do_handshake
    self._sslobj.do_handshake()

IOError: [Errno socket error] [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

O código que está sendo executado é esse:
from urllib import urlopen
url = 'https://minhaurl.com/webhook.php'
urlopen(url).read()

Obs: Não há erro no arquivo PHP porque usei ele antes.
Alguém poderia me ajudar?
Answer: O problema é que você está tentando usar https e não http, e para isso, são necessárias várias libs de criptografia instaladas e em versão atualizada. O python 2.7.3 é ancião (foi lançado a mais de 6 anos atrás) e muita coisa mudou nesse campo desde que ele foi lançado.
A tecnologia de cifragem (ssl) foi atualizada várias vezes nesse período. Tente atualizar o seu python para a versão mais nova. Se você tiver o pyOpenSSL, atualize ele também.
Comment: Obrigado, eu não tinha percebido isso antes.


Proving a recurrence relationship for a sequence

Question: I have an assignment question which I have spent hours working on without getting even close to the answer, and would really appreciate any pointers that could help me figure it out.
QUESTION
Let $b_n$ be the number of ways a set of size $n$ can be split into singletons and pairs (i.e.  a partition into subsets of size 1 or 2). Then $b_n= b_{n-1} + (n-1)b_{n-2}$ (where $n\ge1$). Let $B(x)$ be the recurrence relation for the sequence $b_n$.
Show that $B(x)=e^{x+\frac{x^2}{2}}$.
ATTEMPTS SO FAR
In order for the situation to make sense, I have set $b_0=b_1=1$.
Tried using the recursive formula to derive an Ordinary Generating Function.
$B(x)=\sum_{n\ge0}b_nx^n=b_0+\sum_{n\ge1}(b_{n-1}+(n-1)b_{n-2})x^n=...nothing...happy...$
I'm sure that an Exponential Generating Function is the way to go (seeing as the equation we want to end up with is exponential). But the working seems to get complicated and I'm not sure where to go with it.
Let $B(x)=\sum_{n\ge0}\frac{b_nx^n}{n!}=b_0+\sum_{n\ge1}\frac{b_{n-1}+(n-1)b_{n-2}}{n!}x^n$
$=1+\sum_{n\ge1}\frac{b_{n-1}}{n!}x^n+\sum_{n\ge1}\frac{(n-1)b_{n-2}}{n!}x^n$
$=1+\sum_{n\ge0}\frac{b_{n}}{(n+1)!}x^{n+1}+\sum_{n\ge2}\frac{(n-1)b_{n-2}}{n!}x^n$
$=1+\sum_{n\ge0}\frac{b_{n}}{(n+1)!}x^{n+1}+\sum_{n\ge0}\frac{(n+1)b_{n}}{(n+2)!}x^{n+2}$
This is where I get stuck. I've gone over many pages of working and scribbles trying to move on from here, but I have nothing. Not a clue!
Am I on the right track at all? And if so, where should I be heading from here?
Comment: Aside: I think the question, in place of "Let $B(x)$ be the recurrence relation for the sequence $b_n$", should have "Let $B(x)$ be the [exponential] generating function for the sequence $b_n$".
Comment: @ShreevatsaR Yeah, I think so, too. That's what was throwing me off to begin with. Then I assumed that I just needed to find an EGF for $b_n$, which is how I got on to the track mentioned above.
Comment: Yes definitely the right question is to find an EGF; note that $\exp(x + x^2/2) = 1+x+\frac{2x^2}{2!}+ \frac{4x^3}{3!} + \frac{10x^4}{4!} + \dots$ and the coefficients satisfy the recurrence.
Comment: I can see that it is satisfied, but only because I know that it should be. How do I got about proving this, though?
Comment: I think I've come up with a good solution and have just posted it as an answer.
Answer: Just messing about with random tricks to see if anything helped, and I'm pretty sure I've managed to come up with a solution! I'm 99% sure that the working is legit, and I get the right generating function at the end, so I'm pretty confident. Below is my solution (if anyone has a better way, feel free to post it).
SOLUTION
Given $b_n=b_{n-1}+(n-1)b_{n-2}$, let $B(x)=\sum_{n\ge0}\frac{b_n}{n!}x^n$ be the EGF for $b_n$.
Define $b_1=b_0$ (from recurrence formula). Set $b_1=b_0=1$.
Let $m=n+1$, then $b_{m+1}=b_{m}+mb_{m-1}$
Now, the generating function for the $b_{m+1}$ must be equal to the generating function for $b_{m}+mb_{m-1}$. So we have:
$\sum_{m\ge0}\frac{b_{m+1}}{m!}x^m=\sum_{m\ge0}\frac{b_{m}}{m!}x^m+\sum_{m\ge0}\frac{mb_{m-1}}{m!}x^m$
$\sum_{m\ge1}\frac{b_m}{(m-1)!}x^{m-1}=\sum_{m\ge0}\frac{b_{m}}{m!}x^m+\sum_{m\ge1}\frac{b_{m-1}}{(m-1)!}x^m$
$\sum_{m\ge1}\frac{b_m}{(m-1)!}x^{m-1}=\sum_{m\ge0}\frac{b_{m}}{m!}x^m+x\sum_{m\ge1}\frac{b_{m-1}}{(m-1)!}x^{m-1}$
$\sum_{m\ge1}\frac{b_m}{(m-1)!}x^{m-1}=\sum_{m\ge0}\frac{b_{m}}{m!}x^m+x\sum_{m\ge0}\frac{b_m}{m!}x^m$
We know $B(x)=\sum_{n\ge0}\frac{b_n}{n!}x^n$ and we can differentiate to get $B'(x)=\sum_{n\ge1}\frac{b_n}{(n-1)!}x^{n-1}$, so substituting these values in to the above expression, we get:
$B'(x)=B(x)+xB(x)$
$B'(x)=(1+x)B(x)$
$\frac{B'(x)}{B(x)}=1+x$
Integrating both sides, we get:
$ln(B(x))=x+\frac{x^2}{2}+c$
Therefore, $B(x)=e^{x+\frac{x^2}{2}+c}$. Finally, $B(0)=b_0=1$ (as defined above).
$B(0)=e^{0+\frac{0^2}{2}+c}=e^c=1$, so $c=0$.
Hence we get the final EGF: $B(x)=e^{x+\frac{x^2}{2}}$, which is what we wanted!
Comment: Really nice solution, congratulations. :-) The main trick seems to be making sure that the $(n-1)b_{n-2}$ term gets multiplied by $x^{n-1}/(n-1)!$ rather than say $x^n/n!$ or $x^{n-2}/(n-2)!$, so that the $(n-1)$ factor cancels cleanly and we don't have to solve too-complicated differential equations.
Comment: @ShreevatsaR Thanks! You're right, that does seem to be the trick.


Adding Pager to entity referenCED field display

Question: I have two content types: Parent and Child
I have an entity reference field (called "Link") in parent content type referencing it to child content type.
I am using inline entity forms module for the entity reference field .
I want to know if there is a way to achieve the following:
Question 1:
I want to have a read more button on parent content type, which would open the first entity referenced child page.
Question 2:
I want to have a pager in the child page which would link to the other child pages of the same entity referenced parent content type.
(something similar to what books module provides for book child in child pages)
Any help would be highly appreciated. Thank You.
Answer: There might be better way of doing that.
But one of the way will be to use views module
Answer to question 1:

Go to your_site/admin/structure/types/manage/content_type/display
Change the reference field format to Rendered entity
Click the setting and make sure Show links is checked

Answer to question 2:

Install the module views if you don't have it already
Go to yoru_site/admin/structure/views/add
Give your view name for example read more button to parent content type
Unchecked Create a page and Check Create a block
Click Continue & edit
Change format to "Table"
Click add filed and select the fields you want to show
Click add Filter criteria and select the criteria you want
Click the Advance and Add Contextual Filters
SelectContent  Content: Nid"
Select Relationship as content entity referenced from your_xyz
Change the option for When the filter value is NOT available to Provide default value and select Content ID from URL.
Change When the filter value IS available or a default is provide to Specify validation criteria and select Content from Validator select field, and select the parent content.
Make sure Filter value format  is = to Node ID
Make sure Action to take if filter value does not validate is = Hide view
Click Apply
Add a Relationship, Click add and select Entity Reference
Click Save.
Go to yoru_site/admin/structure/block, search for the new view name black you just added.
Click configure change the Visibility settings  to content type and select the parent content type.
Set the Region where you want the black to be display.
Comment: Thanks for the speedy response. I think i had not explained the question well. I made some edits, hope it helps you understand it better. I used your answer to the second question to solve the first problem. Yes I had views installed ( Can't imagine a day with drupal without views, All hail Merlin :) )
Answer: I solved my first question with the help of the detailed instructions from Yama as below:

Create a block view of html list .
Use relationship: Entity Referencing.
Click Advance and Add Contextual Filter
SelectContent Content: Nid"
Select Relationship as content entity referenced from your_xyz
Change the option for When the filter value is NOT available to Provide default value and select Content ID from URL.
Change When the filter value IS available or a default is provide to Specify validation criteria and select Content from Validator select field, and select the parent content.
Make sure Filter value format is = to Node ID
Make sure Action to take if filter value does not validate is = Hide view
Click Apply
Click Save.
Go to your_site/admin/structure/block, search for the new view name block you just added.
Click configure change the Visibility settings to content type and select the parent content type.
Set the Region where you want the black to be display.

Instead of Steps 12 to 14, I used Display Suite, Block Field feature.
It works like a charm.


Is the Magento 2 community dead? (not getting answers)

Question: I'm just curious how active the Magento 2 community is . I've asked couple of questions and no one is answering. Also noticed a lot of questions unanswered. Is the M2 community dead or its just that there aren't too many Magento 2 devs?
Comment: Not sure about the community but for me... I'm not dead. I checked.
Comment: magento 2 community is busy migrating all the sh-load of custom code from m1
Comment: Haha! good to know.
Answer: from what I see your questions tend to be quite broad feature requests. These seldom get proper answers here.
I can recommend narrowing them down and adding things like what you have tried so far. Any code that is failing, specific errors the community can help you with.
Comment: Okay, thank you for your feedback. I'll try to do just that.
Comment: I have asked many questions.none of any broad feature requests,although it is not answerd
Answer: Magento 2 community is not dead but there are few reason for not getting response very soon as you get on stackoverflow because:

There are less number of Magento developer as compared to core PHP
web developers and more less developers of Magento 2 framework who
are expert.
Writing code of Magento 2 questions requires more effort.
Even if developer knows that answer if it requires lot of verification and writing lot of coding he skips that question.
Comment: That makes sense. It might be one of the reasons I'm not getting any answers. Its just tough for new comers to Magento like me to figure things out on our own that is why we are seeking out for help. Thanks.
Answer: No Magento 2 community is not dead it's working hard to resolve issue which are faced by us.I know there are very few discussion on magento community is just because of less magento 2 developer but still it help many new magento developers and it's a grate place to learn things.
Answer: Magento 2 community is not dead, most of the question which are not answered are the ones that are not even following Question/Answer format of the site, if question is just mentioning a feature that is required/ I am getting this error and no logs , no debugging on your end etc. the person is just copy pasting client requirement / work assigned to him on stackexchange.
Such low quality and low effort posts are quite common on magento stackexchange where people have not yet mastered magento 2 fully.
In my honest opinion these posts should just be flagged "too broad" and closed.


How can i create in incremental backups of mysql databases

Question: I have linux centos 6.4 server with mysql5.6
I have the cron job for making hourly mysql database backups like this
Its in python
os.popen("mysqldump -u %s --password=%s -h %s -e --opt --skip-lock-tables  --skip-extended-insert -c %s | gzip -c > %s.gz" % (username, password, hostname, database, filename))

The problem is very little data gets chnaged but every time i have to backup all databases 24 times , which takes too much space.
What is best alternative for that
Is there any way to have incremental backups so that i take 1 full backup of database evry week  and then only incremental backups.
I want to have separate files for separate databases so that if i need to restore single database then i can do that as well
Answer: Very simple: binlogging. Configure mysql to keep the binary log for at least one day (possibly longer). Then change your backup to not do mysqldump, but use something like xtrabackup.
That way you can reduce your backup schedule to once per day and still have the possibility to roll forward to any point in time using the binlog.
Comment: Sounds like a case for versioning within your application, not backup.
Comment: My main issue is i need to only restore 1 or 2 databases not whole mysql . suppsoe i want to restore the last hour backup of my `database1` on test system to see what chnages user has done which disrupts the system
Answer: It's pretty silly to be backing up every hour for most situations. Maybe you need to consider mysql replication to another node.
Comment: i have only one VPS server and my budget is very tight. so i can't afford new server.
Comment: In that case, can you think of any scenario in which you would need to  restore from a particular hour within the day? A full dump once a day should really be enough. Worst case scenario, you lose <24 hours of changes.
Answer: You can do incremental backups with xtrabackup. To restore a single database prepare the full and incremental backups (that include all databases) and then run MySQL using the xtrabackup directory as the datadir and take a mysqldump of the single database you want.
Answer: If you want to save space, you could continue to do your full backups hourly but to a deduplicated filesystem like lessfs.  You could easily carve off a partition and format/mount it with lessfs and then let it handle the deduplication while still being able to restore at any hourly point, just without the space.