Is it possible to make a Poisson Distributions without Poisson Property?

Question: In Poisson Distribution, the amount of time you need to wait for next event does not depend on how much time you have already waited. EX: In Poisson Distribution with parameter lambda, event happens every lambda minutes ... even if have already waited 2 lambda minutes, the event will still be expected to happen lambda minutes from now ... the 2 lambda minutes already waited are not relevant.
Is it possible to make modified Poisson Distribution where the time waited actually has impact on when the event will happen? I think this is more realistic. Ex: Is it possible to do something like:

Between Time = 0 and Time = 5: Event has Poisson( Lambda_1)
Between Time = 5 and Time = 10: Event has Poisson (Lambda_2)
Between Time = 10 and Time = 15: Event has Poisson (Lambda_3)
etc

Here : Lambda_1 > Lambda_2 > Lambda_3 ....
Is it possible to make some modified Poisson Distribution where there is a fluid lambda parameter that changes as time goes on? This will make it so that the probability of event happening increases if an event has not happened in a long time.
Comment: Is this generalization enough for your problem? https://www.probabilitycourse.com/chapter11/11_1_4_nonhomogeneous_poisson_processes.php
Comment: In a Poisson process, the hazard function is constant (equal to the rate of the process), corresponding to an exponential distribution with the same rate.  You can change the hazard function however you wish, but if it is not constant then you get a different process: for example with a hazard function equal to $\frac1{c-t}$ where $t$ is the time since the last arrival, you get a uniform distribution on $[0,c]$ instead of an exponential distribution.
Answer: You are confusing the Poisson distribution with the Poisson process. In the Poisson process the waiting time until the next arrival has a memoryless exponential distribution, which is a continuous distribution, and the number of arrivals during a specificed time interval has a Poisson distribution, which is a discrete distribution.
Often these arrivals get called "events", but I think it is preferable to avoid that word because it is prominently used for a different concept in probability theory. Hence I call them arrivals.
Certainly there are Poisson processes in which the rate of arrivals varies with time.


manipulação de json via linha de comando

Question: Estou utilizando o jq para manipular json via linha de comando.
Tendo como entrada um json obtido via api do gitlab:
[
  {
    "id": 001,
    "description": "Uma descrição teste",
    "ssh_url_to_repo": "firstname.lastname@example.com:shazam/dc.git",
    "created_at": "2019-04-22T19:55:04.851Z",
    "last_activity_at": "2019-04-24T17:09:28.217Z"
  },
  {
    "id": 002,
    "description": "Uma descrição teste",
    "ssh_url_to_repo": "email@example.com:marvel/marvel.git",
    "created_at": "2019-04-22T19:55:04.851Z",
    "last_activity_at": "2019-04-23T17:09:28.217Z"
  },
  {
    "id": 003,
    "description": "Uma descrição teste",
    "ssh_url_to_repo": "email@example.com:one/piece.git",
    "created_at": "2019-04-22T19:55:04.851Z",
    "last_activity_at": "2019-04-22T17:09:28.217Z"
  }
]

Eu rodo o seguinte comando:
if .[].ssh_url_to_repo | contains("one/piece") then .[] | .last_activity_at else false end

E obtenho a seguinte saída:
false
false
"2019-04-24T17:09:28.217Z"
"2019-04-23T17:09:28.217Z"
"2019-04-22T17:09:28.217Z"

Eu queria a data apenas quando ele acha uma ssh que contém a substring one/piece. Porém, quando ele acha essa substring ele imprime a data de todos os objetos.
O que estou fazendo de errado?
Que outra ferramenta, além do jq posso utilizar para manipular json?
Answer: (Testar com o habitual jq 'programa' f.json)
Tenta algo como selecionar os que interessam:
.[] | select(.ssh_url_to_repo | contains("one/piece")).last_activity_at

Outra alternativa seria map(select(cond).campo ):
map(select(.ssh_url_to_repo | contains("one/piece")).last_activity_at)

Para obter os falsos como aparecem na tua versão:
map(if .ssh_url_to_repo | contains("one/piece") then  .last_activity_at else false end)


Como mostrar uma listagem de todos os posts em qualquer página

Question: Estou querendo fazer uma lista para pegar as postagens mais comentadas, mas o meu problema é que eu não consigo chamar a listagem certa sempre, eis o código:

        <?php
            global $query_string;
            query_posts($query_string.'&posts_per_page=-1, post_status=publish');

            if (have_posts()): while (have_posts()): the_post();

            $post_name = get_the_title();
            $post_url  = get_permalink();
        ?>

                <a class="transition-2s" title="<?php $post_name; ?>" href="<?php $post_url; ?>" rel="bookmark">
                    <?php echo $post_name; ?>

        <?php
            endwhile;
            endif;
            wp_reset_query();
        ?>

Na página inicial funciona muito bem, mas em uma página específica, como a de uma postagem por exemplo, esse código só faz a listagem de um único item, que é a do post em questão.
Quero lançar esse código no rodapé, para que sempre apareça, independente da página que o leitor esteja.
Agradeço desde já!
Answer: Tem alguns problemas aqui, no título você diz que quer listar todos, mas na descrição você esta dizendo que quer listar o mais comentários...
Enfim, de qualquer forma isso não vai funcionar porque você esta pegando o $query_string que muda de uma página para outra.
Além que não se deve utilizar query_posts(), basta ler na documentação que o correto é usar pre_get_posts para alterar os loops que já existem e os adicionais devem ser feitos com WP_Query.
Para listar todos você poderia utilizar:

    <?php
        $all_posts_query = new WP_Query( array(
            'nopaging' => true, // deve ser usado no lugar de posts_per_page -1
            'post_status' => 'publish'
        ) );

        if ( $all_posts_query->have_posts() ) :
            while ( $all_posts_query->have_posts() ) :
                $all_posts_query->the_post();
            ?>

                <a class="transition-2s" title="<?php the_title(); ?>" href="<?php the_permalink(); ?>" rel="bookmark">
                    <?php the_title(); ?>

            <?php endwhile;
        endif;
        wp_reset_postdata();
    ?>

É bem simples agora também mudar isso para pegar as postagens mais comentadas, pois basta ordenar pelo número de comentários.

    <?php
        $all_posts_query = new WP_Query( array(
            'nopaging' => true, // deve ser usado no lugar de posts_per_page -1
            'post_status' => 'publish',
            'orderby' => 'comment_count', // Ordena pelos mais comentados
            'order' => 'DESC' // Começa pelos números maiores, exemplo 10, 9, 8...
        ) );

        if ( $all_posts_query->have_posts() ) :
            while ( $all_posts_query->have_posts() ) :
                $all_posts_query->the_post();
            ?>

                <a class="transition-2s" title="<?php the_title(); ?>" href="<?php the_permalink(); ?>" rel="bookmark">
                    <?php the_title(); ?>

            <?php endwhile;
        endif;
        wp_reset_postdata();
    ?>

