PHPDoc - O que é, qual sua utilidade e como usar?

Question: Nesses dias ando mexendo bastaste em arquivos de frameworks, projetos, etc...e estou vendo varias coisas que nunca vi, uma delas é o tal do PHPDoc (consegui o nome graças a minha IDE), mas pesquisando aprendi muito pouco sobre!
Exemplo:
<code>class Foo {
    /**
     * Constructor
     *
     * @param string $string
     * @return string
     */
    public function __construct($string){
        return $string;
    }
}
</code>
Agora as perguntas:

O que é PHPDoc?
Qual sua utilidade?
Como usar?
Tem alguma regra, recomendação do PSR sobre isso? Se sim, qual?
Comment: [Qual a diferença entre tipos de comentários em PHP?](http://pt.stackoverflow.com/q/94374/91)
Comment: Tem os comentário normais da linguagem. De linha, via o caracter # ou //. De múltiplas linhas /* igual ao do C . E aqueles com semântica que começam com /** interpretados por pré processadores como o PHPDOC, Doctrine.
Answer: O que é PHPDoc?
Para não confundir aqui vou usar o termo DockBlock alguns vão chamar de doclet ou PHPDoc, isso não importa, o que é importante é diferenciar o PHPDoc comentário do PHPDoc ferramenta.
O PHPDoc ferramenta gera documentação automaticamente com base no código e em comentários DockBlock. Porém você pode usar outras ferramentas para gerar essa documentação, eu particularmente prefiro o ApiGen.
O DockBlock começa com /**  , eles tem origem no javadoc e podem (ou não) ter uma infinidades de tags que começam com @;
Qual sua utilidade?
Docblocks são um meio de comunicação entre quem faz o código e quem o consome. Quando você passa seu código para terceiros, ou obtêm um código essa documentação vai ajudar no entendimento, uso e modificação do mesmo.
Eles servem de base para gerar uma documentação objetiva que pode abordar uma série de questões comuns a quem consome o código.
Posso utilizar livremente o código em meus projetos? (@license);
Quem é o autor do código? (@author);
O que essa função retorna? (@return);
etc;
Essas tags se comunicam bem com a máquina elas ajudam o IDE a entender o código, no site do PHPDoc existe uma lista de tags são suportadas pelas ferramentas de geração de documentação.
Existem também frameworks como o Doctrine e PHPUnit que aceitam suas próprias tags nesses comentários. Com elas é possível, por exemplo, mapear e gerar todo o banco de dados ou entidades de uma aplicação com o Doctrine mas esse uso já foge da questão de documentação.
Como usar?
Dentro da filosofia de Robert C. Martin a regra básica que recomendo é: coloque o mínimo possível de comentários mas o suficiente para ser claro.
A exceção é se você vai disponibilizar o código publicamente então - a exemplo dos sistemas open sources mais comuns em PHP - quanto mais explicado melhor, fora este caso raramente vale a energia documentar muito.
Lembre-se que você vai ter manter os comentários coerentes com o código, é muito comum o código ser refatorado e os comentários passarem informações erradas por estarem defasados, por isso muitos consideram comentários como um tipo de duplicação de código.
Qualquer código, função, variável, classe, devem ser claros o suficientes para entendermos o eles fazem e são dentro do seu contexto, sem precisarmos de nenhum comentário explicando.
Quando não atingimos esse ideal um comentário é bem-vindo. Ele pode ser um alerta, esclarecimento ou explicação. Mas esses comentários são sempre fracassos da nossa capacidade de se expressar através do código.
Quando necessário ele deve ser preciso e claro para não confundir, um comentário ruim mais atrapalha do que ajuda.
Existem muitas tags no padrão phpdoc, mas não considero que seja ideal manter a maioria dessas informações em um DocBlock, quando estão nele costumam ser apenas firulas. Autoria, versão, modificação, por exemplo ficam melhor em um sistema de controle versão. Outros exemplos de comentários ruins são aqueles óbvios ou redundantes em relação ao código, são apenas poluição.
Exemplo de documentação inútil:
<code>/**
* Entidade Usuário
*/
class user {
    /**
    * nome do usuário
    */
    $nome;

    //...

    /**
     *Estabelece o Nome do usuário
     */
    function setName(){//... }

    /**
     *Pega o Nome do usuário
     */
    function getName(){//... }

    // …

}
</code>
O que vale a pena documentar normalmente são os tipos retornados pelas funções, tipos das variáveis, e tipos dos parâmetros. Mesmo assim só documente quando não é possível a indução (Com PHP 7 a necessidade de documentação deve diminuir). Isso facilita bastante a vida.
Tem alguma regra, recomendação do PSR sobre isso? Se sim, qual?
A regras de apresentação do código na PSR-2 se aplicam a DocBlocks, fora isso existe apenas um rascunho em desenvolvimento que poderá vir a ser uma recomendação no futuro. Pode ser lido aqui: https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md
Answer: PHPDoc é uma forma de adicionar informações sobre uma estrutura(méotodo ou classe etc) elas são úteis para algumas ferramentas que geram documentação automaticamente apartir desses 'comentários'. Essas informações são importantes para IDE com elas suas classes entram no auto-complete então é fácil ir navegando de um método a outro.
Para usar o doclet é quase igual a um comentário o fato importante é que após a barra são necessarios dois asteriscos do consecutivos.
<code>/** doclet
/* comentário
</code>
Answer: O PHPDoc foi baseado no JAVADoc da Sun e tem como objetivo padronizar a documentação de códigos PHP. Ele lê o código e analisa gramaticalmente procurando por tags especiais. A partir delas extrai toda documentação usando diferentes formatos (pdf, xml, html, chm Windows help e outros). Todas as tags especiais são escritas dentro do comentários do php /*comentários */ e necessariamente começam com o @ (arroba).
Descrição de algumas tags especiais:
<code>@access Especifica o tipo de acesso (public, protected e private).
@author Especifica o autor do código/classe/função.
@copyright Especifica os direitos autorais.
@deprecated Especifica elementos que não devem ser usados.
@exemple Definir arquivo de exemplo, $path/to/example.php
@ignore Ignora código
@internal Documenta função interna do código
@link Link do código
@see Define uma referência a outro elemento ou uma URI
@since Define a partir de qual versão os elementos estruturais foram disponibilizados
@name Especifica o apelido (alias).
@package Especifica o nome do pacote pai, isto ajuda na organização das classes.
@param Especifica os paramêtros (muito usado em funções).
@return Especifica o tipo de retorno (muito usado em funções).
@subpackage Especifica o nome do pacote filho.
@version Especifica a versão da classe/função.
</code>
Para gerar a documentação, pode-se instalar a ferramenta utilizando PEAR, Composer ou download manual.
Referências:
Linha de Codigo
PHPDoc


How to send a Group email based on date field using Rules?

Question: I'm using the Group module and I have a Group content type called Events with a date field. I am having trouble figuring out how use Rules to send an Email on the same day as the date field to all the members of the Group.
I've tried creating a rule but it's just wrong:

Event: runs on cron
Condition: group content, datefield equals, is node type Event
Action: get group members from group audience, loop group members, send email

Most of what keeps showing up in my searches to answer my question, are not for Group content.
Any help?
Comment: Yes, I'm using the group module.
Answer: This is typically something you can get to work using the Rules module, together with Rules Scheduler (a sub-module of it), as explained in the steps below.
Step 1: Enable the Rules Scheduler
Enable the Rules Scheduler (a sub-module of Rules). And make sure your cron jobs are running (to ensure that scheduled rules actually start executing.
Step 2: Create a Rules "Component"
Create a Rules Component labeled something like Notify all members of a Group, which looks like so (in Rules export format):
{ "rules_notify_all_members_of_a_group" : {
    "LABEL" : "Notify all members of a Group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "group" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "group" : { "label" : "Group", "type" : "group" },
      "event_node" : { "label" : "Event node", "type" : "node" }
    },
    "ACTION SET" : [
      { "entity_query" : {
          "USING" : {
            "type" : "group_membership",
            "property" : "group",
            "value" : [ "group" ]
          },
          "PROVIDE" : { "entity_fetched" : { "group_members" : "Group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "member_of_group" : "Member of group" },
          "DO" : [
            { "drupal_message" : { "message" : "Group member named \u0022[member-of-group:user:name]\u0022 and eMail Id \u0022[member-of-group:user:mail]\u0022 is a member of the \u0022[group:group-type]\u0022 group titled \u0022[group:title]\u0022 and group id \u0022[group:gid]\u0022, related to the node with id [event-node:nid] and title [event-node:title] (and date [event-node:field-expiration-date])." } },
            { "mail" : {
                "to" : "[member-of-group:user:mail]",
                "subject" : "eMail notification to group [group:title]",
                "message" : "Hello [member-of-group:user:name],\r\n\r\nyou are a member of the group [group:title] (which is of type [group:group-type]).\r\n\r\nYou are receiving this eMail as a friendly reminder related to the node with id [event-node:nid] and title [event-node:title] (and date [event-node:field-expiration-date]).\r\n\r\nGreetings,\r\n\r\nPS: contact the site admin by eMail (via [site:mail]) for more details if needed",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Some more details about this Rules Component:

The type of this Rules Component is an "Action Set" (no need for any conditions).
Action 1 is to build a list of all the members of the group. It uses "Fetch entity by property", with these additional specs:

Entity type value = Group Membership.
Property value = Group.
Value of the data selector = Group.
Limit result count = blank (we do not want to limit the nr of results).
Provided variables = "Group members" (variable label) and "group_members" (variable name).

Action 2 is to iterate (= loop) over each of the members of the group. It uses "Add a (Rules) loop", with these additional specs:

The list to loop over = group-members
Current list item = "Member of group" (variable label) and "member_of_group" (variable name).
Sub-action (i) of this Action 2 is to just "Show a message on the site" (while QA-testing this Rules Component), with message type = Status and with an appropriate message using various tokens which might be interesting.
Sub-action (ii) of this Action 2 is to actually send an eMail to the "member_of_group" being processed in the loop, using various tokens similar to those in Sub-action (i).

If you have the Rules UI enabled , as well as the Group module, you can simply import the above rule in your own site, no need to tweak anything in it. Though you may want to tune the Subject and Message content of the actual eMail (just remember the various tokens you may want to use), while you might also want to use some other From eMail ID. And after QA-testing it, you probably want to remove the Rules Action "Show a message on the site".
Step 3: Create a "Rule" using the Rules Component
Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste):
{ "rules_schedule_group_notification" : {
    "LABEL" : "Schedule Group notification",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" },
      "node_update--article" : { "bundle" : "article" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_event_date" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_notify_all_members_of_a_group",
          "task" : "[node:nid]"
        }
      },
      { "schedule" : {
          "component" : "rules_notify_all_members_of_a_group",
          "date" : [ "node:field-event-date" ],
          "identifier" : "[node:nid]",
          "param_group" : [ "node:group" ],
          "param_event_node" : [ "node" ]
        }
      }
    ]
  }
}

The above rule refers to the Rules Component from the previous step. And is based on these assumptions:

The content type of the event node is has machine name article (adapt prior to import to fit your case).
The field "Event date" has machine name field_event_date (adapt prior to import to fit your case).

The schedule_delete that is part of this rule is to ensure that previously "scheduled" notifications will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recently entered date).
Attention: whatever gets updated in such node, will each time trigger this rule. Even if the actual date itself is not updated. If that's not what you want, just add additional Rules Conditions so that the rules Actions are only performed if the date is updated.
PS: I'm assuming this question is about D7.


Squid not caching from npm, but is from curl

Question: I'm hoping I'm being blind here, but I'm trying to cache registry.npmjs.org very aggressively using squid, but really can't get it working.
I've compiled squid with --enable-http-violations, and I'm getting the warnings when it starts, and I'm using the following cache line:
refresh_pattern -i registry.npmjs.org/.* 900 20% 4320 ignore-no-store ignore-auth ignore-private ignore-no-cache ignore-reload override-expire override-lastmod

Now it seems to cache as I expect, when using curl, but not when using the npm client.  I've put the two logs below but I can't see what header/difference would be causing one to cache but the other not to
Using curl (caches as expected):
1488230087.926      0 127.0.0.1 TCP_MEM_HIT/200 2710 GET http://registry.npmjs.org/should-util - HIER_NONE/- application/json [User-Agent: curl/7.51.0\r\nAccept: */*\r\nProxy-Connection: Keep-Alive\r\nHost: registry.npmjs.org\r\n] [HTTP/1.1 200 OK\r\nServer: nginx/1.10.1\r\nContent-Type: application/json\r\nLast-Modified: Mon, 08 Aug 2016 15:17:14 GMT\r\nETag: "57a8a27a-871"\r\nCache-Control: max-age=300\r\nContent-Length: 2161\r\nAccept-Ranges: bytes\r\nDate: Mon, 27 Feb 2017 20:44:44 GMT\r\nVia: 1.1 varnish\r\nAge: 0\r\nX-Served-By: cache-lcy1134-LCY\r\nX-Cache: MISS\r\nX-Cache-Hits: 0\r\nX-Timer: S1488228284.071646,VS0,VE18\r\nVary: Accept-Encoding\r\nConnection: keep-alive\r\n\r]

Using npm client (does not cache):
1488230089.133     89 127.0.0.1 TCP_MISS/304 368 GET http://registry.npmjs.org/should-util - HIER_DIRECT/188.8.131.52 - [Accept-Encoding: gzip\r\nversion: 4.1.2\r\nAccept: application/json\r\nReferer: view should-util\r\nnpm-session: 169f8528ea8fd926\r\nnpm-in-ci: false\r\nUser-Agent: npm/4.1.2 node/v7.6.0 linux x64\r\nIf-None-Match: W/"57a8a27a-871"\r\nIf-Modified-Since: Mon, 08 Aug 2016 15:17:14 GMT\r\nConnection: keep-alive\r\nHost: registry.npmjs.org\r\n] [HTTP/1.1 304 Not Modified\r\nDate: Mon, 27 Feb 2017 21:14:49 GMT\r\nVia: 1.1 varnish\r\nCache-Control: max-age=300\r\nETag: W/"57a8a27a-871"\r\nAge: 83\r\nX-Served-By: cache-lcy1132-LCY\r\nX-Cache: HIT\r\nX-Cache-Hits: 2\r\nX-Timer: S1488230089.111498,VS0,VE0\r\nVary: Accept-Encoding\r\nConnection: keep-alive\r\n\r]

Comment: Because you are getting a HTTP code 304, I am digging into this issue also, you can find some useful discussion here:
http://lists.squid-cache.org/pipermail/squid-users/2016-October/013018.html
Answer: We ran into a similar issue with using nginx proxy_cache for caching proxied objects for NPM - at speedtest.net we ended up using this project: https://github.com/mixu/npm_lazy for caching requests to NPM. It works great with private modules as well. We've used it across over 40,000 builds with no issues and it's handled npm outages without an issue.
With that said, we have run into issues with it and Yarn, though it may be Yarn at fault.


Will changing an SSL binding to new certificate in IIS7 affect Application Pools, i.e. cause them to recycle?

Question: I want to change SSL bindings to a replacement certificate, but don't want to affect logged in users.
Will doing this cause the Application Pools for the web site to recycle?
Many thanks,
Kenny
Comment: If I remove SSL binding completely and then re-add the same again, my app pool is still running without recycling. But the app pool I have tested runs PHP via FastCGI which may work completely different to the asp.net (hence the comment a not the answer).
Comment: Thanks for the comment, good to know. Still keen to find out if it'll affect Asp.Net apps.
Comment: Well, you can try this (if you can, of course -- maybe this app is not designed to work on non-standard ports etc): 1) duplicate your site in question on another app pool (put it on the same SSL certificate but different port); 2) login as a customer there; 3) replace certificates and see if it the job (if I understand correctly you will be logged out on website if app pool recycles). **If** you need to perform this operation rather urgently it may be quicker compared for someone posting the 100%-assured answer here.
Answer: I have just done this in IIS7.5 and it did reset the application pool


Write bytes from blob IMAGE into a txt file

Question: I wrote this code to convert one of my documents from "blob" IMAGE to txt file. Export works properly. When I open the file, it not contains only text but another the information, like file name, path and then obscure information.
I attach an example:
        File name: new 1.txt
        Text original file: CIAO6
ÐÏà¡±á                >  þÿ                                   þÿÿÿ          ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿýÿÿÿþÿÿÿþÿÿÿþÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿR o o t   E n t r y                                               ÿÿÿÿÿÿÿÿ         À      F             €N&¥¥÷Ð           O l e 1 0 N a t i v e                                              ÿÿÿÿÿÿÿÿ                                       `       C o m p O b j                                                    ÿÿÿÿÿÿÿÿÿÿÿÿ                                        L                                                                            ÿÿÿÿÿÿÿÿÿÿÿÿ                                                   þÿÿÿ                þÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿ þÿ
   ÿÿÿÿ      À      F   OLE Package        Package ô9²q                                                                \   new 1.txt C:\Users\stefano\Desktop\new 1.txt    7   C:\Users\STEFAN~1.CER\AppData\Local\Temp\new 1 (2).txt    CIAO6   C : \ U s e r s \ S T E F A N ~ 1 . C E R \ A p p D a t a \ L o c a l \ T e m p \ n e w   1   ( 2 ) . t x t       n e w   1 . t x t *   C : \ U s e r s \ s t e f a n o\ D e s k t o p \ n e w   1 . t x t
 protected void onEventImpl(Event event)
            {
                 ...
                String fileName = aaDocumentoMultimedia.getPercorso();
                byte[] documento = aaDocumentoMultimedia.getDocumento();
                Date docData = aaDocumentoMultimedia.getDataRegistrazione();
                if (StringUtils.isNotBlank(fileName))
                {
                    migrazioneDocumentiManager.writeFileOnDisk(fileName, documento, docData);
                }
                 ...
            }

@Override
public void writeFileOnDisk(String fileName, byte[] documento, Date registrationData) throws SQLException, FileNotFoundException, IOException
{
    ByteArrayInputStream input = null;
    FileOutputStream output = null;
    try
    {
        (new File(getPathFile(registrationData))).mkdirs();

        input = new ByteArrayInputStream(documento);
        output = new FileOutputStream(new File(getPathFile(registrationData) + fileName));

        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while (-1 != (n = input.read(buffer)))
        {
            output.write(buffer, 0, n);
        }
        output.flush();

    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        if (input != null)
        {
            input.close();
        }
        if (output != null)
        {
            output.close();
        }
    }
}

Comment: the word "convert" makes no sense in your case - you arent converting anything. At all. You simply write bytes into a file.
Answer: Well, two points:

You have to ensure this code is executed within the data base session, other way you won't read correctly blob content.
Although you flushed output stream, you don't close input/output streams, it would be nice.

Considerations away, your code is ok, so, are you sure your blob content is ok? You could test your blob content with some apps as squirrelSql. Maybe your problem is when storing blob?
Instead the while bucle, you could also use org.apache.commons.io.FileUtils from apache-commons-io (I used 2.4) this is what I used to convert from blob to files:
FileUtils.copyInputStreamToFile(inStream, blobFile);

With this approach you won't need outStream, length, size and buffer.
Comment: Thank you for your response. I answer immediately:
* I have the blob file and export works.
* I closed the input/out I but I did not write this code here.
* The blob on db is it's correct.
Comment: I tried it with your new code but still persists Error. I can not even open files with other extensions correctly, as .xls, docx
Comment: I insert other code , maybe the problem is elsewhere
Comment: Not sure, I don't see anything wrong in your code, and I can ensure my code works.  Can you compare size of a file generated with this code and the same file exported from database?
Comment: I did some tests of reading and writing file on disk and worked.
I think that the problem is decoding doing hibernate file blob .
I use Microsoft SQLServer . Field where are the file content is type IMAGE
Comment: I have no experience with mssql, always worked with postgre, oracle, MySQL and hypersonic


How to order tests using junit 5

Question: I'm Created some automation test in java , using appium and junit 5.
I'm trying to Order my test with @Order annotation before each test.
And before test class I'm using @TestMethodOrder(MethodOrderer.OrderAnnotation.class).
But it still not ordered.
Below the code you can see attachment with tests order.
Based on what it looks like, it doesn't make any order right now.
Maven dependencies:
<dependencies>
        <dependency>
            <groupId>io.appium</groupId>
            <artifactId>java-client</artifactId>
            <version>7.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.6.0-M1</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>

Class with tests:
package Tests;

import AppiumBase.BaseTestClass;
import Components.DrawerNavigation;
import Components.RenewPolicy;
import Utils.CustomAnotations.Attributes;
import Utils.CustomScreenAction;
import com.sun.org.glassfish.gmbal.Description;
import org.junit.jupiter.api.*;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.core.annotation.Order;

import static Utils.CustomAnotations.Attributes.TEXT_VIEW;

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@TestInstance(TestInstance.Lifecycle.PER_METHOD)
@DisplayName("Renew policy functionality")
@Attributes
public class RenewPolicyTest extends BaseTestClass {

    private WebDriverWait wait;
    private DrawerNavigation drawerNavigation;
    private RenewPolicy renewPolicy;
    private CustomScreenAction csa;

    @BeforeEach
    void executeBeforeEachTestInThisClass() {
        wait = new WebDriverWait(driver(), 10);
        drawerNavigation = new DrawerNavigation(driver());
        renewPolicy = new RenewPolicy(driver());
        csa = new CustomScreenAction();
    }

    @AfterEach
    void executeAfterEachTestInThisClass() {
        wait = null;
        drawerNavigation = null;
        renewPolicy = null;
    }

    @Test
    @Order(1)
    @DisplayName("Check renew policy button")
    @Description("Verify that the renew policy button appear on main screen")
    void isButtonAppear() {
        renewPolicy.isRenewPolicyButtonAppearOnMainScreen();
    }

    @Test
    @Order(2)
    @DisplayName("Check renew policy screen is opens")
    @Description("Verify that the renew policy button on MAIN SCREEN is clickable and right screen is opens")
    void isRenewPolicyScreenAppear() {
        renewPolicy.clickOnRenewPolicyButton();
    }

    @Test
    @Order(3)
    @DisplayName("Check renew policy screen opens from side menu")
    @Description("Verify that the renew policy button on DRAWER NAVIGATION is clickable and right screen is opens")
    void isRenewPolicyScreenOpenOnClickButtonFromDN() {
        drawerNavigation.openSideMenu();
        drawerNavigation.openRenewPolicyScreen();
    }

    @Test
    @Order(4)
    @DisplayName("Check checkbox")
    @Description("Check that the checkbox is checkable")
    void isCheckBoxCheckable() {
        renewPolicy.clickOnRenewPolicyButton();
        if (renewPolicy.isRenewPolicyScreenOpens()) {
            CustomScreenAction csa = new CustomScreenAction();
            csa.scrollToElement(TEXT_VIEW, "לשינויים אפשר לפנות למוקד");
        }
        renewPolicy.checkCheckBox();
    }

    @Test
    @Order(5)
    @DisplayName("Check confirm and pay button - disabled")
    @Description("Verify that the button is disabled while checkbox not checked")
    void isButtonDisabled() {
        renewPolicy.clickOnRenewPolicyButton();
        if (renewPolicy.isRenewPolicyScreenOpens()) {
            csa.scrollToElement(TEXT_VIEW, "מאשר תשלום וחידוש פוליסה");
        }
        if (renewPolicy.isConfirmAndRenewPolicyButtonDisplay()) {
            csa.isElementDisabled(renewPolicy.getConfirmAndRenewPolicyButton());
        }
    }

    @Test
    @Order(6)
    @DisplayName("Check confirm and pay button - enabled")
    @Description("Verify that the button is enabled while checkbox checked")
    void isButtonEnabled() {
        renewPolicy.clickOnRenewPolicyButton();
        if (renewPolicy.isRenewPolicyScreenOpens()) {
            csa.scrollToElement(TEXT_VIEW, "מאשר תשלום וחידוש פוליסה");
        }
        renewPolicy.checkCheckBox();
        if (renewPolicy.isConfirmAndRenewPolicyButtonDisplay()) {
            csa.isElementEnabled(renewPolicy.getConfirmAndRenewPolicyButton());
        }
    }
}

Output:
Comment: I can see the tests are ordered in the way you have marked them with @Order. What is your expectation ?
Comment: Post the complete code of your test, from line 1 (and thus including the import statements).
Comment: You have `@Order(1)` set on two tests: `Check renew policy button` and `Check checkbox`.
Comment: Hi @JBNizet , I'm updated the question with the full code. please see. Also changel Order number of check checkbox, but still not working
Comment: Now look at the imports: would JUnit rely on an annotation coming from the Spring framework, and thus force every user of JUnit to also use Spring, rather than using its own?
Comment: On a side note, try to avoid ordering in unit testing. In general, JUnit runs tests using a deterministic, but unpredictable order. Unless you really need to order them you should ignore ordering.
Answer: Your import is wrong, replace import org.springframework.core.annotation.Order; with import org.junit.jupiter.api.Order;

How to order tests using junit 5


How to check if Python3 was built with '--enable-shared'?

Question: Environment:

Mac OS X 10.8.5
Apache 2.2.26
Homebrew Python 3.3.3

Problem:
I am trying to install mod_wsgi but first need to determine if Python was configured and compiled with the '--enable-shared' option.
Questions:

How can I determine if Homebrew installed Python with the '--enable-shared' option?
If it was not installed, what is the correct way to install it?

Thank you!
Comment: http://stackoverflow.com/questions/10192758/how-to-get-a-list-of-options-that-python-was-compiled-with - This works with python 3.
Comment: The ``--enable-shared`` option will not be relevant if Python was installed as a MacOS X style framework.
Answer: From the python repl:
import sysconfig
sysconfig.get_config_vars('Py_ENABLE_SHARED')

Comment: thanks! 'print(sysconfig.get_config_vars('Py_ENABLE_SHARED'))' returned 'SyntaxError: invalid syntax' but just 'sysconfig.get_config_vars('Py_ENABLE_SHARED')' returned '[0]', which I'm assuming means false / "this feature is not enabled".
Comment: Correct, it is a boolean return so, you are correct. The feature is not enabled.  I will fix the syntax error.
Answer: A bit better is to use
import sysconfig
sysconfig.get_config_var('Py_ENABLE_SHARED')

This returns the integer value 0 or 1 directly.
The plural form is used to get multiple values or a whole dict if no argument is given, see https://docs.python.org/3/library/sysconfig.html?highlight=get_config_vars#sysconfig.get_config_vars


Repeated measures over time with small $n$

Question: I was given data to analyze for a study looking at the effects of a treatment on iron levels at four different time points (before treatment, the day treatment ended, 4 weeks after treatment, and 2-4 months after treatment).  There is no control group.  They are looking to see if there are significant increases in iron levels at each of the 3 post-treatment time points to the before treatment (baseline) level.  Eleven patients had baseline levels but only 8 patients had complete data for all 4 time points ($n$=11, 10, 9, and 8 for each time point).  Not only were iron levels measured, but two other laboratory measures were taken at each time point to be compared to baseline.
I have a few questions as to how to analyze this.  I first thought an RM ANOVA would be appropriate to analyze this data, but I was concerned about the small sample size, the loss of data, and the non-normal distribution of the data.  I then considered comparing each post-treatment measure to baseline using Wilcoxon signed-rank tests, but then I run into the issue of multiple comparisons.  However, I have read some literature that downplays needing to run multiple comparisons.  So overall, I'm dealing with small sample sizes, incomplete data, and multiple comparisons (and whether or not its necessary).
I hope this all made sense.  I'm new to CrossValidated and was directed here by a colleague as a place to learn from experienced statisticians, so I'd appreciate any advice!  Thanks!

Edited to add raw data from comment:
There are four total time points and the outcome variable is continuous. For example, the results at each time point look similar to this:
 Baseline (n=11): [2, 7, 7, 3, 6, 3, 2, 4, 4, 3, 14]
 1st Post (n=10): [167, 200, 45, 132, ., 245, 199, 177, 134, 298, 111]
 2nd Post (n=9):  [75, 43, 23, 98, 87, ., 300, ., 118, 202, 156]
 3rd Post (n=8):  [23, 34, 98, 112, ., 200, ., 156, 54, 18, .]

Comment: If you add reproducible example (or raw data) it would be helpfull.
Comment: The outcome variable is continuous. For example, the results at each time point look similar to this:  Baseline levels n=11: [2, 7, 7, 3, 6, 3, 2, 4, 4, 3, 14].  1st Post n=10 [167, 200, 45, 132, ., 245, 199, 177, 134, 298, 111].  2nd Post n=9 [75, 43, 23, 98, 87, ., 300, ., 118, 202, 156].  3rd Post Level n=8 [23, 34, 98, 112, ., 200, ., 156, 54, 18, .] .   There are four total time points.
Answer: I have re-think your problem and found Friedman's test which is a non-parametric version of a one way ANOVA with repeated measures.
I hope you have some basic skills with R.
# Creating a source data.frame
my.data<-data.frame(value=c(2,7,7,3,6,3,2,4,4,3,14,167,200,45,132,NA,
245,199,177,134,298,111,75,43,23,98,87,NA,300,NA,118,202,156,23,34,98,
112,NA,200,NA,156,54,18,NA),
post.no=rep(c("baseline","post1","post2","post3"), each=11),
ID=rep(c(1:11), times=4))

# you must install this library
library(pgirmess)

Perform test Friedman's test...
friedman.test(my.data$value,my.data$post.no,my.data$ID)

    Friedman rank sum test

data:  my.data$value, my.data$post.no and my.data$ID
Friedman chi-squared = 14.6, df = 3, p-value = 0.002192

and then find between which groups the difference exist by non-parametric post-hoc test.
Here you have all possible comparisons.
friedmanmc(my.data$value,my.data$post.no,my.data$ID)
Multiple comparisons between groups after Friedman test
p.value: 0.05
Comparisons
               obs.dif critical.dif difference
baseline-post1      25     15.97544       TRUE
baseline-post2      21     15.97544       TRUE
baseline-post3      20     15.97544       TRUE
post1-post2          4     15.97544      FALSE
post1-post3          5     15.97544      FALSE
post2-post3          1     15.97544      FALSE

As you can see only baseline (first time point) is statistically different from others.
I hope this will help you.
Comment: Ladislav, this an excellent answer to this question. It is extremely thorough and complete. The only issue I see is that Kruskal-Wallis ANOVA's also have an assumption of independence of observations, such that there are different subjects at each level of the independent variable, which in this case, we do not have as we are following the same 11 patients across 4 time points. Do you have any opinion on this or have any other methods in mind to address this issue? Thanks so much!
Comment: I deleted my comment above. I finally found better test. Enjoy !
Comment: This isn't my original question, @msturm17, will have to accept your answer, I gave you the bounty though!
Comment: Thank you, Ladislav, for taking the time to thoroughly respond to my question!
Answer: If you don't know the distribution of individual changes over time, you cannot approximate it with distribution of between-patient differences.  For example, if you have 10 patient with respective iron levels (510,520,...,600) before treatment and (520,530,...,610) after treatment, the Kruskal-Wallis ANOVA (or any other similar algorithm) would claim that there is no significant change of iron levels.
IMHO, without the control group, the best you can do is to count how many patients increased their iron level and how many decreased it, and test the significance of this.
That said, if the KW ANOVA tells you that there is a significant iron level, it is (no false positives).
Comment: If there are $m$ positives and $n$ negatives, $p = 2^{-(m+n)} \sum_{k=0}^m {m+n \choose k}$
Comment: Yay for no false positives! Haha, thanks for your answer. How do you suggest we "test the significance of this" in regards to counting how many patients increased their iron level and how many decreased it? Thanks!
Comment: Thank you!  This was another interesting way to look at my question and will see how it applies to my data.


Number of six-digit numbers with strictly ascending digits.

Question: How many strictly ascending 6-digit sequences are there, as $024579$ or $135789$, but not $011234$?
I have tried $10\cdot9\cdot8\cdot7\cdot6\cdot5 =151200$, but this is wrong.
Comment: Hint:  every sequence of distinct numbers can be listed in increasing order in exactly one way.
Comment: You start with the least of them, then the second least, up to the greatest.
Comment: To be clear... you used two different words here.  Are you looking for six-digit **numbers** where 024579 is considered a five digit number rather than a six digit number due to the leading zero?  Or are you looking for six-digit **sequences** where leading zeroes are allowed?
Comment: what is that  way
Comment: start with 2-digit numbers to see the pattern
Answer: Here's another hint: such a number is determined entirely by which numbers are present and which ones are absent. So in order to determine one of these numbers, then, out of the $10$ digits that exist, you simply need to choose $6$ to be present (and the remaining $4$ will be absent).
Now can you come up with a guess for how many six-digit numbers with strictly ascending digits there are? Your first guess is likely to be correct.
Answer: choose any of the 6 digits out of these 10 in
$$C_6^{10}$$ways
now you have selected and only have one way to arrange them.
so it is the answer
$$C_6^{10}=210$$
Comment: A more common notation is $\binom{10}{6}$.


how to show the following is euclidean domain...??

Question: Which of the following is Euclidean domain??
1.$Z_{2}[i][x]$
2.$Z_{3}[i][x]$
3.$Z_{5}[i][x]$
4.$Z_{15}[i][x]$
And how to we prove this??
I know the 2 properties of Euclidean domain..except that how we show this?
Comment: $Z_{15}[i][x]$ is not even a domain.
Comment: Anyway, what is the *two properties of Euclid domain* you know? Stating them makes easy to answer your question.
Answer:
The ring $\mathbb{Z}_2[i]$ is not a domain, since $(1 + i)^2 = 0$.
First see that we have the following ring isomorphism: $\mathbb{Z}_3[i] \cong \frac{\mathbb{Z}_3 [y] }{(y^2 + 1)}$ and the polynomial $y^2 + 1$ is irreducible in the ring $\mathbb{Z}_3[y]$ (why?). Thus $\mathbb{Z}_3[i]$ is a field and $\mathbb{Z}_3[i][x]$ is an Euclidean Domain.
The ring $\mathbb{Z}_5[i]$ is not a domain, since $(1 + 2i)(1 - 2i) = 0$.
The ring $\mathbb{Z}_{15}[i]$ is not a domain, since $\mathbb{Z}_{15}$ is not a domain. (this fact is already pointed out by tetori).


Removi todas as TAGs de postagens do Wordpress, mas continua mostrando no Google

Question: Fazendo manutenção de SEO de meu site, apaguei todas as TAGS cadastradas por muitas não serem mais válidas:
Link do Wordpress para edição das tags: wp-admin/edit-tags.php?taxonomy=post_tag
No Yoast SEO, na aba "Taxionimias", na opção Tags (post_tag) marquei como "NÃO" a opção Mostrar Tags nos resultados de pesquisa?.
Mandei o sitemap.xml ao console do Google e até pedi para reindexar o site, mas continua mostrando as "Tags" no resultado de busca, mesmo elas não existindo, o que leva ao usuário uma péssima experiência pois não há nada.
Vejam: O RESULTADO Link da pesquisa no Google com site:meusite.com.br ainda com as tags
Como posso fazer o Google não indexar as "Tags" que, já não existem mais?
PS: Já deu tempo de reindexar e ler o XML, que fazem 4 semanas que removi todas as tags.
Comment: Cara acho que isso pode te ajudar, ou pelo menos te dar uma luz... https://pt.stackoverflow.com/questions/266584/o-google-leva-mais-em-considera%c3%a7%c3%a3o-o-nome-de-view-controller-ou-parametros/266608#266608 de qq forma o Google pode demorar semanas até parar de indexar rotas inexistentes ou mesmo atualizar um conteúdo mostrado na SERP sobre isso talvez essa outra resposta possa te interessar https://pt.stackoverflow.com/questions/383314/indexa%c3%a7%c3%a3o-no-google-tag-h1/383322#383322
Comment: Neste link você obtém mais informações sobre sitemap.
https://resultadosdigitais.com.br/blog/sitemap-xml/ Você deve ajustar para que impeça a indexação, redirecione e liste os novos endereços. No Google Search Console (https://www.google.com/webmasters/tools/home) você pode verificar e solicitar nova indexação.
Answer: Depois de muito pesquisar, a resposta foi criar um bloqueio via bot.

Criei um arquivo Robots.txt com:
Disallow: /tag/
Enviei este arquivo para a raiz do site.
No Console do Google pedi para reindexar o site.

Pronto. Já não mostra as tags.
PS: Lendo a documentação do Google, há o resultado "Pagina 1 -", "Pagina 2 -", mas eles não recomendam bloquear a indexação de "/page/" pois atrapalha a indexação, então isso não é problema.
Por usar o Ubbersugest do Neil Patel, a ferramenta dele diz que é um problema, mas a documentação do Google diz que não deve proibir os "/page/" que pode atrapahar a indexação do site.


I have 2 AUCs from the same data but 2 algorithms. How I determine if one of the AUCs is greater in a statistically significant sense

Question: Problem:
I have 200k data samples which are class imblanced (10% positive class, 90% negative class). I split the data in exactly half so my training set is 100k samples and my test set os 100k samples. I train algorithms A and B.
Algorithm A discriminates between the two classes using the test set and it achieves an AUC of AUC_A. Algorithm B, which is an improvement on A, gets AUC we call AUC_B. I want to determine if AUC_B > AUC_A by chance or not (statistically significant).
What is an algorithm to determine this answer? (say we set p<0.001)
Answer: If you want a p-value you need many values. How about bootstraping the training set? Then you build N models. For each model you make a prediction on the test set. Here the test set stays the same. You get two distribution for the AUC's. These you can check with standard staticial tests. E.g. Welch's test.
Also have a look at this
Comment: Bootstrapping using the training set is unfair.  You would have to do it on the test set.
Comment: Can you explain more what you mean with "unfair"? If you bootstrap the test set, you would will just get the same answer as without bootstrapping, wouldn't you? Let's say `AUC_A < AUC_B`. If you bootstrap the test set and you do enough bootstrapping rounds `N` you will converge to the exact same answer `AUC_A < AUC_B`. Since the p-value depends on the sample size, you would could just choose `N` large enough and get an arbitrary small p-value. Right? Do you think the same happens when sampling the training set? So, what is the point of bootstrapping the test set if you already know the answer?
Answer: I used the wilcoxon ranked sum test to solve the problem.  It is designed to determine if one scoring yields better results than another when the samples are paired.  Additionally, I used the Bonferonni correction since I did multiple comparisons.
I computed many AUCs by using bootstrapping and fed the results to the wilcoxon ranked sum test.
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ranksums.html


How should I play strikethrough notes?

Question: I'm currently practicing Chopin's Ballade No. 1 in G minor. In my Edition at the last page, in the sixth last bar, there are some strikethrough notes:

How should I play them? I have never seen them anywhere else and in other editions I found (for example this one, this one or this one), they are just missing.
Edit: My edition is from Ernst Rudorff and was published in "Friedrich Chopin's Werke. Band I" by Breitkopf und Härtel in 1878. It can also be found at the IMSLP.
Answer: The advice to ignore these marks based on the "first edition" is not well-founded. These marks are present in the autograph. The situation with Chopin is usually quite complex as he was selling his works simultaneously to multiple publishers.
Let's look at how a couple of well-regarded editions handled them.
The Paderewski edition reproduced them in the text. From the critical commentary:

In MS the last three octaves in the treble, as well as in the bass,
  are marked by small oblique lines pointing downwards in the treble,
  upwards in the bass. This signifies that these octaves should be
  played as arpeggios, in the same way as the preceding octaves, but
  more rapidly. FE, GE, and EE do not have these arpeggio signs which
  are, in fact, no longer used.

FE, GE, EE refer to the French, German, and English editions by Schlesinger, Breitkopf and Härtel, and Wessel respectively.
The Henle edition chooses not to reproduce the marks. It says nothing about them in the critical commentary, but adds a footnote on the relevant page of the score giving the notation and saying:

A: Probably an abbreviation for the continuation of the appoggiaturas
  in this measure.

Here A stands for autograph.
Wiener Urtext also reproduces the marks and offers comments on the interpretation, but I don't have access to this edition at the moment.
Answer: Typically a slash is shorthand for playing repeated notes.  One slash thru a quarter note is the same as two eighth notes, two slashes would mean 4 sixteenth, etc. (With digressions for triplet rhythms).
See Dolmetsch under "tremolo" .
edit
Since you point out they aren't in other editions, I'd check each edition to see who the "editor" or "arranger" was.  It's very common for some advisor/musician to put in their interpretations over the original composer's markings.
edit #2
Just quoting comments, as those can be prone to vaporizing.
PatMuchmore says

But those markings wouldn't be in between the two noteheads usually,
they'd be on the stem above the top note or the stem below the bottom
note. Maybe this is just shorthand for continuing the grace note
figures from the previous measure.

And 'replete' points out the Henle edition agrees with that interpretation.
Comment: But those markings wouldn't be in between the two noteheads usually, they'd be on the stem above the top note or the stem below the bottom note. Maybe this is just shorthand for continuing the grace note figures from the previous measure?
Comment: @PatMuchmore  could well be.  No accounting for publisher mistakes.
Comment: @PatMuchmore The editors of the Henle edition agree with you.
Answer: The OP's edition was apparently edited by Ernst_Rudorff.
Chopin has always been a victim of editors (often "famous" pianists who were not famous because of the depth of their musical scholarship) who thought they know better than the composer how the music should be notated and played  (though Rudorff seems to have been a piano teacher, not a performer).
These marks were certainly not in the first edition. Just ignore them. They might possibly mean "play these octaves the same way as the previous ones, notated with grace notes" - but if Chopin had wanted that, he was quite capable of writing it himself. The fact that the octaves with the grace notes that Chopin did write are marked "ritenuto," and those without grace notes are marked "accelerando," is not the sort of detail most "famous pianists" bothered about, if their own whims and fancies about playing the music differed from what the composer actually wrote.
Incidentally, the first of the OP's three links (to a nameless modern engraving of the piece, which looks like it has been produced by modern computer notation software and not "professionally" edited) arbitrarily changes the position of the "accelerando" mark, obliterating the meaning of the comment in the previous paragraph. Don't believe anything done by "some guy on the interweb" unless you can verify it yourself.
Comment: I added some information about my edition in the post.

How should I play strikethrough notes?


Extracting Require information from google map place api in IOS

Question: I am working on GPS app in which i need to determine location based on longitude and Latitude of a place.I am able to determine the longitude and latitude and also location but i am getting the result of the google maps api call in json format in which there is a lot of data along with city name.
I have done like this.(I am using simulator so i have passed fixed latitude and longitude)
NSString *urlString = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",30.819297, 76.444017];
    NSError* error;
        NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
        locationString = [locationString stringByReplacingOccurrencesOfString:@"\"" withString:@""];

    NSLog(@"%@",locationString );

The output string i am getting is
015-04-16 10:38:45.056 demolocationapp[690:12005] {
   results : [
      {
         address_components : [
            {
               long_name : Rauni Kalan Link Road,
               short_name : Rauni Kalan Link Rd,
               types : [ route ]
            },
            {
             **long_name : Rauni Kalan,
               short_name : Rauni Kalan,
               types : [ locality, political]**

            },
            {
               long_name : Rupnagar,
               short_name : Rupnagar,
               types : [ administrative_area_level_2, political ]
            },
            {
               long_name : Punjab,
               short_name : PB,
               types : [ administrative_area_level_1, political ]
            },
            {
               long_name : India,
               short_name : IN,
               types : [ country, political ]
            },
            {
               long_name : 140102,
               short_name : 140102,
               types : [ postal_code ]
            }
         ],
         formatted_address : Rauni Kalan Link Road, Rauni Kalan, Punjab 140102, India,
         geometry : {
            bounds : {
               northeast : {
                  lat : 30.8209903,
                  lng : 76.4550081
               },
               southwest : {
                  lat : 30.8178417,
                  lng : 76.44540219999999
               }
            },
            location : {
               lat : 30.8186057,
               lng : 76.4507395
            },
            location_type : APPROXIMATE,
            viewport : {
               northeast : {
                  lat : 30.8209903,
                  lng : 76.4550081
               },
               southwest : {
                  lat : 30.8178417,
                  lng : 76.44540219999999
               }
            }
         },
         place_id : ChIJc8IoHwICEDkR38Ie5TOeGu0,
         types : [ route ]
      },
      {
         address_components : [
            {
               long_name : Rauni Kalan,
               short_name : Rauni Kalan,
               types : [ locality, political ]
            },
            {
               long_name : Rupnagar,
               short_name : Rupnagar,
               types : [ administrative_area_level_2, political ]
            },
            {
               long_name : Punjab,
               short_name : PB,
               types : [ administrative_area_level_1, political ]
            },
            {
               long_name : India,
               short_name : IN,
               types : [ country, political ]
            },
            {
               long_name : 140102,
               short_name : 140102,
               types : [ postal_code ]
            }
         ],
         formatted_address : Rauni Kalan, Punjab 140102, India,
         geometry : {
            bounds : {
               northeast : {
                  lat : 30.8219531,
                  lng : 76.4462614
               },
               southwest : {
                  lat : 30.81705139999999,
                  lng : 76.4414979
               }
            },
            location : {
               lat : 30.8192965,
               lng : 76.44401660000001
            },
            location_type : APPROXIMATE,
            viewport : {
               northeast : {
                  lat : 30.8219531,
                  lng : 76.4462614
               },
               southwest : {
                  lat : 30.81705139999999,
                  lng : 76.4414979
               }
            }
         },
         place_id : ChIJ_f1PWh0CEDkRKlzFwhc62zo,
         types : [ locality, political ]
      },
      {
         address_components : [
            {
               long_name : 140102,
               short_name : 140102,
               types : [ postal_code ]
            },
            {
               long_name : Punjab,
               short_name : PB,
               types : [ administrative_area_level_1, political ]
            },
            {
               long_name : India,
               short_name : IN,
               types : [ country, political ]
            }
         ],
         formatted_address : Punjab 140102, India,
         geometry : {
            bounds : {
               northeast : {
                  lat : 30.869706,
                  lng : 76.47508049999999
               },
               southwest : {
                  lat : 30.7970006,
                  lng : 76.3335855
               }
            },
            location : {
               lat : 30.8288892,
               lng : 76.4215988
            },
            location_type : APPROXIMATE,
            viewport : {
               northeast : {
                  lat : 30.869706,
                  lng : 76.47508049999999
               },
               southwest : {
                  lat : 30.7970006,
                  lng : 76.3335855
               }
            }
         },
         place_id : ChIJHX2_rA0BEDkR_QslHcc_M0g,
         types : [ postal_code ]
      },
      {
         address_components : [
            {
               long_name : Fatehgarh Sahib,
               short_name : Fatehgarh Sahib,
               types : [ administrative_area_level_2, political ]
            },
            {
               long_name : Punjab,
               short_name : PB,
               types : [ administrative_area_level_1, political ]
            },
            {
               long_name : India,
               short_name : IN,
               types : [ country, political ]
            }
         ],
         formatted_address : Fatehgarh Sahib, Punjab, India,
         geometry : {
            bounds : {
               northeast : {
                  lat : 30.8779699,
                  lng : 76.63427999999999
               },
               southwest : {
                  lat : 30.4275501,
                  lng : 76.0761799
               }
            },
            location : {
               lat : 30.6810924,
               lng : 76.4100267
            },
            location_type : APPROXIMATE,
            viewport : {
               northeast : {
                  lat : 30.8779699,
                  lng : 76.63427999999999
               },
               southwest : {
                  lat : 30.4275501,
                  lng : 76.0761799
               }
            }
         },
         place_id : ChIJqf6CHWocEDkR4EljDGd5be8,
         types : [ administrative_area_level_2, political ]
      },
      {
         address_components : [
            {
               long_name : Punjab,
               short_name : PB,
               types : [ administrative_area_level_1, political ]
            },
            {
               long_name : India,
               short_name : IN,
               types : [ country, political ]
            }
         ],
         formatted_address : Punjab, India,
         geometry : {
            bounds : {
               northeast : {
                  lat : 32.4981352,
                  lng : 76.92175809999999
               },
               southwest : {
                  lat : 29.537147,
                  lng : 73.8708879
               }
            },
            location : {
               lat : 31.1471305,
               lng : 75.34121789999999
            },
            location_type : APPROXIMATE,
            viewport : {
               northeast : {
                  lat : 32.4981352,
                  lng : 76.92175809999999
               },
               southwest : {
                  lat : 29.537147,
                  lng : 73.8708879
               }
            }
         },
         place_id : ChIJVXOeVqpkGTkRYYijAzEmvY8,
         types : [ administrative_area_level_1, political ]
      },
      {
         address_components : [
            {
               long_name : India,
               short_name : IN,
               types : [ country, political ]
            }
         ],
         formatted_address : India,
         geometry : {
            bounds : {
               northeast : {
                  lat : 35.5087008,
                  lng : 97.395561
               },
               southwest : {
                  lat : 6.7535159,
                  lng : 68.162386
               }
            },
            location : {
               lat : 20.593684,
               lng : 78.96288
            },
            location_type : APPROXIMATE,
            viewport : {
               northeast : {
                  lat : 35.5087008,
                  lng : 97.395561
               },
               southwest : {
                  lat : 6.7535159,
                  lng : 68.16288519999999
               }
            }
         },
         place_id : ChIJkbeSa_BfYzARphNChaFPjNc,
         types : [ country, political ]
      }
   ],
   status : OK
}

I have put my Required data where type is locality,political in **Required Text **
How can i get that
Answer: Used this method
 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat: @"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",30.819297, 76.444017]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (!error)
    {
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

             NSArray *arr=[[json valueForKeyPath:@"results.address_components"] objectAtIndex:0];

        for (NSDictionary *dictAddress in arr)
        {
            if ([[dictAddress objectForKey:@"types"] count] > 0)
            {
                if([[[dictAddress objectForKey:@"types"] objectAtIndex:0] isEqualToString:@"locality"])
                {
                    return [dictAddress objectForKey:@"long_name"];
                }
                else if([[[dictAddress objectForKey:@"types"] objectAtIndex:0] isEqualToString:@"political"])
                {
                    return [dictAddress objectForKey:@"long_name"];
                }
            }
            else
            {
                return @"";
            }
        }
        return @"";
        }
    }
}];

Using this method you will find the name of the area which type start with "locality" or "political".
But i have took first object of the api response but if you need rathar than this , then put loop to take object of the json called.
Hope this will helps you.
Answer: You need to convert your string of the JSON object to an NSDictionary and then use key/value accessors to get each field.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat: @"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",30.819297, 76.444017]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (!error)
    {
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        NSArray *results = [json valueForKey:@"results"];
        for (NSDictionary *result in results)
        {
            NSLog(@"%@", [result valueForKey:@"formatted_address"]);
            NSLog(@"%@", [result valueForKey:@"place_id"]);
            // Etc...
        }
    }
}];

Answer: First off, I would use NSURLSessions and blocks to make network calls. The beauty of blocks is that if my network connection is poor my block will only get executed at after the call returns.
Then you need to convert your JSON to foundation objects that you can work with.
NSString *urlString = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",30.819297,76.444017];
NSURL *url = [NSURL URLWithString:urlString];

//Next we need a NSURLSession instance
NSURLSession *session = [NSURLSession sharedSession];

//All tasks (there are three, see documentation) are created from an NSURLSession instance
//We want a DataTask
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    //This "block" (of code) will be executed when the call is complete

    //Serialize the JSON to Foundation objects
    NSDictionary *geocodeDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    //Parse through the JSON to get to where we want, address_components array
    NSArray *resultsArray = geocodeDictionary[@"results"];
    NSDictionary *resultsDictionary = resultsArray[0];
    NSArray *addressComponents = resultsDictionary[@"address_components"];

    //Declare variables to hold desired results
    NSString *longName;
    NSString *shortName;

    //The address_components array contains many dictionaries,
    //we loop through each dictionary and check the types array
    for (NSDictionary *addressComponentDictionary in addressComponents) {
        NSArray *typesArray = addressComponentDictionary[@"types"];

        if (    [typesArray[0] isEqualToString:@"locality"]
             && [typesArray[1] isEqualToString:@"political"]) {
            //the type IS locality and political
            longName = addressComponentDictionary[@"long_name"];
            shortName = addressComponentDictionary[@"short_name"];
        }
    }

    //Test log to see we are correct
    NSLog(@"%@", longName);
    NSLog(@"%@", shortName);
}];

[dataTask resume];


I am trying to find the original index value of the last occurence of each group

Question: I am trying to find the original indices for the last occurrence of groupby groups.
If I have the dataframe given by:
data = {
    'Name':['Jack', 'Jill', 'Jill', 'Jill', 'Ryan',
            'Ryan','Lilian', 'Jack', 'Jack', 'Jack'],
    'Age': [15, 20, 25, 30, 23, 23, 45, 24, 65, 115]
}

df = pd.DataFrame(data)

df

I hope to see:
0 Jack 15
3 Jill 30
5 Ryan 23
6 Lilian 45
9 Jack 115

Tried using groupby and .last() after the groupby but this gets rid of the index.
Answer: If you want to drop duplicates not considering the records which appear latter as a dupe(i think the expected output before editing), you can also do:
(df.assign(k=df['Name'].ne(df['Name'].shift()).cumsum())
  .drop_duplicates(['Name','k'],keep='last'))

Or better as @PiR mentions:
df[df.Name.ne(df.Name.shift(-1))]

     Name  Age  k
0    Jack   15  1
3    Jill   30  2
5    Ryan   23  3
6  Lilian   45  4
9    Jack  115  5

Comment: `df[df.Name.ne(df.Name.shift(-1))]` is so concise and pretty
Answer: Can also
df.groupby(df.Name.ne(df.Name.shift()).cumsum()).tail(1)

     Name  Age
0    Jack   15
3    Jill   30
5    Ryan   23
6  Lilian   45
9    Jack  115

Answer: Use duplicated:
print(df[~df.Name.ne(df.Name.shift()).cumsum().duplicated(keep='last')])

Output
     Name  Age
0    Jack   15
3    Jill   30
5    Ryan   23
6  Lilian   45
9    Jack  115


Does using MongoDB for field storage limit functionality?

Question: I am considering using MongoDB on a site for field storage, and not just moving cache, session, lots, etc., out of my SQL database.
The Field Storage API should make this seamless, assuming I am using the Drupal API for accessing data.  But, does this limit my site in any way.  In particular, I am wondering how Views will be affected.
Comment: I think this can be rewritten to give it focus, and be a good fit fot the site.
Comment: This will most likely get closed down as being too broad, however; the only thing that has kept me away from MongoDB is that fact that I would lose Views' relationships functionality for fields stored using MongoDB. I am concerned that one day I'll need it and BANG - none of the queries can be `JOIN`ed.
Comment: That is one of the things that came to mind.
Comment: @Chapabu You can mitigate that with [Mongodb](https://drupal.org/project/mongodb) and [EFQ Views Backend](https://drupal.org/project/efq_views)
Comment: @Clive Are you sure? I was sure I read somewhere that this was not the case? I've never had the time to try it - so I can't 100% say either way. If it works then hell, I can't see any reason not to use it :-)
Comment: *"NO RELATIONSHIPS WHATSOEVER. EFQ Views do not support relationships because Mongo doesn't support JOINs."* - Under the *Converting the Views* section on [this post](http://drupalconnect.com/blog/converting-existing-drupal-site-mongodb). (Just to clarify, I'm not being argumentative, I'm genuinely curious)
Comment: @Chapabu Yeah you're right, I hadn't thought that through properly
Comment: Took a pass at a rewrite.  I think this is an important question.
Comment: @MPD Cheers! I think this is actually a very valuable question, so thanks for the edit :-)
Comment: Thanks for the edit, I think some of the input here could be some great indexed discussion for lots of people to push them over to make the leap or proceed with caution.
Answer: its a cool question.
Im on my 5 week adventure of playing around with Drupal 7 and mongo,
However as Cahpabu stated and quoted.

NO RELATIONSHIPS WHATSOEVER. EFQ Views do not support relationships
  because Mongo doesn't support JOINs." - Under the Converting the Views
  section on this post. (Just to clarify, I'm not being argumentative,
  I'm genuinely curious) – Chapabu Sep 6 at 15:57

I think you can do a lot using mongo with Drupal, moving a lot of other stuff into mongo, like sessions, etc. simple "fields" however :
Since Views is extremly limited with Mongo db. I found out that its better(and much more timeconsuming) to rewrite some custom modules fitting into the schema of mongo.
So its for sure, a great adventure if your starting up a new project/site. But the adventure will be filled with great challenges down mystery lane.
Even the Whitehouse had to go back to Mysql from mongo.
here is a quote I found on it.

"The current release depends on MongoDB. When we first created the
  application, we wanted to make sure we had a highly scalable
  application and database to meet our anticipated performance needs
  under high loads. We have been running MongoDB in production for over
  a year, but we have decided that the performance benefits it provides
  are outweighed by the complexity of trying to extend Drupal features
  backed by MongoDB."

However other people had great succes with mongodb and Drupal 8
Mongodb and Drupal 8

As they state in their slide, To achieve full mongodb functionality is
  of course impossible.

But you will have to give up several modules using SQL, (which is a lot) For now, I still have the feeling that Drupal cant dance a full tango with Mongo. Even using the modules. its still a rough way.
Comment: Thanks for sharing your thoughts on this!  It's appreciated!


specifying favicon in a type-safe manner in yesod

Question: this is a re-post of my original question that I asked on the yesod mailing list (please see http://groups.google.com/group/yesodweb/browse_thread/thread/934c4141fc615cb) in an attempt to get a faster response.
I am trying to figure out whether it is possible to generate a <link> with the type attribute that corresponds to the MIME type sent by the HTTP handler that serves the favicon file.
so far I have this link:

<link rel="icon" href=@{FaviconR} sizes="32x32" type="image/png">

and this handler:

getFaviconR :: Handler ()
getFaviconR = sendFile "image/png" "config/favicon.png"

I am looking for a way to make sure that the code compiles only if getFaviconR and <link> have the same MIME type.
I realize of course that I can omit type attribute from the link altogether and rely on the client to figure out the type, but think of it as a theoretical question.
I am new to Haskell, so may be I am asking for something impossible. no?
Comment: Not very familiar with Yesod. Is it possible to write something like `` and have the template for `Favicon` generate both the `href="foo"` and `type="image/png"` bits? Then at least both `"image/png"` bits are in one place.
Answer: I think the easiest thing to do here is to define the image type in a separate variable and use it in both places.


View the original price, the discounted price and the discount percentage

Question: I am currently working on a newsletter and I want to display the prices of my products there. How to recover the original price, discounted prices and the discount percentage. I wish to put three different value to place my letter and apply a different style.
With this line print render($content['product:commerce_price']);
it displays the three values. But I would separate them.
So what line of code do I type to get the original price, then to get the discounted price and then to get the discount percentage?
here is a product page of my site enter link description here
thank you
Comment: I need to separate the three, to display prices in simplenews
Comment: there is no solution ?
Answer: If this is Drupal 7, you can use the Commerce Price Savings Formatter.  This extends the price field to show the "list price" and "sale price" and automatically calculates the percentage.
The module page links to a video explaining how to use the module.


Errors while Running the ZXING library in Eclipse

Question: I'm trying to run ZXING library on my windows PC. I'm using Eclipse IDE. But when I open the project file in my eclipse it's showing me different errors(As shown in the this image

Although I'm following all the steps mentioned in this link Getting Started with ZXing but when I try to build android it failed as shown in this image:

I need to deliver the project to my client. Please help or is there anyother barcode reader (I need UPC reader) library for Android available.
Answer: This is not an issue with zxing. You don't appear to understand how to use Eclipse, as you have not actually added zxing libraries to your project. I think you would need to take some time to get used to your IDE.
The second error is because Windows is not supported by the Proguard optimizer. Best is to get access to a Mac or Linux-based machine, since you do want to run the optimizer.
Answer: The zxing getting started is a bit confusing at times. Its not as easy as it seems to get started immediately. I faced similar issues and created a project for making it easy for the rest of the folks to follow.
Download http://www.4shared.com/file/bFx8Y5Ys/zXingJune2010.html. Let me know if you can not get it working.


RegEx for 301 redirects to change path AND remove a string

Question: I am looking for an RegEX redirect rule to redirect the image file locations to a new location, whilst also removing part of the original url which is the name of the image
OLD URL:
<code>/components/com_mijoshop/opencart/image/cache/catalog/ecom2/GM815-365x365.jpg
</code>
NEW URL:
<code>/wp-content/uploads/nc/catalog/ecom2/GM815.jpg
</code>
So I need to change the directory path AND remove the '-365x365' part of the url.
I can remove the part of the image name with the following, but unsure how to also change the path:
<code>/(?'path'.*)-365x365.jpg  /[path].jpg
</code>
Comment: What is the environment where you are using the regex?
Comment: It's Wordpress, a redirect plugin. We migrated from a really old Joomla site and we have thousands of image urls that have changed that I would like to put 301s on.
Comment: Please add link to the plugin to the question, so that we can check the documentation. Without seeing documentation, an answer cannot be given.
Comment: Please see link to the plugin documentation.  If you could help it would be very much appreciated.

https://docs.wp301redirects.com/article/307-regex-redirects-recipes
Answer: You can try this:
<code>/components/com_mijoshop/opencart/image/cache/(?'path'.*)-365x365.jpg /wp-content/uploads/nc/[path].jpg
</code>
Comment: Thanks so much, that worked perfectly!


How is the identity mapping from $\Bbb{R_\ell}\to\Bbb{R}$ continuous?

Question: Munkres' book on Topology (Pg 122 of the Second edition) says

The identity mapping $f:\Bbb{R_\ell}\to\Bbb{R}$ defined by $f(x)=x$ (identity mapping) is continuous

I don't understand how. An open set in $\Bbb{R}$ would be of the form $(a,b)$. $f^{-1}(a,b)=(a,b)$, as it is an identity mapping. But $(a,b)$ is not an open set in $\Bbb{R_\ell}$. How is $f$ a continuous mapping then?
Thanks in advance!
Comment: $(a,b)=\bigcup\limits_{a<c<b}[c,b)$ is a union of open sets hence open in $\Bbb R_\ell$.
Comment: Why is $(a,b)$ not open in $\mathbb{R}_{l}$. $\mathbb{R}_{l}$ is strictly finer than $\mathbb{R}$.
Comment: @Tian- I just got why that is. It's a pretty neat argument!
Answer: Hint: What is $\bigcup_{n=1}^\infty [a + \frac{1}{n} , b )$?


Why is the SS(A|B) larger than SS(A) in anova analysis

Question: **Analysis 1**
Code: anova(lm(y~A+B))
Result:
Analysis of Variance Table

Response: y
              Df Sum Sq Mean Sq F value    Pr(>F)
          A   1  40.58  40.583  214.11 < 2.2e-16 ***
          B   4 171.31  42.829  225.96 < 2.2e-16 ***
Residuals       1994 377.94   0.190

**Analysis 2**
Code: anova(lm(y~B+A))
Result:
Analysis of Variance Table

Response: y
               Df Sum Sq Mean Sq F value    Pr(>F)
          B    4  87.10  21.774  114.88 < 2.2e-16 ***
          A    1 124.80 124.800  658.43 < 2.2e-16 ***
Residuals        1994 377.94   0.190

From analysis 1, SS(A) = 40.58, while from analysis 2, SS(A|B) = 124.80, which is larger than SS(A) from analysis 1. If I want to evaluate the effect of A after excluding the effect of B, I should use analysis 2. However, in analysis 2, I get a larger SS(A|B) and F value than SS(A) and F value obtained from analysis 1. From my understanding, SS(A|B) should always be smaller than SS(A) since the variance accounted by B has been taken away. This leads to the conclusion that after accounting for the effect of B, I get a more significant A effect, which makes me confused.
Comment: @MichaelM, you are welcome to edit my answer to explain why this must be the case. I think it would make for a better answer and I am not confident in my intuition to do it myself.
Comment: A and B are not independent!
Comment: Thanks for the nice answer.
Answer: I screwed around in R and managed to get a similar phenomenon with the following code.
set.seed(0)
X = list()
X$a = rnorm(50)
X$y = rnorm(50)
X$b = with(X, 10*a + y) + rnorm(50)
anova(lm(y~a+b, X))
anova(lm(y~b+a, X))
X$lp = with(X, b - 10*a)
pairs(X)

Here's my read. There's one scenario in which A and B are correlated and correcting for B leaves less association between A and y. This is often taught and it seems to be what you had in mind. But, there's another possible scenario which seems to be applicable here: what if A and B are not very useful individually, but are very useful jointly? Then whatever gets added to the model second gives a big leap in the explanatory power of the model. You can see in the last line of code that the linear predictor $b-10a$ (lp) explains $y$ far better than $a$ or $b$ alone.
As Michael M notes, this example does not leave $a$ and $b$ dependent.
Comment: Interestingly, the causal graph implied by this example has y and a causing b, not and and b causing y.
Comment: Is that possible to plot a Venn graph to illustrate this? Just as what was did in figure 2 from this article https://digitalcommons.wayne.edu/cgi/viewcontent.cgi?article=1860&context=jmasm
Comment: The intuition of this question is to examine the effect of b while controlling the effect of covariate a. Can I understand the big leap in value of SS(b|a) as the true effect of b on y? [In my case, a and b are not that highly correlated]
Comment: Causal interpretation is difficult, but it seems like there's a clear signal in your data that both A and B contain useful signal for predicting Y. If I were to draw a diagram to represent partitioning of variance, I would show two different panels. Both would have the total variance of Y as the full area. Both would show, within that, the variance explained by a linear model containing A and B. Up to that point, both panels would look the same. But within the inside compartment, the left panel would show a smaller area for the variance explained by a linear model containing only A.
Comment: ... the right would show the variance explained by a linear model containing only B.


Help with Web forms

Question: I would like to create a simple form that allows a teacher to enter the individual names of their pupils.
I would then like to create another form that returns the individual names of the pupils one at a time and allows the teacher to input a score next to the name.
is there a module that would allow me to do this
Comment: OK maybe I was a bit hasty closing this...it would be better if you could add a lot more detail to your question though, no-one's going to do _all_ of the work for you - you need to give us something to go on, let us know that you've actually tried to solve the problem yourself, and how, etc
Answer: drupal itself provide a module "webform" for manipulating webform
before you use module just go through readme.txt for better understanding
just download the module :)
Answer: alternatively Entity Form
I find this one more powerful out of box, however it all depends on what exactly you would like to achieve.

Help with Web forms


Applying IO [a -> b] to single parameter of type a

Question: I have
functions :: IO[a -> b]   -- IO List of functions
param :: IO[a]            -- Single parameter

and I want to get
result :: IO[b]
result = IO[*first function* <$> param, *second function* <$> param, ...]

I somehow could get result of type IO[IO b], but I want IO[b]
Answer: By "single parameter" I assume you mean a one element list. If so, then here's how it's done:
result :: IO [b]
result = do
    fs <- functions    -- fs :: [a -> b]
    xs <- param        -- xs :: [a]
    let ys = fs <*> xs -- ys :: [b]
    return ys

Note that since xs is a one element list you're essentially applying every element of fs to that value.
This is the same as:
import Control.Applicative (liftA2)

result :: IO [b]
result = liftA2 (<*>) functions param

Hope that helps.
Comment: `liftA2 (<*>)` is `(<*>)` for `Compose`, so you can write `result = getCompose $ Compose functions <*> Compose param`. If this pattern is used widely, It might be better to wrap everything in `Compose` (e.g `param : Compose IO [] a` and `result : Compose IO [] b`), then it's simply `result = functions <*> params`.
Answer: This looks very much like a simple <*>, but we need to call it... deeply. Can we do this using only the Applicative instance, without resorting to Monad?
Solving a simpler problem first:
functions :: IO (a -> b)
param     :: IO a

We could use:
functions <*> param

To get an IO b.
Similarly, given a list of functions and a list of values:
functions :: [a -> b]
param     :: [a]

We could use:
functions <*> param

To get a [b].
But now to do both at the same time:
functions :: IO [a -> b]
param     :: IO [a]

This is... trickier, because we'll have to take advantage of the Applicative instance for IO and the Applicative instance for [] at the same time. But it's still doable:
doubleAp fns x = liftedFns <*> x
  where apList = (<*>) :: [a -> b] -> [a] -> [b]
        liftedFns = fmap apList fns :: IO ([a] -> [b])

Or the more concise but harder (for me) to parse:
doubleAp fns x = ((<*>) <$> fns) <*> x

Or, according to blunt:
doublAp = (<*>) . ((<*>) <$>)

Comment: You could simply do `liftA2 (<*>) functions param`.
Comment: @AaditMShah That's a lot nicer!
Answer: sequence will get you from [IO b] to IO [b], join will get you from IO (IO [b]) to IO [b].


Bootstrap subtheme does not recognize stylesheets

Question: I'm trying to use a custom (LESS) build of Bootstrap in my Drupal project. I have a subtheme in the proper folder and have compiled a style.css file. However, Drupal does not recognize this file. So far I have

Edited the .info file to switch of the CDN and switch on the local .js files
Cleared the cache
Switched off the aggregation of CSS
Restarted the server
Added a foo.css to the .info file for testing

Nothing of this works. The subtheme does not recognize my custom css files.
What could have gone wrong here?
Comment: does the subtheme otherwise work? can you post the .info file for both the main and sub-theme, and the most painfully obvious question - have you enabled the subtheme and set it active (default perhaps)?
Answer: I forgot to turn the subtheme on in the theme settings.


Flutter: How to add many fields in firestore using one document without overwriting

Question: I'm having a problem on my project right now. I know, many already posted this issue but I really dont know how to implement it in my code. I want to do is, to add multiple data in firestore fields using one document. In the fields, have a field name "Issue" and inside "Issue" I have many data in it. Everytime I add a new data in that document, it overwrites the data in the field. How to add the data without overwriting, please help.
Here is my code:
<code>_saveIssueToActivities(dynamic data) async {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final FirebaseUser user = await _firebaseAuth.currentUser();
try {
  DocumentReference ref = db.collection('ACTIVITIES').document(user.uid);
  return ref.setData({
  'Issue': {
    'User_ID': '',
    'Name_ofUser': '${data['Name_ofUser']}',
    'Help_Description': '${data['Help_Description']}',
    'Help_DatePosted:': '',
    'Help_Location': '',
    'Help_TypeNeeded': '${data['Help_TypeNeeded']}',
    'Help_NotificationID': '',
  }
  });
} catch (e) {
  print(e);
}
</code>
}
Here is my Database Structure:
Link to my db pic
Comment: You tried the merge: true optional parameter in the setData method?
Comment: yes sir marc, but it overwrites the old data, it wont add a new "Issue" :(
Answer: Try with:
<code>Future<dynamic> addDataToFirestore(dynamic data) async {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final FirebaseUser user = await _firebaseAuth.currentUser();
DocumentReference ref = db.collection('ACTIVITIES').document(user.uid);
dynamic datatoSubmit = [{
    'User_ID': '',
    'Name_ofUser': '${data['Name_ofUser']}',
    'Help_Description': '${data['Help_Description']}',
    'Help_DatePosted:': '',
    'Help_Location': '',
    'Help_TypeNeeded': '${data['Help_TypeNeeded']}',
    'Help_NotificationID': ''
}];
   //Do some debugging with the datatypes or which type of data you have in the firebase document.

await ref.updateData({'Issue': FieldValue.arrayUnion(datatoSubmit)});

}

Or

Future<dynamic> addDataToFirestore(dynamic data) async {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final FirebaseUser user = await _firebaseAuth.currentUser();
DocumentReference ref = db.collection('ACTIVITIES').document(user.uid);
dynamic datatoSubmit = {
    'User_ID': '',
    'Name_ofUser': '${data['Name_ofUser']}',
    'Help_Description': '${data['Help_Description']}',
    'Help_DatePosted:': '',
    'Help_Location': '',
    'Help_TypeNeeded': '${data['Help_TypeNeeded']}',
    'Help_NotificationID': ''
};
   //Do some debugging with the datatypes or which type of data you have in the firebase document.

await ref.updateData({'Issue': FieldValue.arrayUnion(datatoSubmit)});

}

</code>
Here is my result with the 2nd one example :
Comment: Change your firebase Issue field data type to Array. So every time when you push it will add a new entry of data. or can you paste the output error here?
Comment: Still the same sir, this was the  message: I/flutter (11998): type '_InternalLinkedHashMap' is not a subtype of type 'List'
Comment: Wrap the data you are sending to the firebase to a list. I have updated the code. As I mentioned in the comment debug the datatype. The issue is with the data type you are using in firebase and the data you are updating to firebase both are different.  This code is quite working fine for me.
Comment: Yeey it worked sir, but the problem  is if I have an empty document "updateData" wont work @@ first I need to use "setData" then "updataData" so that it will add a new one @@ how will I set a condition if the document is empty use setData but if not updateData @@ please help.


Activity class does not exist android

Question: I am trying to debug my application and upon clicking the button i get the Activity Class {} does not exist error which reads like so: "Error: Activity class {sprint.telematics.sprinttelematicstracking/track.my.world.LoginActivity} does not exist."
The problem is not with the "track.my.world" package name as this does exist but the section before the forward slash:"sprint.telematics.sprinttelematicstracking" as there is no longer anything in the application named this.
I have transferred my project from Eclipse to Android Studio and also changed the package name from "sprint.telematics.sprinttelematicstracking" to "track.my.world" and this is when the error started to occur. My android manifest file contains the correct package as shown.
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="track.my.world"
android:versionCode="1"
android:versionName="1.0" >

<application
    android:allowBackup="true"
    android:icon="@drawable/trackmyworldicon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
        android:name="track.my.world.LoginActivity"
        android:label="@string/app_name">

        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>

How would i be able to change where android studio is looking to launch the app from as i think it is looking in the wrong area for the LoginActivity
Thanks
My build.gradle file:
buildscript {
    repositories {
        maven { url 'http://download.crashlytics.com/maven' }
    }

    dependencies {
        classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+'
    }
}
apply plugin: 'android'
apply plugin: 'crashlytics'

repositories {
    maven { url 'http://download.crashlytics.com/maven' }
}

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile project(':google-play-services_lib')
    compile project(':google-play-services_lib')
    compile 'com.crashlytics.android:crashlytics:1.+'
}

android {
    compileSdkVersion 18
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "track.my.world"
        minSdkVersion 10
        targetSdkVersion 18
        versionCode 1
        versionName "1.0"
    }

    sourceSets {
        main {
             manifest.srcFile 'AndroidManifest.xml'
             java.srcDirs = ['srcc']
             resources.srcDirs = ['srcc']
             aidl.srcDirs = ['srcc']
             renderscript.srcDirs = ['srcc']
             res.srcDirs = ['res']
             assets.srcDirs = ['assets']
        }

        instrumentTest.setRoot('tests')

        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}

Comment: hmmm i think you should move to https://www.eclipse.org/
Comment: Are you sure you don't have any imports in any of your class files for sprint.telematics.sprinttelematicstracking ? Also check none of your class files have `package sprint.telematics.sprinttelematicstracking` in them.
Comment: . I started work on a Windows PC using Eclipse before switching to a Mac with Android Studio on it. Didnt think it would have caused much of an issue?
Comment: I would make yourself sure that all of your classes are titled with the correct package name.
Comment: I have used a search to find anything by the name of sprint and found nothing out of the ordinary. All layout files use the correct context and all classes use the "track.my.world" package
Answer: Did you migrate your project to gradle?
In that case look at the build.gradle file for the packageName. Gradle will override the package name in the androidManifest.xml during the build of the app.
android {
    compileSdkVersion 19
    buildToolsVersion "19.1.0"

    defaultConfig {
        packageName "com.your.app"
        minSdkVersion 14
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
}

Comment: in build.gradle i dont have a defualtConfig i do have sourceSets though?
Comment: This did change what i was looking for however it did not fix my problem. I created a new app and moved the classes, resources and libraries over which fixed the problem. Must be an error within the build files, as suggested, which i cannot find a solution to
Comment: Ive added it to my question above userM143372
Answer: Take a look through some of the build files for the Eclipse project. It appears to have gotten confused and you can just do a "find" function in the main build file and you will probably find "sprint.telematics.sprinttelematicstracking" and then just get rid of it or change the line accordingly.
Comment: I will have a look through the files again but i cant seem to see anything that stands out as wrong. Very annoying
Comment: Hm ok, be sure to let me know

Activity class does not exist android


upload com ajax e formdata exibe erro

Question: Estou tentando enviar um arquivo para o servidor com ajax e php. Já tentei variações com o pessoal que tinha dúvida no mesmo assunto mas nada dá certo (tenho certeza que estou fazendo alguma besteira). Eu tenho um form com 4 campos, sendo um deles do tipo file. Faço toda a validação e na hora de enviar aparece o erro: "SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data".
No form já coloquei o atributo "enctype="multipart/form-data".
Meu script está assim:
$("#formAgendaConsulta1").validate({
    // Define as regras
    unkeyup: false,
    rules:{
        arqup:{
            required: true
        },
        especialidade:{
            required: true
        },
        especialista:{
            required: true
        },
        dataConsulta:{
            required:true,
            dateBR:true
        },
        horaConsulta:{
            required:true,
            timeBR:true
        }
    },
    // Define as mensagens de erro para cada regra
    messages:{
        arqup:{
            required: "Você deve selecionar o arquivo"
        },
        especialidade:{
            required: "Preenchimento obrigatório"
        },
        especialista:{
            required: "Preenchimento obrigatório"
        },
        dataConsulta:{
            required: "Preenchimento obrigatório", dateBR: "Data inválida"
        },
        horaConsulta:{
            required: "Preenchimento obrigatório", timeBR: "Horário inválido"
        }
    },
    submitHandler: function( form ){
        //var dados = $( form ).serialize();
        //dados.append('arqup', $('input[type=file]')[0].files[0] );
        var dados = new FormData( document.querySelector('form') );
        //formData.append('arqup', $("input[name='arqup']").prop('files')[0]);
        //formData.append('horaConsulta', $("input[name='horaConsulta']").val());
        dados.append( 'especialidade', $("#especialidade").val() );
        dados.append( 'dataConsulta', $("#dataConsulta").val() );
        dados.append( 'horaConsulta', $("#horaConsulta").val() );
        dados.append('imagem', $('input[type=file]')[0].files[0] );
        console.log( dados );
        $.ajax({
            type: "POST",
            url: $( form ).attr('action'), // "saveAgendaConsulta1.php",
            data: dados,
            processData: false,
            contentType: false,
            dataType: "json",
            xhr: function () {
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    myXhr.upload.addEventListener('progress', function (s) {
                        console.log('PROGRESSO', s);
                    }, false);
                }
                return myXhr;
            },
            success: function( data ){ // Executa a função se a requisição funcionar
                var msgFinal = data.msgFinal;
                $('#resultAgendaConsulta1').html( msgFinal );
                $('#resultAgendaConsulta1').show( 'slow' );
                // rolar a tela até o elemento
                //$('#cxAgendaConsulta1').animate({ scrollTop: $('#resultAgendaConsulta1').offset().top }, 'slow');
            },
            beforeSend: function(){ // Executa a função assim que a requisição for enviada
                $('#loadAgendaConsulta1').css({display:"block"});
            },
            complete: function(msg){ // Executa a função sempre que a requisição for executada
                $('#loadAgendaConsulta1').css({display:"none"});
            },
            error: function(){
                bootbox.alert("Falha de Conexão!
Não foi possível efetuar sua requisição.
Aguarde alguns instantes e faça uma nova tentativa.");
            }
        });
        return false;
    }
});

Answer: O envio e recepção de dados em AJAX é geralmente feito utilizando strings e você está enviando os dados como object, utilize a função JSON.stringify() para converter os dados antes de fazer o envio.
// ...
$.ajax({
    type: "POST",
    url: $( form ).attr('action'), // "saveAgendaConsulta1.php",
    data: JSON.stringify(dados),
    // ...
    });

Na recepção você precisará usar a JSON.parse() para conversão do JSON recebido (string) para um objeto do JavaScript; exceto se você estiver usando jQuery e aí é possível fazê-lo diretamente com $.getJSON().
Comment: Giovanni fiz como vc disse mas continua o mesmo erro. No debug do navegador, em params, exibe apenas a palavra 'JSON' (acredito que não veio nenhuma string) e em response exibe o erro já mencionado.
Comment: Uma coisa que esqueci, coloque `contentType: 'application/json; charset=utf-8'`para avisar à outra ponta que você está enviando um JSON, talvez resolva. E como você usa o **FormData** não precisa converter o objeto com `JSON.stringify()`.
Comment: Então o arquivo que recebe os dados já estava configurado como vc mencionou. Quanto ao FormData, o erro é exatamente o msm (com ou sem conversão). O engraçado é que olhando os exemplos do pessoal que usa o FormData, nenhum deles faz conversão e pelo que vi, eles não tem esse tipo de erro. O jquery que estou usando é a versão: v1.11.0 e o plugin jquery validade está na versão 1.11.1
Comment: Eu fiz um teste aqui e reparei que os objetos do FormData não são enviados como JSON e sim num formato de texto `Content-Disposition: form-data; name="chave1" Giovanni ...`, e talvez seja este o erro de validação dos dados. Quer que eu edite minha resposta para não usar o FormData?
Comment: Eae, Giovanni. Pode sim mas ainda assim permanece o problema para o envio do arquivo para o upload (input tipo 'file'). É estranho o porque desse erro. Pelos exemplos que vi aqui no site, o pessoal consegue enviar os dados com o FormData sem precisar converter; não sei porque o meu não envia. Agradeço pela ajuda!
Answer: Substitua o trecho submitHandler: function( form ) { ... } por
submitHandler: function( form ) {

    // cria um objeto com os respectivos valores (ao efetuar as solicitações, será convertido)
    // "especialidade=valor&dataConsulta=###[...]""
    let obterDados = {
        "especialidade": $("#especialidade").val(),
        "dataConsulta": $("#dataConsulta").val(),
        "horaConsulta": $("#horaConsulta").val(),
        "imagem": $("input[type=file]")[0].files[0]
    };

    const frmData = new FormData();

    for (let key in obterDados)
        Array.isArray(obterDados[key])
            ? obterDados[key].forEach(value => frmData.append(`${key}[]`, value))
            : frmData.append(key, obterDados[key]);
}

e em $.ajax({ ... }) altere o data: dados por data: frmData
$.ajax({
    type: "POST",
    url: $(form).attr("action"),
    data: frmData, // todo conteúdo armazenado no FormData() inicialmente..
    processData: false,
    contentType: false,
    dataType: "json",
    xhr: function () {
        var myXhr = $.ajaxSettings.xhr();
        if (myXhr.upload) {
            myXhr.upload.addEventListener('progress', function (s) {
                console.log('PROGRESSO', s);
            }, false);
        }
        return myXhr;
    },
})

...

Desta forma poderá enviar Textos e Arquivos e o receptor de dados sendo o php poderá utilizar a variável $_POST["chave-que-deseja"] e a função move_uploaded_file() para receber os respectivos arquivos submitados no formulário.

upload com ajax e formdata exibe erro