Bom é isso, agora você consegue fazer as duas consultas.
Entretanto não recomendo sempre carregar todos os posts assim de uma vez, pois se você tiver muitos posts isso vai causar problemas de desempenho.
No caso dos mais comentados eu recomendo usar posts_per_page de 10 ou algo assim.
Comment: Entendo, obrigada pela ajuda! Você tem razão, vou ter graves problemas de desempenho. Eu tava tentando fazer uma gambiarra, mas vai acabar sendo pior. A minha intenção é só a dos mais comentados, mas eu utilizo os comentários do facebook como eu perguntei [nesse post](http://pt.stackoverflow.com/questions/52461/listagem-de-posts-populares-contando-os-coment%C3%A1rios-do-facebook?noredirect=1#comment110681_52461) e me disseram que eu teria que usar o API do facebook, mas como não sei, estava tentando contornar, mas parece que é mais ruim do que bom... De qualquer forma, eu agradeço muito!


Trazer resultados iguais a 0 como valor em branco em uma consulta no SQL Server

Question: Tenho uma consulta abaixo que os registros que não tem nada está vindo com 0. Queria que pudesse vir em branco. Exemplo:
select
F.C37 [Pontuação],
ISNULL(count(distinct TD.UsuIDCliente),'-')   [Qtde_Clientes Detratores],
ISNULL(count(distinct TN.UsuIDCliente),'-')    [Qtde_Clientes Neutro],
ISNULL(count(distinct TP.UsuIDCliente),'-')    [Qtde_Clientes Promotores]
from FRM_8 F
left join Tarefa TD on TD.TarID = F.TarefaID and F.C37 between 0 and 5 AND TD.TarFechamento between '01-07-2017' and '17-08-2017' -- Detratores
left join Tarefa TN on TN.TarID = F.TarefaID and F.C37 between 6 and 8 AND TN.TarFechamento between '01-07-2017' and '17-08-2017' --Neutro
left join Tarefa TP on TP.TarID = F.TarefaID and F.C37 between 9 and 10 AND TP.TarFechamento between '01-07-2017' and '17-08-2017' --Promotores
where
F.C38 is not null and F.C37 is not null
group by F.C37
order by
CASE F.C37 WHEN '1' THEN 0
                    WHEN '2' THEN 1
                    WHEN '3' THEN 2
                    WHEN '4' THEN 3
                    WHEN '5' THEN 4
                    WHEN '6' THEN 5
                    WHEN '7' THEN 6
                    WHEN '8' THEN 7
                    WHEN '9' THEN 8
                    WHEN '10' THEN 9
END

Hoje está vindo dessa maneira:
Pontuacao      Clientes Detratores    Clientes Neutros
4                    0                      2
5                    1                      5
6                    3                      0

Eu quero que em vez de vir 0, venha NULL ou em branco.
Comment: como assim "está vindo com zero"?
Comment: ôpa @rLinhares, editei a pergunta. Abraços
Answer: O problema é que o tipo de retorno esperado na coluna é int.
Você pode retornar null ou converter a coluna para varchar. Segue código de exemplo:
select
c.id,
count(distinct t1.id) as chave1,
count(distinct t2.id) as chave2,
(case count(distinct t3.id) when 0 then null else count(distinct t3.id) end)  as chave3,
(case count(distinct t4.id) when 0 then '---' else cast(count(distinct t4.id) as varchar) end)  as chave4
from chaves c
left outer join tabela t1 on t1.chave = c.id and t1.chave = 1
left outer join tabela t2 on t2.chave = c.id and t2.chave = 2
left outer join tabela t3 on t3.chave = c.id and t3.chave = 3
left outer join tabela t4 on t4.chave = c.id and t4.chave = 4
group by c.id

a coluna 3, exemplifica o retorno do null,
a coluna 4, o retorno convertido para varchar.
Coloquei no SQL Fiddle: http://sqlfiddle.com/#!6/c2cb0/12
Answer: Não sei se você vai achar gambiarra mas pode checar se o retorno é 0 e retornar vazio:
select
F.C37 [Pontuação],
CASE WHEN ISNULL(count(distinct TD.UsuIDCliente),'-') = 0 THEN '' ELSE CONVERT(VARCHAR(15),ISNULL(count(distinct TD.UsuIDCliente),'-')) [Qtde_Clientes Detratores],
CASE WHEN ISNULL(count(distinct TN.UsuIDCliente),'-') = 0 THEN '' ELSE CONVERT(VARCHAR(15),ISNULL(count(distinct TN.UsuIDCliente),'-')) [Qtde_Clientes Neutro],
CASE WHEN ISNULL(count(distinct TP.UsuIDCliente),'-') = 0 THEN '' ELSE CONVERT(VARCHAR(15),ISNULL(count(distinct TP.UsuIDCliente),'-')) [Qtde_Clientes Promotores]

Comment: ainda retornou 0
Comment: @RenanBessa, fiz uma mudança, vê se resolve


openssl giving me errors and apache is not working with https

Question: I try to configure apache-tomcat  with ssl, but find some issues
[root@manage conf]# openssl s_client -state -debug -connect 10.104.1.38:443 -key server.key -cert server.crt
CONNECTED(00000003)
SSL_connect:before/connect initialization
write to 0x80f1e98 [0x811d5e8] (121 bytes => 121 (0x79))
0000 - 80 77 01 03 01 00 4e 00-00 00 20 00 00 39 00 00   .w....N... ..9..
0010 - 38 00 00 35 00 00 16 00-00 13 00 00 0a 07 00 c0   8..5............
0020 - 00 00 33 00 00 32 00 00-2f 03 00 80 00 00 05 00   ..3..2../.......
0030 - 00 04 01 00 80 00 00 15-00 00 12 00 00 09 06 00   ................
0040 - 40 00 00 14 00 00 11 00-00 08 00 00 06 04 00 80   @...............
0050 - 00 00 03 02 00 80 00 00-ff 0a 86 af 23 f2 2f a1   ............#./.
0060 - 4b 2d 9b f3 a9 d9 0e 1b-34 4d 0c e4 1a 06 b6 25   K-......4M.....%
0070 - 76 04 de bd 6f 50 86 a1-9f                        v...oP...
SSL_connect:SSLv2/v3 write client hello A
read from 0x80f1e98 [0x8122b48] (7 bytes => 7 (0x7))
0000 - 3c 21 44 4f 43 54 59                              <!DOCTY
SSL_connect:error in SSLv2/v3 read server hello A
23995:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:588:

here's my apache config
[root@manage extra]# cat httpd-ssl.conf
Listen 443
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl    .crl
SSLPassPhraseDialog  builtin
SSLSessionCache        "shmcb:/usr/local/apache/logs/ssl_scache(512000)"
SSLSessionCacheTimeout  300
SSLMutex  "file:/usr/local/apache/logs/ssl_mutex"

<VirtualHost _default_:443>
ErrorLog "/usr/local/tomcat/logs/error_log"
TransferLog "/usr/local/tomcat/logs/access_log"

        SSLEngine on
        SSLProtocol +SSLv3 +TLSv1
        SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP+SSLv3:

        ServerName          manage.xyz
        DocumentRoot        /usr/local/tomcat/webapps/xyz
        ServerAdmin         email@example.com
        Alias /backup "/var/backupdata/"
        Alias /logbackup "/var/logbackupdata/"
        Alias /autologbackupdata "/var/autologbackupdata/"
        Alias /client "/usr/local/xxxx/clientfiles/"
        Alias /syshealth "/usr/local/tomcat/webapps/xyz/syshealth/"
        Alias /connection "/tmp"
        Alias /cacheimages "/var/cacherrdimages"
        Alias /xyz/images "/usr/local/xxxx/images/"
        Alias /images "/usr/local/xxxx/images/"
        Alias /javaplugin "/usr/local/xxxx/javaplugin/"
        Alias /bandwidthgraph "/var/bandwidthgraphs"
        Alias /usergraph "/var/bandwidthgraphs/userimage"

        JkMount /xyz/servlet/* ajp13
        JkMount /xyz/*.jsp ajp13

SSLCertificateFile "/usr/local/apache/conf/server.crt"
SSLCertificateKeyFile "/usr/local/apache/conf/server.key"
SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0

<FilesMatch "\.(cgi|shtml|phtml|php)$">
    SSLOptions +StdEnvVars
</FilesMatch>
<Directory "/usr/local/apache/cgi-bin">
    SSLOptions +StdEnvVars
</Directory>

BrowserMatch "MSIE [2-5]" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
CustomLog "/usr/local/apache/logs/ssl_request_log" "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

</VirtualHost>

The error_log output
[Tue Aug 05 13:44:03 2014] [info] [client 127.0.0.1] Connection to child 2 established (server manage.xyz:443)
[Tue Aug 05 13:44:03 2014] [info] Seeding PRNG with 136 bytes of entropy
[Tue Aug 05 13:44:03 2014] [debug] ssl_engine_kernel.c(1903): OpenSSL: Handshake: start
[Tue Aug 05 13:44:03 2014] [debug] ssl_engine_kernel.c(1911): OpenSSL: Loop: before/accept initialization
[Tue Aug 05 13:44:03 2014] [debug] ssl_engine_io.c(1939): OpenSSL: read 7/11 bytes from BIO#8136940 [mem: 813dfc0] (BIO dump follows)
[Tue Aug 05 13:44:03 2014] [debug] ssl_engine_io.c(1872): +-------------------------------------------------------------------------+
[Tue Aug 05 13:44:03 2014] [debug] ssl_engine_io.c(1911): | 0000: 15 03 01 00 02 01                                ......           |
[Tue Aug 05 13:44:03 2014] [debug] ssl_engine_io.c(1915): | 0007 - <SPACES/NULS>
[Tue Aug 05 13:44:03 2014] [debug] ssl_engine_io.c(1917): +-------------------------------------------------------------------------+
[Tue Aug 05 13:44:03 2014] [debug] ssl_engine_io.c(1950): OpenSSL: I/O error, 4 bytes expected to read on BIO#8136940 [mem: 813dfc7]
[Tue Aug 05 13:44:03 2014] [debug] ssl_engine_kernel.c(1940): OpenSSL: Exit: error in SSLv2/v3 read client hello A
[Tue Aug 05 13:44:03 2014] [info] [client 127.0.0.1] (70014)End of file found: SSL handshake interrupted by system [Hint: Stop button pressed in browser?!]
[Tue Aug 05 13:44:03 2014] [info] [client 127.0.0.1] Connection closed to child 2 with abortive shutdown (server manage.xyz:443)
[Tue Aug 05 13:45:37 2014] [error] [client 10.104.1.38] Invalid method in request \x80w\x01\x03\x01

and here's the relevant output when I try without the -key and -cert options:
[root@manage extra]# openssl s_client -state -debug -connect 10.104.1.38:443
CONNECTED(00000003)
SSL_connect:before/connect initialization
write to 0x80f0da0 [0x811c4f8] (121 bytes => 121 (0x79))
0000 - 80 77 01 03 01 00 4e 00-00 00 20 00 00 39 00 00   .w....N... ..9..
0010 - 38 00 00 35 00 00 16 00-00 13 00 00 0a 07 00 c0   8..5............
0020 - 00 00 33 00 00 32 00 00-2f 03 00 80 00 00 05 00   ..3..2../.......
0030 - 00 04 01 00 80 00 00 15-00 00 12 00 00 09 06 00   ................
0040 - 40 00 00 14 00 00 11 00-00 08 00 00 06 04 00 80   @...............
0050 - 00 00 03 02 00 80 00 00-ff 10 44 3f 7f e0 41 4d   ..........D?..AM
0060 - fd 08 dd 10 5b bb f7 10-c6 ec cd 59 b8 ff 55 db   ....[......Y..U.
0070 - 70 cd 97 8d af 9d 2a 65-2a                        p.....*e*
SSL_connect:SSLv2/v3 write client hello A
read from 0x80f0da0 [0x8121a58] (7 bytes => 7 (0x7))
0000 - 3c 21 44 4f 43 54 59                              <!DOCTY
SSL_connect:error in SSLv2/v3 read server hello A
32453:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:588:

apache logs for the same time :
[Tue Aug 05 14:23:49 2014] [error] [client 10.104.1.38] Invalid method in request \x80w\x01\x03\x01

access_log
10.104.1.38 - - [05/Aug/2014:14:23:49 -0400] "\x80w\x01\x03\x01" 501 217

Below are the logs when I  restart my Httpd service. No error found I guess.
==> error_log <==
[Tue Aug 05 14:36:44 2014] [info] removed PID file /var/run/httpd.pid (pid=18411)
[Tue Aug 05 14:36:44 2014] [notice] caught SIGTERM, shutting down
[Tue Aug 05 14:37:09 2014] [info] Init: Seeding PRNG with 136 bytes of entropy
[Tue Aug 05 14:37:09 2014] [info] Loading certificate & private key of SSL-aware server
[Tue Aug 05 14:37:09 2014] [debug] ssl_engine_pphrase.c(470): unencrypted RSA private key - pass phrase not required
[Tue Aug 05 14:37:09 2014] [info] Init: Generating temporary RSA private keys (512/1024 bits)
[Tue Aug 05 14:37:09 2014] [info] Init: Generating temporary DH parameters (512/1024 bits)
[Tue Aug 05 14:37:09 2014] [info] Init: Initializing (virtual) servers for SSL
[Tue Aug 05 14:37:09 2014] [info] Configuring server for SSL protocol
[Tue Aug 05 14:37:09 2014] [debug] ssl_engine_init.c(521): Creating new SSL context (protocols: SSLv3, TLSv1)
[Tue Aug 05 14:37:09 2014] [debug] ssl_engine_init.c(759): Configuring permitted SSL ciphers [ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP+SSLv3:]
[Tue Aug 05 14:37:09 2014] [debug] ssl_engine_init.c(890): Configuring RSA server certificate
[Tue Aug 05 14:37:09 2014] [warn] RSA server certificate CommonName (CN) `jat' does NOT match server name!?
[Tue Aug 05 14:37:09 2014] [debug] ssl_engine_init.c(936): Configuring RSA server private key
[Tue Aug 05 14:37:09 2014] [info] mod_ssl/2.2.27 compiled against Server: Apache/2.2.27, Library: OpenSSL/0.9.8e-fips-rhel5
[Tue Aug 05 14:37:09 2014] [warn] No JkShmFile defined in httpd.conf. Using default /usr/local/apache/logs/jk-runtime-status
[Tue Aug 05 14:37:09 2014] [info] Init: Seeding PRNG with 136 bytes of entropy
[Tue Aug 05 14:37:09 2014] [info] Loading certificate & private key of SSL-aware server
[Tue Aug 05 14:37:09 2014] [debug] ssl_engine_pphrase.c(470): unencrypted RSA private key - pass phrase not required
[Tue Aug 05 14:37:09 2014] [info] Init: Generating temporary RSA private keys (512/1024 bits)
[Tue Aug 05 14:37:09 2014] [info] Init: Generating temporary DH parameters (512/1024 bits)
[Tue Aug 05 14:37:09 2014] [debug] ssl_scache_shmcb.c(253): shmcb_init allocated 512000 bytes of shared memory
[Tue Aug 05 14:37:09 2014] [debug] ssl_scache_shmcb.c(272): for 511952 bytes (512000 including header), recommending 32 subcaches, 133 indexes each
[Tue Aug 05 14:37:09 2014] [debug] ssl_scache_shmcb.c(306): shmcb_init_memory choices follow
[Tue Aug 05 14:37:09 2014] [debug] ssl_scache_shmcb.c(308): subcache_num = 32
[Tue Aug 05 14:37:09 2014] [debug] ssl_scache_shmcb.c(310): subcache_size = 15996
[Tue Aug 05 14:37:09 2014] [debug] ssl_scache_shmcb.c(312): subcache_data_offset = 2144
[Tue Aug 05 14:37:09 2014] [debug] ssl_scache_shmcb.c(314): subcache_data_size = 13852
[Tue Aug 05 14:37:09 2014] [debug] ssl_scache_shmcb.c(316): index_num = 133
[Tue Aug 05 14:37:09 2014] [info] Shared memory session cache initialised
[Tue Aug 05 14:37:09 2014] [info] Init: Initializing (virtual) servers for SSL
[Tue Aug 05 14:37:09 2014] [info] Configuring server for SSL protocol
[Tue Aug 05 14:37:09 2014] [debug] ssl_engine_init.c(521): Creating new SSL context (protocols: SSLv3, TLSv1)
[Tue Aug 05 14:37:09 2014] [debug] ssl_engine_init.c(759): Configuring permitted SSL ciphers [ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP+SSLv3:]
[Tue Aug 05 14:37:09 2014] [debug] ssl_engine_init.c(890): Configuring RSA server certificate
[Tue Aug 05 14:37:09 2014] [warn] RSA server certificate CommonName (CN) `jat' does NOT match server name!?
[Tue Aug 05 14:37:09 2014] [debug] ssl_engine_init.c(936): Configuring RSA server private key
[Tue Aug 05 14:37:09 2014] [info] mod_ssl/2.2.27 compiled against Server: Apache/2.2.27, Library: OpenSSL/0.9.8e-fips-rhel5
[Tue Aug 05 14:37:09 2014] [warn] No JkShmFile defined in httpd.conf. Using default /usr/local/apache/logs/jk-runtime-status
[Tue Aug 05 14:37:09 2014] [notice] Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/0.9.8e-fips-rhel5 mod_jk/1.2.40 configured -- resuming normal operations
[Tue Aug 05 14:37:09 2014] [info] Server built: Jun 14 2014 05:04:12
[Tue Aug 05 14:37:09 2014] [debug] prefork.c(1023): AcceptMutex: sysvsem (default: sysvsem)

Comment: Is there any particular reason why you're testing a connection to the server using its own key and certificate (or so I infer from the filenames)?  Do you get any better results from a simple `openssl s_client -state -debug -connect 10.104.1.38:443`?
Comment: with this, I found the same result. actually I am trying to configure apache(2.)-tomcat over HTTPS. with HTTP it works fine,but in HTTPS browser gives error like "Error code: ERR_SSL_PROTOCOL_ERROR" in chrome and "Error code: ssl_error_rx_record_too_long" in mozzila
Comment: *with this, I found the same result* - er, sorry, what?  Do you mean that you got the same result with the command I typed, and if so, could we see that command and the resulting apache logs?
Comment: See,I have attached logs in Question.
Comment: I get exactly the same output from both server and client when I try to connect to a non-SSL service with `openssl s_client`.  At the moment, I'm very supicious that, for whatever reason, SSL is not being enabled on that apache listener.  Could you do a `service httpd restart` (or OS/distro equivalent) and see if apache logs any problems with the key/certificate files at restart time?
Comment: I could not found any error during restart time, just stuck where it goes wrong. without https it just work all fine.
Comment: [root@manage conf]# `telnet 10.104.1.38 443`
Trying 10.104.1.38...
Connected to 10.104.1.38.
Escape character is '^]'.
get /

501 Method Not Implemented

Method Not Implemented
get to /index.html not supported.

Connection closed by foreign host.
Comment: see, telnet is also give me text output, it should not happen ideally.
Comment: Never mind ideally, it should not happen **at all**.  I don't know what to make of the error `RSA server certificate CommonName (CN) 'jat' does NOT match server name!?` though I don't like the look of it, but the long and the short of it is that you don't have SSL enabled on this particular port and address.  Is there any occurrence of a port-443-related statement anywhere else in the configs that might be overriding the config you've shown?
Comment: `RSA server certificate CommonName (CN) 'jat' does NOT match server name!` I have resolved this warning. And I could not found any statement related to 443 in all conf files.
Comment: To be honest, I'm no apache expert.  We've shown that the problem is definitely that apache isn't doing SSL on that address and port.  If I were you I'd now start stripping out all extraneous statements from the config, to see if I could get apache to start serving a single static document via HTTPS; all you really need is `SSLEngine On`, a key and certificate file, and a `DocumentRoot` to serve the file from.  If you do that and you get SSL, then you can start adding your other config back to see what breaks it.  Other than that, I don't have much to suggest; sorry.
Comment: I have used "NameVirtualHost manage.xxx" for domain support, changed it with "NameVirtualHost *:80" and it works fine. thanks for the replies...
Comment: One of us should write that up, so you can accept it as an answer and put this question to bed.  It is very bad form to leave a question permanently unanswered on SF!  Would you like to write it up, or should I?
Comment: OK, you wrote it up (I've tried to improve it a bit), thank you.  In about two days the site should let you accept that answer, by clicking the tick outline next to it.  Once you've done that, your obligations are fulfilled!  Thanks.
Answer: As can be seen from the comments above, the immediate problem was that my service wasn't running under HTTPS, just HTTP.  openssl s_client could therefore not connect to it, as there wasn't any SSL to handshake on.
The underlying problem was in my apache configuration.  Apache 2.2's NameVirtualHost directive does not support an argument, I have changed NameVirtualHost manage.xxx  to NameVirtualHost *:80
and it all works fine
Comment: For posterity: "\x80w\x01\x03\x01" == client attempting to use SSL/TLS when the server isn't configured to do so.


Drupal 8 - some child pages are not visible on particular book using view

Question: I would like to ask for your help as I'm having a trouble in displaying some child pages of a particular Book in Drupal 8 using view. There's a book which displayed all the child pages but there's some book which displayed incomplete child pages and some book, doesn't display the child pages at all.
I created two views, one for the list of all top level book and the other one is for the child pages.
Here's what I have done on view settings:
to display the list of book:
Format: Unformatted list
Show: Fields
Filter Criteria:
  Content Published (=Yes)
  Content: Content type (= Services)
  Book: Depth (= 1)
Sort Criteria: Content: Title (asc)

to display the child pages:
Format: Unformatted list
Show: Fields
Filter Criteria: Content Published (=Yes)
Sort Criteria: Content: Title (asc)
Contextual Filters: (Book Parent) Content: ID
Relationships: Book Parent
Configure Relationship: Book Parent : Required this Relationship

After saving it, I added this to the block layout.
I'm not sure what went wrong on my settings.
Thank you in advance for you help!
Answer: I'm not too experience in Drupal.  But normally I would not use Views for the child pages.  If the book module is enabled, the BOOK NAVIGATION block will be available to list with hierarchy like a table of content.  You can select in the option to display only for book pages under a particular book.  Not sure whether this helps.
Comment: The book navigation displays the child pages in dropdown format only. Am I right? Because what I would like to achieve is a customize layout for child pages. E.g. it should be in Grid format and the image, title, and body will also display. I think this will be doable using views.


How can I list the logged in users with PowerShell?

Question: I'm trying to get a list of the logged on users from PowerShell. Is there a command that returns a list of the logged in users, regardless of whether their session is connected or disconnected? I'm only looking for local sessions, but remote sessions would be nice too.
Comment: There is an answer to a simliar question here: https://stackoverflow.com/questions/23219718/powershell-script-to-see-currently-logged-in-users-domain-and-machine-status
Comment: Also here is great topic about Powershell features. https://powershell.org/2015/08/28/list-users-logged-on-to-your-machines/
Answer: To retrieve local sessions: qwinsta
To retrieve remote sessions: qwinsta /server:servername
Answer: Try following one line to find a list of logged on users.

query user /server:$SERVER
Answer: quser
This gives connected, disconnected, remote and local logins. Simple and easy.
This also helps when you want to logoff sessions using the logoff # where # is the ID of the quser result


Processing several files one-by-one separately by Spark

Question: I need help with implementation one workflow with Apache Spark. My task is in next:

I have several CSV files as source data. Note: these files could has different layout
I have metadata with info how I need parse each file (this is not problem)
Main goal: result is source file with several additional columns. I have to update each source file without joining to one output range. For example: source 10 files -> 10 result files and each result file have data only from corresponding source file.

As I know Spark can open many files by mask:
var source = sc.textFile("/source/data*.gz");

But in this case I can't recognize which line of a file. If I get list of source files and try to process by following scenario:
JavaSparkContext sc = new JavaSparkContext(...);
List<String> files = new ArrayList() //list of source files full name's
for(String f : files)
{
   JavaRDD<String> data = sc.textFile(f);
   //process this file with Spark
   outRdd.coalesce(1, true).saveAsTextFile(f + "_out");
}

But in this case I will processed all files in sequential mode.
My question is next: how I can processed many files in parallel mode?. For example: one file - one executor?
Thank very much for help me!
Answer: Here are the steps

Use sparkcontext.wholeTextFiles("/path/to/folder/containing/all/files")
The above returns an RDD where key is the path of the file, and value is the content of the file
rdd.map(lambda x:x[1]) - this give you an rdd with only file contents
rdd.map(lambda x: customeFunctionToProcessFileContent(x))
since map function works in parallel, any operations you do, would be faster and not sequential - as long as your tasks don't depend on each other, which is the main criteria for parallelism

The above works with default partition though. So you might not get input files count equal to output file count(as output is number of partitions).
You can re-partition the RDD based on count or any other unique value based on your data, so you end up with output files count equal to input count. This approach will have only parallelism but will not have the performance achieved with optimal number of partitions
Comment: Hi Ramzy, Thank for your answer, but I have another query. Method `sparkcontext.wholeTextFiles("/path/to/folder/containing/all/files")` open and read file in memory. As I know most of source files will have ~1-3 million lines but several files can has size up to 2-3 GB. This will works without any memory errors?
Comment: When you use, sc.textFile or sc.wholeTextFiles, the computation is not started yet. It is only when you perform any action the processing starts, and that is based on the default partitions the data set is being divided. You can get the number of partitions by yourRDD.partitions.length and customize as per your need, and also get the yourRDD.count() to get the actual RDD size.
Comment: @Ramzy, wholeTextFiles will create RDD with key of path and value of whole context of file. If some files are 2-3GB there will be clearly a problem(depends on executor memory, but GBs for 1 partition is too much in any case)
Answer: You can open regular java fixed size thread pool(say 10 threads) and submit spark job your saveAsTextFile from Callable/Runnable.
This will submit 10 parallel jobs, and if you have enough resources in your spark cluster - they will be executed in parallel.
Something like following
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;

import com.google.common.collect.Lists;

public class Test {

    public static void main(String[] argv) {
        final JavaSparkContext sc = new JavaSparkContext(...);
        List<String> files = new ArrayList<>(); //list of source files full name's
        ExecutorService pool = Executors.newFixedThreadPool(10);
        List<Future<?>> futures = new ArrayList<>();
        for(final String f : files)
        {
            Future<?> fut = pool.submit(new Runnable() {

                @Override
                public void run() {
                    JavaRDD<String> data = sc.textFile(f);
                    //process this file with Spark
                    outRdd.coalesce(1, true).saveAsTextFile(f + "_out");

                }
            });
            futures.add(fut);

        }
        //waiting for all tasks
        for (Future<?> fut : futures) {
            fut.get();
        }
    }
}

Comment: Thanks, I think that this make sense. I will try this approach.
Comment: May I know how are the tasks defined for a thread and how are they collected and presented. And with this approach, would the parallelism of 10 is achieved? The applications Mapreduce and spark are for parallel processing. Please revisit the basics may be and see if they fit the requirement
Comment: @Yustas, I've added some code that wraps your task in Runnable
Comment: @Ramzy, see and try yourself. This approach working. If you defining spark action from different threads in driver - all those are converted to separate parallel jobs. Parallelilsm will be 10 * number of partitions in each file.
Comment: It is definitely doable. But in the case of threads, how do you set the limits of which files to process and then get the results from them? All these stuff is handled by spark/mapreduce when used properly. If the usage of threads fits your requirement, you are welcome to proceed. I am just trying to understand the process. Thank you
Comment: This approach is still using spark and not implementing adhoc solution using threads. It just submits several spark jobs in parallel
Comment: Hi This code not works. Failed with exception: `Exception in thread "pool-13-thread-1" Exception in thread "pool-13-thread-2" java.lang.Error: org.apache.spark.SparkException: Task not serializable
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1151)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
 at java.lang.Thread.run(Thread.java:745)`


How do I integrate a nodes edit form on a page?

Question: I would like to integrate a nodes edit form on a page. For example, I want to alter the node with ID id equal to 1.
I know there are a lot of ways to achieve this, but I can imagine there is only one right way.
I am having some troubles with my form. After certain time, the edit form shows values from different nodes: some from this, some from the other, etc. I really don't know why.
Comment: What do you mean by _node as form_? Do you mean the edit form for of the existing nodes? Or the create node form to create new nodes?
Comment: edit form of existing node can be found at `node/[nid]/edit` after some time you just redirect user to edit form, will this work ?
Comment: I would like to integrate this form into page, so i have to go another way.
Answer: Use drupal_get_form(NODETYPE . '_node_form', NODEOBJECT); as callback in your custom menu item.
The original node module callback for menu item 'node/%node/edit' is located in the node.pages.inc file:
/**
 * Menu callback; presents the node editing form.
 */
function node_page_edit($node) {
  $type_name = node_type_get_name($node);
  drupal_set_title(t('Edit @type @title', array('@type' => $type_name, '@title' => $node->title)), PASS_THROUGH);
  return drupal_get_form($node->type . '_node_form', $node);
}


What's the meaning of UNICAST-RESPONSE bit set in mDNS response?

Question:
As per Wikipedia, the UNICAST-RESPONSE field is used to minimize unnecessary broadcasts on the network: if the bit is set, responders SHOULD send a directed-unicast response directly to the inquiring node rather than broadcasting the response to the entire network.
What does it mean when it's set in response? Wireshark shows it as Cache flush, what does that mean? I couldn't find any more documentation.
TIA.
Answer: Read the next section on the wikipedia page you link to:

The CACHE-FLUSH bit is used to instruct neighbor nodes that the record should overwrite, rather than be appended onto, any existing cached entries for this RRNAME and RRTYPE.

The bits in the query and reply does not carry the same meaning, even though they may appear at the same position. It's two different message formats, and you can't use either one to infer anything about the other.
The function is further explained in RFC 6762


SSH Prompts for password even though private keys are available, presented to server and known to it

Question: I've got an ubuntu desktop within a VirtualBox machine and I've got a strange behaviour with the openssh server :

when my user is not already connected to the server (first ssh connexion), it prompts for password even though privates keys are availiable (PuTTY + Pagent). After that first connection, if I open a secondary or a third connection it gets connected with the keys.
If I close all connections and open a new one it prompts for the password.
If I have let say 4 open connections and I close the first one (the one that prompted for the password), the fifth connection will be opened with the keys

Anybody already seen this ?
Thanks for the time spent helping
Answer: How is the user's home directory mounted?  It sounds like, for whatever reason, the user's home directory is not available if the user is not logged in, so that sshd can't find the authorized_keys file.
Also, take a look at /var/log/auth.log on the server for any messages.
Update: if it's necessary to do password-less login, you can change the sshd_config file to look for authorzied_keys in a non-encrypted directory.  http://www.openbsd.org/cgi-bin/man.cgi?query=sshd_config&sektion=5
I suppose something like this would work (not tested):
<code>AuthorizedKeysFile /etc/ssh/pubkeys/%u/authorized_keys .ssh/authorized_keys
</code>
That should tell sshd to check for public keys in both the unencrypted location and the encrypted one.  Check the man page for more info.
Comment: Ah, that'd be the cause, then, since sshd can't decrypt the contents of the home directory.
Comment: @kzh: yup, was burnt by that once with Ubuntu Desktop.  Asks if you want to encrypt the home directory (why not?) without mentioning ssh.  I should've put two and two together, but a simple "note: this will effect SSH..." would've been helpful.
Comment: If you don't enter your password, how will your home directory be decrypted when you log in?
Comment: Good idea !! I think the user dir is encrypted so this could be it!
Comment: The user's home directory must be using ecrypt or something like that.
Comment: Good point, Random832.  The OP needs to go play with this.
Comment: "AuthorizedKeysFile" solution seems to work ! Thanks
Comment: @Random832 it's not decrypted, I need to manually ask for decryption & mounting of my home dir. Fortunately I don't need it often so this behavious still fits my usage. (beside, I've decrypted it's content a few days ago since I was not using the encryption feature)


Paradox - What is wrong with this proof that proves a false assertion?

Question: Theorem: Let $a_{n}=a_{n-1}+1, a_1=1$. For any $n$, in order to compute $a_n$, it is necessary to compute $a_i$ for each $i=1,\dots,n-1$, which takes $\Theta(n)$ time.
Proof: This is vacuously true for $n=1$. Assume true for $n=k-1$. Prove true for $n=k$. In order to compute $a_{k-1}+1$, it is necessary to compute $a_{k-1}$. Then since $a_k=a_{k-1}+1$, in order to compute $a_k$, it is necessary to compute $a_{k-1}$. By the induction hypothesis, in order to compute $a_{k-1}$, it is necessary to compute $a_i$ for each $i=1,\dots,k-2$. Hence, in order to compute $a_k$, it is necessary to compute $a_i$ for each $i=1\dots,k-1$. QED
What is wrong with this proof? It seems valid to me, even though the theorem is false.
Comment: Your proof has shown that it is no worse than $\Theta(n)$, but it has not shown that there is no more clever way to compute $a_n$
Comment: Just to be pedantic. The whole point of algorithmic complexity is that there are often many different programs that can compute the same values given the same input. A particular algorithm has a complexity - your algorithm has complexity $O(n)$. But that doesn't mean that every program that computes the same values on the same input is of complexity $O(n)$. The general quesiton of complexity is, "How can I find an algorithm which computes the same thing faster?"
Comment: Reminds me of the "All horses are the same color" paradox - http://en.wikipedia.org/wiki/All_horses_are_the_same_color
Comment: I'd never heard of the "all horses are the same color" paradox until now. That's a good one.
Answer: In your induction step, you made the additional assumption (beyond the inductive hypothesis) that it was necessary to compute $a_{k-1}$ in order to compute $a_k$. That's hardly the case, as simple inspection of the recursive definition gives us the closed-form definition $a_n:=n$ for all $n$.
Comment: **Why** is it necessary to know what $a_{k-1}$ is in order to compute $a_k$? You've not justified this, and you can't, because it isn't true. For example, I can tell you that $a_{1000000}=1000000$ without ever thinking about $a_{999999}$. Your induction step rests on this false assumption, and by assuming that a false statement is true, you allow yourself to draw the false conclusion.
Comment: What you've shown is that your algorithm is $O(n)$, not that any algorithm, when given an input of $n$, computes $a_n$, is $O(n)$. @CraigFeinstein
Comment: You are confusing definition with algorithm. $a_1=1, a_{n+1}=a_n+1$ is a definition of a sequence. It is also an implicit algorithm for computing that sequence, but it is not the only algorithm that computes the $n$th element of that sequence.
Comment: You've shown that the theorem is false. But why is the proof invalid? In order to compute $a_{k-1}+1$, it is certainly necessary to know what $a_{k-1}$ is, so you have to compute it. Then since $a_k=a_{k-1}+1$, in order to compute $a_k$, you have to compute $a_{k-1}$.
Comment: If recursion were the **only way** to determine the values of the various $a_n$, then we *would* need to do an extra computation at each step. It isn't the case here, though.
Comment: OK, that makes sense.
Answer: The fallacy is at a simpler level than anything about algorithms or runtime complexity.   The point is that

a sequence that satisfies one definition can also satisfy many other definitions.

The alternative definitions might include ones that do not use recursion, or are more computationally efficient when converted to an algorithm.  Therefore,

having one definition of a sequence does not indicate its complexity (in any sense of that word), only an upper bound to the complexity.

As an example, the sequence defined recursively by $$a_n = a_{n-1} + a_{n-2} - a_{n-3}$$ for $n>3$ and $a_1=a_2=a_3=1$, is constant.  It takes an exponential number of operations to compute $a_n$ from that recursive definition, but the sequence also be computed from a different definition, $(\forall n )a_n = 1$.
Proving that different definitions specify the same sequence can be more logically complicated than applying either definition alone.  Fermat's Last Theorem can be seen as an alternative definition of the sequence $0,0,0,.\dots$ but the demonstration involved a few thousand pages of theory.


What does a beam with no notes signify? (semiquaver beam in my case)

Question: I have the below measure showing what appears a semiquaver beam for 1 beat without notes in the middle of the bar. What does this mean?
Comment: Thanks it certainly looks like that now that you mention it I had just never seen it so .... long!
Comment: It's because of the 16th notes.
Answer: I'd wager that it's a tremolo in the right hand, between the triad and the single note. But I don't know this particular piece, etc., so I can't be sure.
Comment: Its the 3rd from last bar of Pearl Fishers from Jeffrey Howard's arrangement. Gosh I have never seen a tremolo this stretched out!


UICollectionViewCell created from XIB will cause flickering during drag and drop

Question: I implement a simple drag and drop sample.
import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    private var collectionView: UICollectionView?

    var colors: [UIColor] = [
        .link,
        .systemGreen,
        .systemBlue,
        .red,
        .systemOrange,
        .black,
        .systemPurple,
        .systemYellow,
        .systemPink,
        .link,
        .systemGreen,
        .systemBlue,
        .red,
        .systemOrange,
        .black,
        .systemPurple,
        .systemYellow,
        .systemPink
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: view.frame.size.width/3.2, height: view.frame.size.width/3.2)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)

        //collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")

        let customCollectionViewCellNib = CustomCollectionViewCell.getUINib()
        collectionView?.register(customCollectionViewCellNib, forCellWithReuseIdentifier: "cell")

        collectionView?.delegate = self
        collectionView?.dataSource = self
        collectionView?.backgroundColor = .white
        view.addSubview(collectionView!)

        let gesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture))
        collectionView?.addGestureRecognizer(gesture)
    }

    @objc func handleLongPressGesture(_ gesture: UILongPressGestureRecognizer) {
        guard let collectionView = collectionView else {
            return
        }

        switch gesture.state {
        case .began:
            guard let targetIndexPath = collectionView.indexPathForItem(at: gesture.location(in: self.collectionView)) else {
                return
            }
            collectionView.beginInteractiveMovementForItem(at: targetIndexPath)
        case .changed:
            collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: collectionView))
        case .ended:
            collectionView.endInteractiveMovement()
        default:
            collectionView.cancelInteractiveMovement()
        }
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        collectionView?.frame = view.bounds
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return colors.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

        cell.backgroundColor = colors[indexPath.row]

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.size.width/3.2, height: view.frame.size.width/3.2)
    }

    func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
        return true
    }

    func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let item = colors.remove(at: sourceIndexPath.row)
        colors.insert(item, at: destinationIndexPath.row)
    }
}

However, I notice that, if my UICollectionViewCell is created with XIB, it will randomly exhibit flickering behaviour, during drag and drop.

The CustomCollectionViewCell is a pretty straightforward code.
CustomCollectionViewCell.swift
import UIKit

extension UIView {
    static func instanceFromNib() -> Self {
        return getUINib().instantiate(withOwner: self, options: nil)[0] as! Self
    }

    static func getUINib() -> UINib {
        return UINib(nibName: String(describing: self), bundle: nil)
    }
}

class CustomCollectionViewCell: UICollectionViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

}

Flickering
By using the following code
let customCollectionViewCellNib = CustomCollectionViewCell.getUINib()
collectionView?.register(customCollectionViewCellNib, forCellWithReuseIdentifier: "cell")

It will have the following random flickering behaviour - https://youtu.be/CbcUAHlRJKI

No flickering
However, if the following code is used instead
collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")

Things work fine. There are no flickering behaviour - https://youtu.be/QkV2HlIrXK8

May I know why it is so? How can I avoid the flickering behaviour, when my custom UICollectionView is created from XIB?
Please note that, the flickering behaviour doesn't happen all the time. It happens randomly. It is easier to reproduce the problem using real iPhone device, than simulator.
Here's the complete sample code - https://github.com/yccheok/xib-view-cell-cause-flickering
Answer: While we are rearranging cells in UICollectionView (gesture is active), it handles all of the cell movements for us (without having us to worry about changing dataSource while the rearrange is in flight).
At the end of this rearrange gesture, UICollectionView rightfully expects that we will reflect the change in our dataSource as well which you are doing correctly here.
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let item = colors.remove(at: sourceIndexPath.row)
    colors.insert(item, at: destinationIndexPath.row)
}

Since UICollectionView expects a dataSource update from our side, it performs following steps -

Call our collectionView(_:, moveItemAt:, to:) implementation to provide us a chance to reflect the changes in dataSource.
Call our collectionView(_:, cellForItemAt:) implementation for the destinationIndexPath  value from call #1, to re-create a new cell at that indexPath from scratch.

Okay, but why would it perform step 2 even if this is the correct cell to be at that indexPath?

It's because UICollectionView doesn't know for sure whether you actually made those dataSource changes or not. What happens if you don't make those changes? - now your dataSource & UI are out of sync.
In order to make sure that your dataSource changes are correctly reflected in the UI, it has to do this step.

Now when the cell is being re-created, you sometimes see the flicker. Let the UI reload the first time, put a breakpoint in the cellForItemAt: implementation at the first line and rearrange a cell. Right after rearrange completes, your program will pause at that breakpoint and you can see following on the screen.

Why does it not happen with UICollectionViewCell class (not XIB)?

It does (as noted by others) - it's less frequent. Using the above steps by putting a breakpoint, you can catch it in that state.

How to solve this?

Get a reference to the cell that's currently being dragged.
Return this instance from cellForItemAt: implementation.

var currentlyBeingDraggedCell: UICollectionViewCell?
var willRecreateCellAtDraggedIndexPath: Bool = false
@objc func handleLongPressGesture(_ gesture: UILongPressGestureRecognizer) {
    guard let cv = collectionView else { return }

    let location = gesture.location(in: cv)
    switch gesture.state {
    case .began:
        guard let targetIndexPath = cv.indexPathForItem(at: location) else { return }
        currentlyBeingDraggedCell = cv.cellForItem(at: targetIndexPath)
        cv.beginInteractiveMovementForItem(at: targetIndexPath)

    case .changed:
        cv.updateInteractiveMovementTargetPosition(location)

    case .ended:
        willRecreateCellAtDraggedIndexPath = true
        cv.endInteractiveMovement()

    default:
        cv.cancelInteractiveMovement()
    }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if willRecreateCellAtDraggedIndexPath,
       let currentlyBeingDraggedCell = currentlyBeingDraggedCell {
        self.willRecreateCellAtDraggedIndexPath = false
        self.currentlyBeingDraggedCell = nil
        return currentlyBeingDraggedCell
    }

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

    cell.contentView.backgroundColor = colors[indexPath.item]

    return cell
}

Will this solve the problem 100%?

NO. UICollectionView will still remove the cell from it's view hierarchy and ask us for a new cell - we are just providing it with an existing cell instance (that we know is going to be correct according to our own implementation).
You can still catch it in the state where it disappears from UI before appearing again. However this time there's almost no work to be done, so it will be significantly faster and you will see the flickering less often.

BONUS
iOS 15 seems to be working on similar problems via UICollectionView.reconfigureItems APIs. See an explanation in following Twitter thread.

Whether these improvements will land in rearrange or not, we will have to see.

Other Observations
Your UICollectionViewCell subclass' XIB looks like following

However it should look like following (1st one is missing contentView wrapper, you get this by default when you drag a Collection View Cell to the XIB from the View library OR create a UICollectionViewCell subclass with XIB).

And your implementation uses -
cell.backgroundColor = colors[indexPath.row]

You should use contentView to do all the UI customization, also note the indexPath.item(vs row) that better fits with cellForItemAt: terminology (There are no differences in these values though). cellForRowAt: & indexPath.row are more suited for UITableView instances.
cell.contentView.backgroundColor = colors[indexPath.item]

UPDATE
Should I use this workaround for my app in production?

NO.

As noted by OP in the comments below -

The proposed workaround has 2 shortcomings.
(1) Missing cell
(2) Wrong content cell.
This is clearly visible in https://www.youtube.com/watch?v=uDRgo0Jczuw Even if you perform explicit currentlyBeingDraggedCell.backgroundColor = colors[indexPath.item] within if block, wrong content cell issue is still there.
Comment: After I did some testing, I feel it is Ok to use the default XIB with only safeArea. I guess even if the contentView is not visible in XIB, the components added under safeArea will place in contentView implicit. I confirm my finding, to print out `cell.contentView.subviews.count`.
Comment: Thanks for your suggestion. However, please do note that, the proposed workaround do have 2 shortcomings. (1) Missing cell (2) Wrong content cell. This can shown in https://www.youtube.com/watch?v=uDRgo0Jczuw Even I perform explicit `currentlyBeingDraggedCell.backgroundColor = colors[indexPath.row]` within `if` block, wrong content cell issue still there.
Comment: Thank you for your detailed explanation. However, if I create UICollectionViewCell subclass from XIB, I do not get the "contentView" as shown in https://imgur.com/a/s3olpZ7 . Do you know why?
Comment: @CheokYanCheng You can delete this cell from XIB, manually drag a new `Collection View Cell` from the view library and set it's class to the correct subclass. See this - https://imgur.com/4Yt4GjA
Comment: I never know this till I read on https://developer.apple.com/documentation/uikit/uicollectionviewcell/1620133-contentview . So far, I still not encounter any issue of not using contentView. Do you know why Xcode default XIB creation behaviour doesn't place contentView in UICollectionViewCell?
Comment: To be honest, I'm a bit surprised that `UICollectionViewCell` subclass (when created with XIB) doesn't create the expected `contentView` wrapper in the XIB as intended. You have `contentView` in both `UITableViewCell` & `UICollectionViewCell` sublcasses.
Comment: Thanks. I appreciate that you're informing me regarding the contentView. I will investigate further.
Comment: Well it is what it is - you now have a clear understanding of why it is flickering. This is a workaround and NOT a solution. In fact it creates more issues like you mentioned above. We can't change this behavior in `UICollectionView`. Recreate will happen after drop and it will inconsistently flicker as well. I have provided this information in the **UPDATE** to the answer.
Answer: The flickering is caused by the cell being recreated at its new position. You can try holding to the cell.
(only the relevant code is shown)
// keeps a reference to the cell being dragged
private weak var draggedCell: UICollectionViewCell?
// the flag is set when the dragging completes
private var didInteractiveMovementEnd = false

@objc func handleLongPressGesture(_ gesture: UILongPressGestureRecognizer) {
    switch gesture.state {
    case .began:
        // keep cell reference
        draggedCell = collectionView.cellForItem(at: targetIndexPath)
        collectionView.beginInteractiveMovementForItem(at: targetIndexPath)

    case .ended:
        // reuse the cell in `cellForItem`
        didInteractiveMovementEnd = true
        collectionView.performBatchUpdates {
            collectionView.endInteractiveMovement()
        } completion: { completed in
            self.draggedCell = nil
            self.didInteractiveMovementEnd = false
        }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // reuse the dragged cell
    if didInteractiveMovementEnd, let draggedCell = draggedCell {
        return draggedCell
    }
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    ...
}

Comment: Thanks for your suggestion. However, please do note that, the proposed workaround do have 2 shortcomings. (1) Missing cell (2) Wrong content cell. This can shown in https://www.youtube.com/watch?v=uDRgo0Jczuw Even I perform explicit `draggedCell.backgroundColor = colors[indexPath.row]` within `if` block, wrong content cell issue still there.
Comment: @CheokYanCheng I do not see these issues with the code I've posted. You can update your code repository with your changes for review.


reorder fields on user profile page

Question: I can't find any solution to reorder some fields on user profil pages (like user/%/edit). At first I see User photo and language options. But in field options I have set another fields to be applied to the first position.
I have no possibility to move some fields to wished position.
Have you any advice, how to do it? Thank you very much. Peter.
Answer: You need to go to "Admin > Configuration > People > Account Settings > Manage display". You will be able to reorder the fields from there. If you want to remove some of them from the display, you can select "Hidden" from the menu in the "Format" column.
EDIT:
The profile picture, however, is managed separately by Drupal, not as a field. If you want to be able to manage it, a workaround might be to disable the default Drupal profile picture (Admin > Configuration > People > Accounts > Personalization) and to create a new Image field to display the picture, which you can treat as any other regular field. There are even some modules that create the field for you, like user picture field.
Comment: no, it doesn't work. Some field that can not be deleted, are also can not be reordet. And I see no field, like profile foto, I think it has to be modified via hook.
Comment: @user52660, you are right about the profile picture, I have just edited my answer.
Answer:
Navigate to the Content types page (Administer > Structure > Content
types).
In the table, locate the row that contains your content type and
click the manage fields link.
Locate the field you want to re-order, and drag the four-headed
arrow icon up or down.
Click Save.

When users create an Article, they will now see the Image field displayed immediately after the Title field:

OR
You can do it by editing user-profile.tpl.php
and arrange fields as your requirement like:
 <?php
 print render($user_profile['field_age']);
?>

Comment: yes, but it's not the user profile form - user/%/edit. Here i have some fields, that can not be removed or moved to rigth position.
Comment: i am edit answer check it

reorder fields on user profile page


Desabilitar link no menu de paginação em jQuery

Question: Tenho um plugin de paginação feito em jQuery.
O que não estou conseguindo fazer é quando estiver na última página, o link que dá acesso a próxima página seja desabilitado e o usuário não consiga clicar mais.
Da mesma maneira o botão de dá acesso a página anterior.
Já segui algumas dicas, como inserir "disable" mas isso não funciona. Some a "mãozinha" no link mas dá para clicar ainda.
O método a seguir foi criado para customizar os dois link's
<code>function tagNextPrev() {
        if($nav_panels.children('.last').hasClass('active_page')){
            $nav_panels.children('.next_link').add('.last_link').removeClass('.next_link').addClass('no_more');
        } else {
            $nav_panels.children('.no_more').add('.last_link').removeClass('no_more');
        }

        if($nav_panels.children('.first').hasClass('active_page')){
            $nav_panels.children('.previous_link').add('.first_link').addClass('no_more');
        } else {
            $nav_panels.children('.previous_link').add('.first_link').removeClass('no_more');
        }
    }
</code>
Answer: Você pode usar pointer-events para impedir o clic nos elementos que tiverem essa classe. Assim na sua classe use:
<code>.no_more{
    pointer-events: none;
}
</code>
Pode lêr aqui sobre mais variantes, mas penso que CSS é a melhor, ainda que só funcione em browsers mais modernos:
Como impedir um click sobre um link/âncora ou elemento com evento amarrado
Comment: Muito Obrigado, funcionou perfeitamente.


Does the "Pythagorean Theorem" have a person-neutral alternate title

Question: The "Pythagorean Theorem" is a well-known theorem connecting the lengths of the legs of a right triangle to the length of said triangle's hypotenuse. The title above, which is the name I've almost always read, is named after the Greek philosopher Pythagoras. But other people around the world for millennia have also discovered that relation. Is "Pythagorean Theorem" the official name, or is there another official title that doesn't use the name of any of the discoverers?
Comment: Wikipedia is a good place to start with questions like this. There is also a [History of Science and Mathematics Stackexchange](https://hsm.stackexchange.com/).
Comment: You might be interested in [this blog post](https://mathwithbaddrawings.com/2019/04/17/lets-rename-the-pythagorean-theorem/) by Ben Orlin, which lists many suggestions for renamings (some more serious than others). As far as I know, though, none are standard, and certainly none are as standard as "Pythagorean Theorem" or "Gougu Theorem" (as mentioned in John's answer). The first option is "The Three Squares Theorem", which I quite like.
Comment: IMHO, this kind of issues are not worth the time spent on them. On the contrary, the essential fact is that people agree all over the world on this naming. Why should we torn down this unity ? Of course, you can decide to call whatever you want ; for example you can call it  "Pont aux Anes" ("Donkey's bridge") which was a famous french surname or Gougu theorem or 3 squares theorem, it's your right. Will you be followed ?
Comment: Knowing the relation is not nearly as impressive as PROVING the relation. the Pythagoreans were the first to prove it, that we know of. that is why the theorem bears their name.
Comment: In the [link](https://mathwithbaddrawings.com/2019/04/17/lets-rename-the-pythagorean-theorem/) given by HallaSurvior, one of Ben Orlin's suggestion is to rename it to "Babylonian Theorem" because it was discovered centuries before Pythagoras. This is another nice example of the [Arnold principle](https://mathoverflow.net/q/66075/340165). I agree however with @JeanMarie that it could be hard to convince the rest of the world about renamings.
Answer: Certain right triangle lengths (like 3-4-5) were known by the Babylonians and others in ancient times, but the Pythagoreans were the ones to prove it is true for ALL right triangles.  It's also called the Gougu theorem but I'm not aware of a name that doesn't include a person.
Comment: From [Wikipedia](https://en.wikipedia.org/wiki/Zhoubi_Suanjing#Contents) and [another page in zh Wikipedia](https://zh.wikipedia.org/zh-hk/勾股定理#普遍定理的发现), and what I remembered, in a right-angled triangle, 勾/"gou" in Mandarin is one of the short sides and 股/"gu" in Mandarin is the other short side, so gougu theorem doesn't include a person.
Answer: "Gougu theorem" is a "person-neutral alternate title", but not sure if it's an internationally "official title".
From Wikipedia and another page in zh Wikipedia, in a right-angled triangle, 勾/"gou" in Mandarin is one of the short sides and 股/"gu" in Mandarin is the other short side, so gougu theorem doesn't include a person.
(Editing an ephemeral and temporary comment into an answer.)

Does the “Pythagorean Theorem” have a person-neutral alternate title


Views exposed filter: Upcoming/Past events

Question: I want to implement an exposed filter in the view with a date field. I want to show two choice in select list according to the date value (upcoming events/past events). But I don't know how to achieve this using date field because it allows to choose date only.
Is there any way to achieve this feature?
Thank you in advance.
Answer: Add a date filter.
Expose the date filter.
Select the grouped filters option

Scroll down and define your filters as shown in next image

And you are good to go. You will have an output like this

You can change the options to make it a drop-down too.
To fix for the UI bug in exposed filters groups:
Make sure your date module is at Version: 7.x-2.9 or later, then apply the patch exposed_grouped_filter-1876168-71.patch (https://www.drupal.org/node/1876168#comment-10344663)
Comment: I am also using the same version but I am having problem in UI. Screenshot: https://skydrive.live.com/?cid=cf1e32c5f0c9e63a&id=CF1E32C5F0C9E63A!217#cid=CF1E32C5F0C9E63A&id=CF1E32C5F0C9E63A!218
Comment: From the operator dropdown select less than or greater than options, and then add the labels accordingly. That should work.
Comment: I had the same problem in UI.
After a lot of attempts tried to save the grouped filter as following:
1. Created the view filter and saved with the 3 initial group items with random labels (as those cannot be removed in first save).
2. Removed the group items in next save and added one with relative value now.
3. Saved the view.
4. Added the 2nd group item to the filter. The relative date input still does not appear but for some reason it took the value now.
5. Saved the view.

More saves of view or re-edits in filter may be needed in between.
Comment: Thank you Gokul.
Can I ask you a question? Which version of views are you working on because I have option to select date and relative date but no place to input the value.
Comment: I am using Views 7.x-3.5
Comment: If this does not work for you, try either to display the hidden relative day input with your browser developer tools or to export the view and manually edit the relative date value.
Comment: Works on Drupal 9
Answer: Remove the 3 default options (hit "Remove" link) and add them manually by using the button "Add another item".
The new options will now display the field for relative date.
Hope that helps
Best
EDIT: that seemed to work but actually not... Sorry


Proof - Subsets of disjoint open sets are separated

Question: Let $A$ and $B$ be nonempty subsets of R. Show that if there exist disjoint open sets $U$ and $V$ with $A\subseteq U$ and $B\subseteq V$, then $A$ and $B$ are separated.
Proof:
We will first show that $U$ and $V$ are separated by contradiction. Assume the two sets are not separated, then (without loss of generality) $\overline{U}\cap V$ is nonempty. Take L to be the set of limit points of $U$, since $U$ and $V$ are disjoint but $\overline{U}\cap V=(U\cup L)\cap V=(V\cap U)\cup(V\cap L)=\emptyset\cup(V\cap L)=V\cap L\neq\emptyset$, there must exist some element $a\in L,a\in V$. Because $a$ is a limit point of $U$, we know that every $V_\epsilon(a)$ intersects U at some point other than $a$. We also know that V is an open set with $a\in V$, which means that there exists an $V_{\epsilon_1}(a)\subseteq V$. However, we also know that there exists some point $V_\epsilon(a),b\in V_{\epsilon_1}(a)\rightarrow b\in V,b\in U\rightarrow V\cap U\neq\emptyset$. However, this contradicts our original assumption that V and U are disjoint, which means V and U must be separated sets.
Now to prove that $A$ and $B$ are separated. We know that (without loss of generality) $U\cap\overline{V}=\emptyset$, and that if L is a subset of limit points, $B\cup L_B\subset V\cup L_V\rightarrow \overline{B}\subseteq\overline{V}$, taken together with the fact that $A\subseteq U$, we get that $A\cup\overline{B}\subseteq U\cup\overline{V}=\emptyset\rightarrow A\cup\overline{B}=\emptyset$, thus A and B are separated.
I think this proof is complete and correct but I just want to make sure. I also know I took  $B\cup L_B\subset V\cup L_V\rightarrow \overline{B}\subseteq\overline{V}$ without proof but I'm not too sure how to go about proving that.
Answer: You've far overcomplicated the proof. It's as simple as this.
$A\cap\overline B\subset U\cap \overline V=\varnothing$, where the equality holds because $$\overline V=\bigcap\limits_{C\text{ open}\\V\cap C=\varnothing}\mathbb R\setminus C\subset\mathbb R\setminus U$$A parallel argument shows that $\overline A\cap B=\varnothing$. Thus, $A,B$ are separated.


Proof of the Local Convergence Theorem (for fixed points).

Question: The Theorem says:
Let $g,g'$ be continuous functions in the neighbourhood of an isolated fixed point $x_*=g(x_*)$. If $|g'(x_*)|<1$ then there is an interval $L=[x_*-\delta,x_*+\delta]$ such that $x_{k+1}=g(x_k)$ convergces to $x_*$ whenever $x_0\in L$.
The proof goes:
By continuity of $g'$ there exists some interval $L=[x_*-\delta,x_*+\delta]$ with $\delta>0$ such that $|g'(x)|\leq M$ for $M<1^{(1)}$. Not let $x\in L$. It follows that:
$$
|x_*-g(x)|=|g(x_*)-g(x)|\leq^{(2)}M|x_* - x|<|x_* -x|\leq \delta
$$
so $g(x)\in L$. Hence g is a contraction mapping on $L$ and the contracting mapping theorem (Banach fixed point theorem) shows that $x_k \rightarrow x$.
Now I have two questions about this proof:
(1) Why does this sentence hold? I know the theorem of Maxima and Minima for continuous functions and that they are bounded on a closed intervall but isn't this the other way around when we define a boundary and then say that a continuous function stays in this boundary on a certain (small enough) intervall? I cannot remember a theorem about that.
(2) This is the part I don't understand at all, why does this inequality hold? I guess it is a combination of $|g'(x)|\leq M$ and $|g'(x_*)|<1$, but how does one show this inequality formaly?
Appreciate your help and stay safe!
Answer: $(1)$:
$g'$ is continuous at $x_*$, then $\forall \epsilon > 0, \exists \hat{\delta} >0, |x-x_*|< \hat{\delta} \implies |g'(x)-g'(x_*)| < \epsilon$.
Note that if $|g'(x)-g'(x_*)|<\epsilon$ then we have $|g'(x)|<|g'(x_*)|+\epsilon$
Let $\epsilon = \frac{1-|g'(x_*)|}2>0$, then we have $|g'(x)|<|g'(x_*)|+\frac{1-|g'(x_*)|}{2} =\frac{1+|g'(x_*)|}2<1$.
Hence by the definition of continuity of $g'$ at $x_*$, we found an interval
$\forall x \in (x_*-\hat{\delta}, x_*+\hat{\delta}),|g'(x)|<\frac{1+|g'(x_*)|}2$
We can let $\delta = \frac{\hat{\delta}}2$ and $M=\frac{1+|g'(x_*)|}2$, then we have found an interval $L=[x_*-\delta, x_*+\delta]$  such that $|g'(x)|\le M<1$.
$(2)$:
We can use the mean value theorem, for any $x \in L$, we have
$$|g(x_*)-g(x)|=|g'(\zeta_x)||x_*-x|$$
where $\zeta_x$ lies between $x_*$ and $x$, hence $\zeta_x \in L$. Hence from part $(1)$, we know that $|g'(\zeta_x)|\le M$
$$|g(x_*)-g(x)|=|g'(\zeta_x)||x_*-x| \le M |x_*-x|$$


How can I open large files over HTTP with PHP, then display in the browser for viewing?

Question: I have a tomcat server (Server A) which has a ton of progressively streaming encoded mp4 video and mp3 audio files and is on a private network. I also have a web server (Server B) running Apache 2 and PHP which is on the private network and has a public facing interface. Server B manages application ACL.
I want a client (say a browser) to be able to go to a specific url on Server B's public interface, and be able to download, (listen or view in a player) the media from the private server. At the moment, on server B, I have tried the following:
<?php
$handler = fopen('http://server_a/path/to/file.mp4', 'r');
header('Content-type: video/mp4');
while (!feof($handler)) {
    print fread($handler, 8192);
}
exit;

and
<?php
$handler = fopen('http://server_a/path/to/file.mp4', 'r');
header('Content-type: video/mp4');
print stream_get_contents($handler);
exit;

and
<?php
$handler = fopen('http://server_a/path/to/file.mp4', 'r');
header('Content-type: video/mp4');
fpassthru($handler);
exit;

All of which PHP will either run out of memory or the client (browser) will download the entire file before even beginning to play. Am I going the wrong way about this? Any ideas on what I could be doing wrong?
Answer: No, that's the way it works. Basically your php is showing the file as a file. Your PHP script is going from "I'm not an HTML file, I'm an MP4 File, and here's my contents". PHP is not what you want for streaming
Why not try using HTML5 Video or Audio, pointing to your PHP script?
Comment: I am not sure I understand your suggestion. I am using Video.js and/or jPlayer in the browser. They point to the PHP script on Server B. However, they download the entire video before playing it. Or, if the video is large, the PHP memory on server B becomes exhausted. The PHP memory used is set to 512MB currently for debugging, still cant even play a 400MB video.
Answer: The first and third option should not run out of memory, however, I would suggest to set up a proxy on server B for a particular path (e.g. /path/to/videos/).
http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypass
I'm not sure whether it will honour partial content requests, something you will have to figure out.
Secondly, there are two things that could explain why the browser has to download the whole file before playback:

the file is not optimized for web streaming; you can use MP4Box to optimize it (i.e. bring the meta data headers to the front of the file)
the file size is unkown; using either the aforementioned proxy or PHP's header() that can be resolved.
Answer: Flush buffers on your loop!!!
function flush_buffers(){
   ob_end_flush();
   ob_flush();
   flush();
   ob_start();
}


Importação circular

Question: A doc do Flask, apesar de usar nos seus exemplos, alerta ao final da página sobre a má prática de se usar importações circulares.
Outra coisa que me incomoda é criar "objetos globais" dentro de um arquivo __init__.py.
Qual seria a outra solução?
Arquivo __init__.py do módulo principal, ou seja, a pasta principal da aplicação:
from flask import Flask
app = Flask(__name__)

import yourapplication.views

O arquivo views.py (A view da aplicação):
from yourapplication import app

@app.route('/')
def index():
    return 'Hello World!'

A estrutura do projeto:
/yourapplication
    setup.py
    /yourapplication
        __init__.py
        views.py
        /static
            style.css
        /templates
            layout.html
            index.html
            login.html
            ...

Créditos do código de exemplo: http://flask.pocoo.org/docs/1.0/patterns/packages/#simple-packages
Comment: E por quê o objeto `app` **precisa** ser definido em `__init__.py`?
Comment: Também queria saber. Estou começando no desenvolvimento de Flask. Olhando rápido me parece que é pelo fato de que o `__init__.py` é chamado no momento que o módulo é importado ai o objeto seria criado.
Answer: Bem, o flask tem a intenção de ser completamente modularizado e livre para que você se sinta à vontade de definir a melhor estrutura. Uma das boas práticas do framework é trabalhar com a chamada "Application factory", ou "Fábrica de aplicações" (http://flask.pocoo.org/docs/1.0/tutorial/factory/).
Quando você cria uma "app factory", você não precisa ter objetos globais e todo o processo de configuração e inicializações são efetuadas dentro da função da fábrica de app. Por exemplo:
def create_app(test_config=None):

    # cria e configura a aplicacao
    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object(DevelopmentConfig)

    from .blueprint_um import views
    app.register_blueprint(views.bp)

    db.init_app(app)
    CORS(app)

    return app

Nesse exemplo eu crio uma fábrica com a função create_app e faço todas as minhas inicializações necessárias, incluindo o registro das minhas blueprints, que é muito importante. Esta função pode estar dentro de __init__.py que está dentro do pacote de aplicação principal do seu projeto. Esta é uma prática importante para que você consiga importar a sua função de criação do app sem dificuldades. Por exemplo, ao utilizar o waitress para rodar sua aplicação, basta executar
    waitress-serve --call --listen=0.0.0.0:5000 app:create_app
para que o waitress entenda que dentro do seu pacote app existe uma função create_app que pode ser chamada.
Enfim, existem muitas maneiras diferentes de fazer isso e é por isso que o flask é tão legal. Não deixa de conferir a documentação e implementações diferentes para que vocês conheça as possibilidades (eu também estou aprendendo muito ainda sobre o flask). Tenho um projetinho pequeno disponível lá no gitlab, se quiser pode dar uma olhada e até melhorar alguma coisa (tem muito a ser melhorado) https://gitlab.com/cavalcantigor/my-flaskr

Importação circular


Issues with Working and Activating Multiple Workbooks excel VBA

Question: I'm having some issues when working with calling and working with multiple workbooks.  I have a macro that updates some excel sheets using some data.  All 5 of those spreadsheets are assigned a variable with the filename and the file path. When I run a second SUB / Macri to Save and Close all 5 of those workbooks after they are done updating - It doesn't select the right workbooks even though they've been assigned the same variable names as the previous macro.  So I believe my issue is - If the workbooks are already open I can't associate a variable too them.  - I assume that if the file name and file path are right, the workbooks open can be set as variables and then be able to close them - Thoughts?
    Sub CloseWorkbooks()

    Dim MB, WB1, WB2, WB3, WB4, WB5 As Workbook
    Dim FP1, FN1, FN2, FN3, FN4, FN5 As String

    FP1 = "G:\DATA......"

        FN5 = "Book1.xlsx"
        FN2 = "Book2.xlsx"
        FN3 = "Book3.xlsx"
        FN4 = "Book4.xlsx"
        FN1 = "Book5.xlsx"

        Application.DisplayAlerts = False

            Set WB1 = Workbooks.Open(Filename:=FP1 & FN1)
            WB1.Activate
            WB1.Save

            'Application.Wait (Now + TimeValue("00:00:05"))
            WB1.Close

                Set WB2 = Workbooks.Open(Filename:=FP1 & FN2)
                WB2.Activate
                WB2.Save
                'Application.Wait (Now + TimeValue("00:00:05"))
                WB2.Close

                    Set WB3 = Workbooks.Open(Filename:=FP1 & FN3)
                    WB3.Activate
                    WB3.Save
                    Application.Wait (Now + TimeValue("00:00:02"))
                    WB3.Close

                        Set WB4 = Workbooks.Open(Filename:=FP1 & FN4)
                        WB4.Activate
                        WB4.Save
                        Application.Wait (Now + TimeValue("00:00:02"))
                        WB4.Close

                            Set WB5 = Workbooks.Open(Filename:=FP1 & FN5)
                            WB5.Activate
                            WB5.Save
                            Application.Wait (Now + TimeValue("00:00:02"))
                            WB5.Close

End Sub

This works if the worksheets are NOT Open, but it doesn't work if the worksheets are open - which is what I want it to accomplish.  The previous macro opens all the worksheets and updates them.  I want this macro (2nd one shown above) to save and close all the workbooks.
-Thank you.
Comment: Are the workbooks open when you run this code?
Answer: If you replace your Workbooks.Open(...) with a call to this it should return the workbook if its open, and open and return it if it is not.
Public Function getWorkbookByFileName(ByVal FileName As String) As Workbook
Dim Book As Workbook: Set Book = Nothing
Dim Count As Integer: Count = Application.Workbooks.Count
Dim Index As Integer: Index = 1
Do
    If Application.Workbooks(Index).FullName = FileName Then
        Set Book = Application.Workbooks(Index)
        Exit Do
    End If
    If Index < Count Then
        Index = Index + 1
    Else
        Exit Do
    End If
Loop
If Book Is Nothing Then
    Set Book = Application.Workbooks.Open(FileName:=FileName)
End If
Set getWorkbookByFileName = Book
End Function

This is fairly long winded, looking at some of the answers to Detect whether Excel workbook is already open I see that it can be achieved without looping through the workbooks.
Answer: This will close the correct workbook.
Sub CloseWorkbooks()
    Application.DisplayAlerts = False

    Dim wb As Workbook
    Dim i As Long

    For i = 1 To 6
        Set wb = Workbooks.Open(Filename:="G:\DATA......Book" & i & ".xlsx")
        Application.Wait (Now + TimeValue("00:00:02"))
        wb.Close SaveChanges:=True
    Next i
Exit Sub


Running two PHP versions (5.3 & 5.2) at the same time

Question: I have read this topic: Running php4 and php5 along side each other
There, the issue is handling two different generations of PHP (PHP 4 vs PHP 5), but what I need is to make all but one of my server accounts work under 5.3 and just a single domain under 5.2.
I cannot make this through Apache models, and the answer from https://stackoverflow.com/questions/524508/how-can-one-run-multiple-versions-of-php-5-x-on-a-development-lamp-server does not apply since in my case I can't use a different port - this is a regular website  on the same server.
Comment: Why do you need two different PHP versions on a single website?
Comment: Can you use one PHP version via CGI?
Comment: i need to have tow versions of php for intsall  osdate 2.5
Comment: Serious deployments (a.k.a. not-PHP applications) quite often require different versions of interpreter and libraries in a shared hosting configuration, nothing weird.
Answer: You can still use the answer in https://stackoverflow.com/questions/524508/how-can-one-run-multiple-versions-of-php-5-x-on-a-development-lamp-server; you just need to add a way to redirect that traffic to the other port. Here's how:
You set up a separate apache instance with PHP 5.2, and you set it to listen to port 8080.
On your regular apache, you change the VirtualHost for that one domain so that it now contains a reverse proxy to the 5.2 apache. Example:
<VirtualHost *:80>
   Servername php52.example.com
   ProxyPass / http://yourservername.example.com:8080/
   ProxyPassReverse / http://yourservername.example.com/
</VirtualHost>

That way, your original apache instance will accept all traffic to all websites on your server. But requests to this one particular domain will be transparently forwarded to the other instance without the user on the other side of the browser knowing it.
Comment: Will be WP (wordpress) work in such case?
Comment: I see no reason why it shouldn't.
Comment: WP is very sensitive to changing of url, even port name. If you change url from site.example.com to site.example.com:8080 the WP wouldn't work. Other the most common CMS like - Drupal, Joomla, Magento is less sensitive, as far as I know
Comment: Given that, I can make no guarantees - but the point here is that you should *not* change the URL; the proxy setup is specifically so you can keep the old URL even though the server is in fact running on another port. But we're now getting onto a territory that I'm less familiar with.
Answer: There is a way to achieve this on a per-directory basis. You do find contradicting opinions on the web, but I have been able to make it work.
First, you must organize to have your different versions of PHP ready to run as CGI or fastCGI extentions. I use fastCGI in the example below
You will need to set up two separate php.ini files (and yes, maintaining them in sync where it matters can be a pain, but the alternative is to have only one php.ini file for 2 different versions of PHP & that's either impossible or full of loopholes)
Place those php.ini files in the directory of your PHP code, modules, etc. one for each version. This is where PHP will go look for them first, absent the PHPRC environment variable. You should not set the PHPRC variable, unless you discover how to make it different for 2 different fastCGI stubs, I have not been able to:  the Apache FcgidInitialEnv directive works only globally, not on a per-directory basis, and the FcgidCmdOptions which is supposed to does not work at all.
Then, all you have to do is to add the following code in you httpd.conf file:
#
# start PHP as FastCGId
#

LoadModule fcgid_module modules/mod_fcgid.so

#
# PHP 7.0 is the default
# PHP 5.2 is the legacy
#

<Files ~ "\.php$>"
  AddHandler fcgid-script .php
  FcgidWrapper "c:/WebServers/PHP-7.0.5/php-cgi.exe" .php
</Files>

#
# Keep PHP 5.2 for legacy Drupal sites
#
<DirectoryMatch "Puitscarre|Royale$">

  <Files ~ "\.php$>"
    AddHandler fcgid-script .php
    FcgidWrapper "c:/WebServers/PHP-5.2.39/php-cgi.exe" .php
  </Files>

</DirectoryMatch>

It works perfectly on my environment: Windows 7, Apache 2.2. And, by the way, the code that is in the Directory environment above also works if you put it in the .htaccess file of the directories which need a specific or legacy version of PHP
Enjoy !
Answer: I just used cgi for such case
<VirtualHost *:80>
    Servername site.example.net
    ScriptAlias /php-fastcgi/ /usr/local/php-5.2.17/bin/

    AddHandler php-fastcgi .php
    AddType application/x-httpd-php .php
    Action php-fastcgi /php-fastcgi/php-cgi
...
</VirtualHost>


Unable to get Wacom events from /dev/input/event*

Question: I have created a pygtk program to monitor the keyboard status and mouse clicks across any application (i.e. not just for my application). This uses evdev by Micah Dowty which basically monitors /dev/input/event* for output and decodes the information in a way that I can display the information to the user.
The program works perfectly for USB keyboards and mice, but doesn't work for a USB Wacom (nor serial Wacom), even when running as root.  I don't get any events for coming out of any of the /dev/input/* nodes for the Wacom as use it.  It's not just my Wacom, but also they guys from the podcast "Meet the Gimp" (Rolf and Philippe) don't get anything as well.
The code lives at http://code.google.com/p/key-mon.
To test, you can run something like:
sudo ./evdev.py /dev/input/event0

You should see events coming out for whatever is connected to event0 as you move the mouse or click the keyboard, for example.
Comment: It's possible that with the Wacom, the X driver is grabbing the input device for exclusive use (with the `EVIOCGRAB` ioctl).
Comment: Could it be that the original evdev code wasn't meant for catching wacom devices? Aren't these also registering their own nodes directly under /Dev/ oder /dev/wacom/ ? (Haven't got a Linux at work to check it, sorry)
Comment: No, it *should* work the way Scott is trying.  Does `wacdump` work?
Comment: I suspect that as well. When I try EVIOCGRAB myself it fails.
Comment: Since this program is used for screencasts for usually one program (ex. Gimp, or Inkscape).  Might it be possible to run that program from within my keyboard monitor program and get the events somehow via pyGTK ?
Comment: Hmm, I wouldn't have thought of it, but... it may be possible to write a Gtk module to intercept input; http://chipx86.github.com/gtkparasite/ already has all the pokey bits down.
Answer: This is due to X that take the full control of your input device, you can't read event yourself. You might have one of theses 2 issues :

A "catchall" is actually getting your device.
In your /var/log/Xorg.0.log, you should see a line like :
Stantum MTP USB Controller: Applying InputClass "evdev touchscreen catchall"
But for wacom of course. If it's true, you can disable the "touchscreen" catchall by editing your /usr/share/X11/xorg.conf.d/10-evdev.conf, and remove the section that talking about touchscreen.
Maybe you'll fit in the Wacom section, so edit the /usr/share/X11/xorg.conf.d/50-wacom.conf, and remove appropriate section that can match your device.

Of course, both of the issue is not resolved in a clean manner, and you can't have X and Kernel event working at the same time. (I never found a solution with Wacom, if anybody have, please share !)


SQL 2008 Central Management Server

Question: Is there a way to register a server to your CMS and use SQL Authentication?
Answer: No, you can't use SQL authentication with the CMS.  It's Windows authentication only.  It doesn't store any authentication data inside the CMS - it's only a list of registered servers.
Comment: and no possible workaround?
Comment: Yeah, sadly no.  Same problem with multiple domains without a trust between 'em too.
Comment: found this connect item, can we get people to vote?

https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=381185
Answer: When you register your CMS there's a drop down with Authentication. Change that to SQL Server Authentication (if I'm understanding you correctly)
Comment: thanks, but that is just for the connection to the CMS. I am looking to register instances to the CMS, and the option for authentication is disabled. i tried an import/export, but the option was changed (and disabled) upon import.
Comment: and how the hell do you have 186 points and three badges already? where have i been?

SQL 2008 Central Management Server


Are there any other settings besides php.ini to allow file upload?

Question: I have a problem with drupal upload file (core module) bigger than 1 MB. For images smaller than this, the upload run smoothly, the progress bar correctly shows the progress and when completed it display the uploaded images as expected.
However, when I tried to upload image bigger than 900 kb, the problem start to arise. The throbber progress indicator show progress until about 98% and then restart again from 0% and never completed and stuck.
In Firebugs it shows that the request was aborted when the progress reach 94%-98% depending on the size images I uploaded. And it only happend when the file > about 900 kB and never for smaller images.
I already changed the php.ini as suggested here and I verified through phpinfo() it is correct setting. I also change the max_input_time and max_execution_time in httpd.conf
In fact, when uploading images, I monitor temporary folder /tmp and it shows temporary file progressing from 0 to the size of the file and restarting from 0 again. Thus, it indeed receive the file, no issue on the size of the file.
I also check the permission, 777 on /tmp and 755 on default/files and it is no problem as I can easily upload 500kb images.
Can anyone help? is there any other settings in the server I have to look into?
Thanks
Answer: Please read through this documentation:
https://www.drupal.org/node/97193
Depending on your HTML form and server configuration if you have a 1MB filesize limit; uploaded files close to your maximum filesize may not successfully upload to a webserver because a file is sent as apart of a multi-part HTTP transmission.
You want to assure post_max_size is typicaly 2x or 3x larger than your upload_max_filesize. Brief discussion on this can be found here:
https://stackoverflow.com/a/15077229/1491507
Googling PHP maximum post size and file sizes should lead to similar documentation on php.net and other resources.
Comment: thank you @tenken, That's exactly what I followed and I can confirm that in phpinfo() it shows correct setting as suggested. I even try to create small php upload program on http://ping.rustamaji.net/uploadtest.html and i can upload about 4 MB file successfully although the browser shows connection was reset
Answer: After some experiments, I conclude that the problem is not on the server side, but rather on my client and LAN. Apparently using proxy server (I use ClearOS) as gateway server, to access server that is the cause the problem.
By turning off proxy (squid), accessing directly internet, the problem immediately dissapear. But the problem remains if we are behind proxy server.


ASP.NET Dropdownlist: value of ddl.text becomes the value of ddl.selectedvalue in selectedindexchanged

Question: ASP.NET 4.0 & SQL 2008
I would like to ask for help in my coding, I don't know what's wrong or what am I missing.
What I want to do is when I select an item in dropdownlist, it will give me the ID (ddlSchool.selectedvalue) and the value of the text (ddlSchool.text).
Below is the code that populates the dropdownlist. I'm getting the value of ID and Text from the database, it works perfectly fine; When I debug it, it gives the correct value of the ID (newItem.Value = .dr("fnorglevelid")) and the correct value of Text (newItem.Text = .dr("fcorgcode").ToString()
    Protected Sub populateDDLDepartment()

    If Not IsPostBack Then
        Dim newItem As New ListItem()
        newItem.Text = "Select a Department..."
        newItem.Value = "0"
        ddlSchool.Items.Add(newItem)

        Try
            With connSchool
               .conn = New SqlConnection(.strCNN_ADMtoGRAD) : .conn.Open()
               .strSQL = "select fnorglevelid, rtrim(fcorganization) as 'fcorgcode'"& _
                            "from hris_organization " & _
                            "where flschool = 1 " & _
                            "order by fcorgcode asc"
               .cmd = New SqlCommand(.strSQL, .conn)
               .dr = .cmd.ExecuteReader()

                While .dr.Read
                    newItem = New ListItem()
                    newItem.Text = .dr("fcorgcode").ToString()
                    newItem.Value = .dr("fnorglevelid")
                    ddlSchool.Items.Add(newItem)
                End While

            End With
        Finally
            With connSchool
                .conn.Close()
                .conn = Nothing
                .strSQL = vbNullString
                .strSQL = Nothing
                .cmd.Dispose()
                .cmd = Nothing
                .dr = Nothing
            End With
        End Try
    End If
End Sub

But when I select an item, the value of ddlSchool.text becomes the same as the value of ddlSchool.selectedValue. I put it in the message box first:
    Protected Sub ddlSchool_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlSchool.SelectedIndexChanged
         MsgBox("Text:" & ddlSchool.Text & "   ID:" & ddlSchool.SelectedValue)
    End Sub

What am I missing? What do I have to do? It seems that selectedValue is the same as Text.
Comment: can you try ddlSchool.SelectedItem.Text
Comment: THANK YOU VERY MUCH! It works. OMG that was dumb of me *facepalm*

:D
Comment: no problem glad to help :), please mark felix's answer as correct cause it has the same asnwer
Comment: Research dropdownlist datasource, databind, datavalefield and datatextfield.
Answer: You can use
Value
ddlSchool.SelectedValue

or
ddlSchool.Text

Text
ddlSchool.SelectedItem.Text for

thank you